From reid at x10sys.com Mon Aug 7 00:20:19 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 00:20:19 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Unix/Path.inc Message-ID: <200608070520.k775KIV2005942@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Unix: Path.inc updated: 1.50 -> 1.51 --- Log message: Add a note about how the "isFile" check in Path::eraseFromDisk prevents the erasure of non-file paths like /dev/null. --- Diffs of the changes: (+0 -0) 0 files changed From reid at x10sys.com Mon Aug 7 00:34:22 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 00:34:22 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Unix/Signals.inc Message-ID: <200608070534.k775YM1P006141@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Unix: Signals.inc updated: 1.12 -> 1.13 --- Log message: Make the removal of files use Path::eraseFromDisk just like it does for the removal of directories. Using std::remove is indiscriminate and can lead to the removal of things like /dev/null if run as root. The Path::eraseFromDisk method ensures that we only ever remove regular files or directories, but never character or block special nodes. This should clear up the problem with usage like: llvm-as -o /dev/null which is used in the llvm-test makefiles. --- Diffs of the changes: (+0 -0) 0 files changed From reid at x10sys.com Mon Aug 7 00:36:38 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 00:36:38 -0500 Subject: [llvm-commits] CVS: llvm/lib/System/Unix/Signals.inc Message-ID: <200608070536.k775ac5V006182@zion.cs.uiuc.edu> Changes in directory llvm/lib/System/Unix: Signals.inc updated: 1.13 -> 1.14 --- Log message: Remove extraneous #include. --- Diffs of the changes: (+0 -0) 0 files changed From lattner at cs.uiuc.edu Mon Aug 7 00:45:48 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 00:45:48 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/ADT/SmallVector.h Message-ID: <200608070545.k775jmUK006416@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/ADT: SmallVector.h updated: 1.4 -> 1.5 --- Log message: Add a clear method to SmallVector --- Diffs of the changes: (+0 -0) 0 files changed From evan.cheng at apple.com Mon Aug 7 16:02:55 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 16:02:55 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/X86/X86RegisterInfo.td Message-ID: <200608072102.k77L2tTK015719@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/X86: X86RegisterInfo.td updated: 1.36 -> 1.37 --- Log message: Make XMM, FP register dwarf register numbers consistent with gcc. --- Diffs of the changes: (+24 -24) X86RegisterInfo.td | 48 ++++++++++++++++++++++++------------------------ 1 files changed, 24 insertions(+), 24 deletions(-) Index: llvm/lib/Target/X86/X86RegisterInfo.td diff -u llvm/lib/Target/X86/X86RegisterInfo.td:1.36 llvm/lib/Target/X86/X86RegisterInfo.td:1.37 --- llvm/lib/Target/X86/X86RegisterInfo.td:1.36 Thu Aug 3 12:27:09 2006 +++ llvm/lib/Target/X86/X86RegisterInfo.td Mon Aug 7 16:02:39 2006 @@ -54,14 +54,14 @@ def BH : RegisterGroup<"BH", [BX,EBX]>, DwarfRegNum<3>; // MMX Registers. These are actually aliased to ST0 .. ST7 - def MM0 : Register<"MM0">, DwarfRegNum<41>; - def MM1 : Register<"MM1">, DwarfRegNum<42>; - def MM2 : Register<"MM2">, DwarfRegNum<43>; - def MM3 : Register<"MM3">, DwarfRegNum<44>; - def MM4 : Register<"MM4">, DwarfRegNum<45>; - def MM5 : Register<"MM5">, DwarfRegNum<46>; - def MM6 : Register<"MM6">, DwarfRegNum<47>; - def MM7 : Register<"MM7">, DwarfRegNum<48>; + def MM0 : Register<"MM0">, DwarfRegNum<29>; + def MM1 : Register<"MM1">, DwarfRegNum<30>; + def MM2 : Register<"MM2">, DwarfRegNum<31>; + def MM3 : Register<"MM3">, DwarfRegNum<32>; + def MM4 : Register<"MM4">, DwarfRegNum<33>; + def MM5 : Register<"MM5">, DwarfRegNum<34>; + def MM6 : Register<"MM6">, DwarfRegNum<35>; + def MM7 : Register<"MM7">, DwarfRegNum<36>; // Pseudo Floating Point registers def FP0 : Register<"FP0">, DwarfRegNum<-1>; @@ -73,24 +73,24 @@ def FP6 : Register<"FP6">, DwarfRegNum<-1>; // XMM Registers, used by the various SSE instruction set extensions - def XMM0: Register<"XMM0">, DwarfRegNum<32>; - def XMM1: Register<"XMM1">, DwarfRegNum<33>; - def XMM2: Register<"XMM2">, DwarfRegNum<34>; - def XMM3: Register<"XMM3">, DwarfRegNum<35>; - def XMM4: Register<"XMM4">, DwarfRegNum<36>; - def XMM5: Register<"XMM5">, DwarfRegNum<37>; - def XMM6: Register<"XMM6">, DwarfRegNum<38>; - def XMM7: Register<"XMM7">, DwarfRegNum<39>; + def XMM0: Register<"XMM0">, DwarfRegNum<21>; + def XMM1: Register<"XMM1">, DwarfRegNum<22>; + def XMM2: Register<"XMM2">, DwarfRegNum<23>; + def XMM3: Register<"XMM3">, DwarfRegNum<24>; + def XMM4: Register<"XMM4">, DwarfRegNum<25>; + def XMM5: Register<"XMM5">, DwarfRegNum<26>; + def XMM6: Register<"XMM6">, DwarfRegNum<27>; + def XMM7: Register<"XMM7">, DwarfRegNum<28>; // Floating point stack registers - def ST0 : Register<"ST(0)">, DwarfRegNum<16>; - def ST1 : Register<"ST(1)">, DwarfRegNum<17>; - def ST2 : Register<"ST(2)">, DwarfRegNum<18>; - def ST3 : Register<"ST(3)">, DwarfRegNum<19>; - def ST4 : Register<"ST(4)">, DwarfRegNum<20>; - def ST5 : Register<"ST(5)">, DwarfRegNum<21>; - def ST6 : Register<"ST(6)">, DwarfRegNum<22>; - def ST7 : Register<"ST(7)">, DwarfRegNum<23>; + def ST0 : Register<"ST(0)">, DwarfRegNum<11>; + def ST1 : Register<"ST(1)">, DwarfRegNum<12>; + def ST2 : Register<"ST(2)">, DwarfRegNum<13>; + def ST3 : Register<"ST(3)">, DwarfRegNum<14>; + def ST4 : Register<"ST(4)">, DwarfRegNum<15>; + def ST5 : Register<"ST(5)">, DwarfRegNum<16>; + def ST6 : Register<"ST(6)">, DwarfRegNum<17>; + def ST7 : Register<"ST(7)">, DwarfRegNum<18>; } //===----------------------------------------------------------------------===// From lattner at cs.uiuc.edu Mon Aug 7 16:19:42 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 16:19:42 -0500 Subject: [llvm-commits] CVS: llvm-test/MultiSource/Applications/hexxagon/bitboard64.h Message-ID: <200608072119.k77LJgpt019851@zion.cs.uiuc.edu> Changes in directory llvm-test/MultiSource/Applications/hexxagon: bitboard64.h updated: 1.3 -> 1.4 --- Log message: Fix PR873: http://llvm.org/PR873 : nonportable code in hexxagon. Reported by Nick Lewycky --- Diffs of the changes: (+1 -1) bitboard64.h | 2 +- 1 files changed, 1 insertion(+), 1 deletion(-) Index: llvm-test/MultiSource/Applications/hexxagon/bitboard64.h diff -u llvm-test/MultiSource/Applications/hexxagon/bitboard64.h:1.3 llvm-test/MultiSource/Applications/hexxagon/bitboard64.h:1.4 --- llvm-test/MultiSource/Applications/hexxagon/bitboard64.h:1.3 Wed Oct 26 10:06:47 2005 +++ llvm-test/MultiSource/Applications/hexxagon/bitboard64.h Mon Aug 7 16:19:26 2006 @@ -44,7 +44,7 @@ BitBoard64 operator=(const BitBoard64 &right); BitBoard64 operator~(void); - BitBoard64::operator bool(); + operator bool(); void print(void); From evan.cheng at apple.com Mon Aug 7 17:12:29 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:12:29 -0500 Subject: [llvm-commits] CVS: llvm/lib/CodeGen/SelectionDAG/ScheduleDAG.cpp Message-ID: <200608072212.k77MCTJd004164@zion.cs.uiuc.edu> Changes in directory llvm/lib/CodeGen/SelectionDAG: ScheduleDAG.cpp updated: 1.99 -> 1.100 --- Log message: Reverse the FlaggedNodes after scanning up for flagged preds or else the order would be reversed. --- Diffs of the changes: (+10 -5) ScheduleDAG.cpp | 15 ++++++++++----- 1 files changed, 10 insertions(+), 5 deletions(-) Index: llvm/lib/CodeGen/SelectionDAG/ScheduleDAG.cpp diff -u llvm/lib/CodeGen/SelectionDAG/ScheduleDAG.cpp:1.99 llvm/lib/CodeGen/SelectionDAG/ScheduleDAG.cpp:1.100 --- llvm/lib/CodeGen/SelectionDAG/ScheduleDAG.cpp:1.99 Fri Jul 21 15:57:35 2006 +++ llvm/lib/CodeGen/SelectionDAG/ScheduleDAG.cpp Mon Aug 7 17:12:12 2006 @@ -55,11 +55,16 @@ // Scan up, adding flagged preds to FlaggedNodes. SDNode *N = NI; - while (N->getNumOperands() && - N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) { - N = N->getOperand(N->getNumOperands()-1).Val; - NodeSUnit->FlaggedNodes.push_back(N); - SUnitMap[N] = NodeSUnit; + if (N->getNumOperands() && + N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) { + do { + N = N->getOperand(N->getNumOperands()-1).Val; + NodeSUnit->FlaggedNodes.push_back(N); + SUnitMap[N] = NodeSUnit; + } while (N->getNumOperands() && + N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag); + std::reverse(NodeSUnit->FlaggedNodes.begin(), + NodeSUnit->FlaggedNodes.end()); } // Scan down, adding this node and any flagged succs to FlaggedNodes if they From evan.cheng at apple.com Mon Aug 7 17:13:44 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:13:44 -0500 Subject: [llvm-commits] CVS: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp Message-ID: <200608072213.k77MDihW005149@zion.cs.uiuc.edu> Changes in directory llvm/lib/CodeGen/SelectionDAG: SelectionDAG.cpp updated: 1.317 -> 1.318 --- Log message: Clear TopOrder before assigning topological order. Some clean ups. --- Diffs of the changes: (+3 -1) SelectionDAG.cpp | 4 +++- 1 files changed, 3 insertions(+), 1 deletion(-) Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp diff -u llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.317 llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.318 --- llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.317 Fri Aug 4 12:45:20 2006 +++ llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp Mon Aug 7 17:13:29 2006 @@ -474,6 +474,7 @@ if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag && !N->isTargetOpcode()) { N->dump(); + std::cerr << "\n"; assert(0 && "Node is not in map!"); } #endif @@ -2497,7 +2498,7 @@ return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; } -// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. +/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. /// This can cause recursive merging of nodes in the DAG. /// /// This version assumes From/To have a single result value. @@ -2711,6 +2712,7 @@ Sources.push_back(N); } + TopOrder.clear(); while (!Sources.empty()) { SDNode *N = Sources.back(); Sources.pop_back(); From evan.cheng at apple.com Mon Aug 7 17:16:23 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:16:23 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/CodeGen/SelectionDAGISel.h Message-ID: <200608072216.k77MGN4c007514@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/CodeGen: SelectionDAGISel.h updated: 1.23 -> 1.24 --- Log message: Move DAGSize to SelectionDAGISel; it's used in tablegen'd isel code. --- Diffs of the changes: (+7 -2) SelectionDAGISel.h | 9 +++++++-- 1 files changed, 7 insertions(+), 2 deletions(-) Index: llvm/include/llvm/CodeGen/SelectionDAGISel.h diff -u llvm/include/llvm/CodeGen/SelectionDAGISel.h:1.23 llvm/include/llvm/CodeGen/SelectionDAGISel.h:1.24 --- llvm/include/llvm/CodeGen/SelectionDAGISel.h:1.23 Tue Aug 1 14:14:14 2006 +++ llvm/include/llvm/CodeGen/SelectionDAGISel.h Mon Aug 7 17:16:08 2006 @@ -17,10 +17,10 @@ #include "llvm/Pass.h" #include "llvm/Constant.h" +#include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/SelectionDAGNodes.h" namespace llvm { - class SelectionDAG; class SelectionDAGLowering; class SDOperand; class SSARegMap; @@ -39,8 +39,10 @@ SSARegMap *RegMap; SelectionDAG *CurDAG; MachineBasicBlock *BB; + std::vector TopOrder; + unsigned DAGSize; - SelectionDAGISel(TargetLowering &tli) : TLI(tli), JT(0,0,0,0) {} + SelectionDAGISel(TargetLowering &tli) : TLI(tli), DAGSize(0), JT(0,0,0,0) {} TargetLowering &getTargetLowering() { return TLI; } @@ -52,6 +54,9 @@ virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {} virtual void InstructionSelectBasicBlock(SelectionDAG &SD) = 0; + virtual void SelectRootInit() { + DAGSize = CurDAG->AssignTopologicalOrder(TopOrder); + } /// SelectInlineAsmMemoryOperand - Select the specified address as a target /// addressing mode, according to the specified constraint code. If this does From evan.cheng at apple.com Mon Aug 7 17:18:12 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:18:12 -0500 Subject: [llvm-commits] CVS: llvm/utils/TableGen/DAGISelEmitter.cpp DAGISelEmitter.h Message-ID: <200608072218.k77MICkQ009949@zion.cs.uiuc.edu> Changes in directory llvm/utils/TableGen: DAGISelEmitter.cpp updated: 1.236 -> 1.237 DAGISelEmitter.h updated: 1.66 -> 1.67 --- Log message: Making TableGen'd instruction selection code non-recursive. This fixes PR805: http://llvm.org/PR805 . --- Diffs of the changes: (+123 -246) DAGISelEmitter.cpp | 366 +++++++++++++++++------------------------------------ DAGISelEmitter.h | 3 2 files changed, 123 insertions(+), 246 deletions(-) Index: llvm/utils/TableGen/DAGISelEmitter.cpp diff -u llvm/utils/TableGen/DAGISelEmitter.cpp:1.236 llvm/utils/TableGen/DAGISelEmitter.cpp:1.237 --- llvm/utils/TableGen/DAGISelEmitter.cpp:1.236 Wed Aug 2 19:42:26 2006 +++ llvm/utils/TableGen/DAGISelEmitter.cpp Mon Aug 7 17:17:58 2006 @@ -2134,7 +2134,6 @@ std::vector &TargetVTs; std::string ChainName; - bool DoReplace; unsigned TmpNo; unsigned OpcNo; unsigned VTNo; @@ -2165,11 +2164,10 @@ std::vector > &gc, std::set > &gd, std::vector &to, - std::vector &tv, - bool dorep) + std::vector &tv) : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr), GeneratedCode(gc), GeneratedDecl(gd), TargetOpcodes(to), TargetVTs(tv), - DoReplace(dorep), TmpNo(0), OpcNo(0), VTNo(0) {} + TmpNo(0), OpcNo(0), VTNo(0) {} /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo /// if the match fails. At this point, we already know that the opcode for N @@ -2236,7 +2234,6 @@ bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE); bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE); bool EmittedUseCheck = false; - bool EmittedSlctedCheck = false; if (HasChain) { if (NodeHasChain) OpNo = 1; @@ -2245,13 +2242,6 @@ // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); EmittedUseCheck = true; - // hasOneUse() check is not strong enough. If the original node has - // already been selected, it may have been replaced with another. - for (unsigned j = 0; j != CInfo.getNumResults(); j++) - emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + - "))"); - - EmittedSlctedCheck = true; if (NodeHasChain) { // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node // has a chain use. @@ -2320,12 +2310,6 @@ // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); } - if (!EmittedSlctedCheck) - // hasOneUse() check is not strong enough. If the original node has - // already been selected, it may have been replaced with another. - for (unsigned j = 0; j < CInfo.getNumResults(); j++) - emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + - "))"); } for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) { @@ -2489,7 +2473,7 @@ for (unsigned i = 0; i < NumRes; ++i) { emitDecl("Tmp" + utostr(i+ResNo)); - emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" + + emitCode("AddToQueue(Tmp" + utostr(i+ResNo) + ", CPTmp" + utostr(i+ResNo) + ");"); } @@ -2501,12 +2485,12 @@ if (LikeLeaf) emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";"); else { - emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");"); - } - - if (isRoot && N->isLeaf()) { - emitCode("Result = Tmp" + utostr(ResNo) + ";"); - emitCode("return;"); + emitCode("AddToQueue(Tmp" + utostr(ResNo) + ", " + Val + ");"); + if (isRoot && N->isLeaf()) { + emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); + emitCode("Result = Tmp" + utostr(ResNo) + ";"); + emitCode("return;"); + } } } // Add Tmp to VariableMap, so that we don't multiply select this @@ -2620,12 +2604,12 @@ // Emit all the chain and CopyToReg stuff. bool ChainEmitted = NodeHasChain; if (NodeHasChain) - emitCode("Select(" + ChainName + ", " + ChainName + ");"); + emitCode("AddToQueue(" + ChainName + ", " + ChainName + ");"); if (NodeHasInFlag || HasImpInputs) EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true); if (NodeHasOptInFlag) { emitCode("if (HasInFlag)"); - emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));"); + emitCode(" AddToQueue(InFlag, N.getOperand(N.getNumOperands()-1));"); } unsigned NumResults = Inst.getNumResults(); @@ -2677,7 +2661,7 @@ emitCode("for (unsigned i = 2, e = N.getNumOperands(); " "i != e; ++i) {"); emitCode(" SDOperand VarOp(0, 0);"); - emitCode(" Select(VarOp, N.getOperand(i));"); + emitCode(" AddToQueue(VarOp, N.getOperand(i));"); emitCode(" Ops.push_back(VarOp);"); emitCode("}"); } @@ -2720,50 +2704,35 @@ return std::make_pair(1, ResNo); for (unsigned i = 0; i < NumResults; i++) - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + - utostr(i) + ", ResNode, " + utostr(i) + ");"); + emitCode("ReplaceUses(SDOperand(N.Val, " + + utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));"); if (NodeHasOutFlag) emitCode("InFlag = SDOperand(ResNode, " + utostr(NumResults + (unsigned)NodeHasChain) + ");"); if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) { - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " - "0, ResNode, 0);"); + emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));"); NumResults = 1; } - if (InputHasChain) { - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + - utostr(PatResults) + ", " + ChainName + ".Val, " + - ChainName + ".ResNo" + ");"); - if (DoReplace) - emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " + - utostr(PatResults) + ", " + ChainName + ".Val, " + - ChainName + ".ResNo" + ");"); - } + if (InputHasChain) + emitCode("ReplaceUses(SDOperand(N.Val, " + + utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, " + + ChainName + ".ResNo" + "));"); if (FoldedChains.size() > 0) { std::string Code; for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " + + emitCode("ReplaceUses(SDOperand(" + FoldedChains[j].first + ".Val, " + - utostr(FoldedChains[j].second) + ", ResNode, " + - utostr(NumResults) + ");"); - - for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) { - std::string Code = - FoldedChains[j].first + ".Val, " + - utostr(FoldedChains[j].second) + ", "; - emitCode("AddHandleReplacement(" + Code + "ResNode, " + - utostr(NumResults) + ");"); - } + utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " + + utostr(NumResults) + "));"); } if (NodeHasOutFlag) - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + - utostr(PatResults + (unsigned)InputHasChain) + - ", InFlag.Val, InFlag.ResNo);"); + emitCode("ReplaceUses(SDOperand(N.Val, " + + utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);"); // User does not expect the instruction would produce a chain! bool AddedChain = NodeHasChain && !InputHasChain; @@ -2820,8 +2789,7 @@ if (NodeHasInFlag || HasImpInputs) Code += ", InFlag"; emitCode(Code + ");"); - emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo" - ", ResNode, 0);"); + emitCode(" ReplaceUses(N, SDOperand(ResNode, 0));"); emitCode(" Result = SDOperand(ResNode, 0);"); emitCode("}"); } @@ -2839,9 +2807,7 @@ emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName() + "(Tmp" + utostr(OpVal) + ".Val);"); if (isRoot) { - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val," - "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" + - utostr(ResNo) + ".ResNo);"); + emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); emitCode("Result = Tmp" + utostr(ResNo) + ";"); emitCode("return;"); } @@ -2905,7 +2871,7 @@ if (RR->isSubClassOf("Register")) { MVT::ValueType RVT = getRegisterValueType(RR, T); if (RVT == MVT::Flag) { - emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");"); + emitCode("AddToQueue(InFlag, " + RootName + utostr(OpNo) + ");"); } else { if (!ChainEmitted) { emitDecl("Chain"); @@ -2913,7 +2879,7 @@ ChainName = "Chain"; ChainEmitted = true; } - emitCode("Select(" + RootName + utostr(OpNo) + ", " + + emitCode("AddToQueue(" + RootName + utostr(OpNo) + ", " + RootName + utostr(OpNo) + ");"); emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName + ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) + @@ -2928,7 +2894,7 @@ } if (HasInFlag) - emitCode("Select(InFlag, " + RootName + + emitCode("AddToQueue(InFlag, " + RootName + ".getOperand(" + utostr(OpNo) + "));"); } @@ -2974,13 +2940,11 @@ std::vector > &GeneratedCode, std::set > &GeneratedDecl, std::vector &TargetOpcodes, - std::vector &TargetVTs, - bool DoReplace) { + std::vector &TargetVTs) { PatternCodeEmitter Emitter(*this, Pattern.getPredicates(), Pattern.getSrcPattern(), Pattern.getDstPattern(), GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs, - DoReplace); + TargetOpcodes, TargetVTs); // Emit the matcher, capturing named arguments in VariableMap. bool FoundChain = false; @@ -3107,7 +3071,9 @@ OS << std::string(Indent, ' ') << "// Pattern complexity = " << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity << " cost = " - << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n"; + << getResultPatternCost(Pattern.getDstPattern(), *this) + << " size = " + << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n"; } EmitPatterns(Other, Indent, OS); return; @@ -3219,9 +3185,6 @@ E = PatternsByOpcode.end(); PBOI != E; ++PBOI) { const std::string &OpName = PBOI->first->getName(); const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first); - bool OptSlctOrder = - (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) && - OpcodeInfo.getNumResults() > 0); std::vector &PatternsOfOp = PBOI->second; assert(!PatternsOfOp.empty() && "No patterns but map has entry?"); @@ -3269,7 +3232,7 @@ std::vector TargetOpcodes; std::vector TargetVTs; GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs, OptSlctOrder); + TargetOpcodes, TargetVTs); for (std::set >::iterator si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) AllGenDecls.insert(*si); @@ -3400,19 +3363,6 @@ OS << "void Select_" << OpName << (OpVTStr != "" ? "_" : "") << OpVTStr << "(SDOperand &Result, const SDOperand &N) {\n"; - if (OptSlctOrder) { - OS << " if (N.ResNo == " << OpcodeInfo.getNumResults() - << " && N.getValue(0).hasOneUse()) {\n" - << " SDOperand Dummy = " - << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " - << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, " - << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" - << " Result = Dummy;\n" - << " return;\n" - << " }\n"; - } // Print all declarations. for (std::set >::iterator @@ -3462,17 +3412,17 @@ // Emit boilerplate. OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n" << " std::vector Ops(N.Val->op_begin(), N.Val->op_end());\n" - << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n" + << " AddToQueue(Ops[0], N.getOperand(0)); // Select the chain.\n\n" << " // Select the flag operand.\n" << " if (Ops.back().getValueType() == MVT::Flag)\n" - << " Select(Ops.back(), Ops.back());\n" + << " AddToQueue(Ops.back(), Ops.back());\n" << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n" << " std::vector VTs;\n" << " VTs.push_back(MVT::Other);\n" << " VTs.push_back(MVT::Flag);\n" << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n" + << " ReplaceUses(SDOperand(N.Val, 0), New);\n" + << " ReplaceUses(SDOperand(N.Val, 1), SDOperand(New.Val, 1));\n" << " Result = New.getValue(N.ResNo);\n" << " return;\n" << "}\n\n"; @@ -3485,11 +3435,6 @@ << " Result = N;\n" << " return; // Already selected.\n" << " }\n\n" - << " std::map::iterator CGMI = CodeGenMap.find(N);\n" - << " if (CGMI != CodeGenMap.end()) {\n" - << " Result = CGMI->second;\n" - << " return;\n" - << " }\n\n" << " switch (N.getOpcode()) {\n" << " default: break;\n" << " case ISD::EntryToken: // These leaves remain the same.\n" @@ -3506,96 +3451,18 @@ << " }\n" << " case ISD::AssertSext:\n" << " case ISD::AssertZext: {\n" - << " SDOperand Tmp0;\n" - << " Select(Tmp0, N.getOperand(0));\n" - << " if (!N.Val->hasOneUse())\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " - << "Tmp0.Val, Tmp0.ResNo);\n" - << " Result = Tmp0;\n" + << " AddToQueue(Result, N.getOperand(0));\n" + << " ReplaceUses(N, Result);\n" << " return;\n" << " }\n" << " case ISD::TokenFactor:\n" - << " if (N.getNumOperands() == 2) {\n" - << " SDOperand Op0, Op1;\n" - << " Select(Op0, N.getOperand(0));\n" - << " Select(Op1, N.getOperand(1));\n" - << " Result = \n" - << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " - << "Result.Val, Result.ResNo);\n" - << " } else {\n" - << " std::vector Ops;\n" - << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" - << " SDOperand Val;\n" - << " Select(Val, N.getOperand(i));\n" - << " Ops.push_back(Val);\n" - << " }\n" - << " Result = \n" - << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " - << "Result.Val, Result.ResNo);\n" - << " }\n" - << " return;\n" - << " case ISD::CopyFromReg: {\n" - << " SDOperand Chain;\n" - << " Select(Chain, N.getOperand(0));\n" - << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" - << " MVT::ValueType VT = N.Val->getValueType(0);\n" - << " if (N.Val->getNumValues() == 2) {\n" - << " if (Chain == N.getOperand(0)) {\n" - << " Result = N; // No change\n" - << " return;\n" - << " }\n" - << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "New.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " - << "New.Val, 1);\n" - << " Result = New.getValue(N.ResNo);\n" - << " return;\n" - << " } else {\n" - << " SDOperand Flag;\n" - << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n" - << " if (Chain == N.getOperand(0) &&\n" - << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n" - << " Result = N; // No change\n" - << " return;\n" - << " }\n" - << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "New.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " - << "New.Val, 1);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, " - << "New.Val, 2);\n" - << " Result = New.getValue(N.ResNo);\n" - << " return;\n" - << " }\n" - << " }\n" + << " case ISD::CopyFromReg:\n" << " case ISD::CopyToReg: {\n" - << " SDOperand Chain;\n" - << " Select(Chain, N.getOperand(0));\n" - << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" - << " SDOperand Val;\n" - << " Select(Val, N.getOperand(2));\n" - << " Result = N;\n" - << " if (N.Val->getNumValues() == 1) {\n" - << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n" - << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "Result.Val, 0);\n" - << " } else {\n" - << " SDOperand Flag(0, 0);\n" - << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n" - << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n" - << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n" - << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "Result.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " - << "Result.Val, 1);\n" - << " Result = Result.getValue(N.ResNo);\n" + << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" + << " SDOperand Dummy;\n" + << " AddToQueue(Dummy, N.getOperand(i));\n" << " }\n" + << " Result = N;\n" << " return;\n" << " }\n" << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n"; @@ -3683,78 +3550,89 @@ OS << "#define NOINLINE\n"; OS << "#endif\n\n"; - OS << "// Instance var to keep track of multiply used nodes that have \n" - << "// already been selected.\n" - << "std::map CodeGenMap;\n"; - - OS << "// Instance var to keep track of mapping of chain generating nodes\n" - << "// and their place handle nodes.\n"; - OS << "std::map HandleMap;\n"; - OS << "// Instance var to keep track of mapping of place handle nodes\n" - << "// and their replacement nodes.\n"; - OS << "std::map ReplaceMap;\n"; + OS << "// Instruction selector priority queue:\n" + << "std::vector ISelQueue;\n"; + OS << "/// Keep track of nodes which have already been added to queue.\n" + << "unsigned char *ISelQueued;\n"; + OS << "/// Keep track of nodes which have already been selected.\n" + << "unsigned char *ISelSelected;\n"; + OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n" + << "std::vector ISelKilled;\n\n"; + + OS << "/// Sorting functions for the selection queue.\n" + << "struct isel_sort : public std::binary_function" + << " {\n" + << " bool operator()(const SDNode* left, const SDNode* right) " + << "const {\n" + << " return (left->getNodeId() > right->getNodeId());\n" + << " }\n" + << "};\n\n"; - OS << "\n"; - OS << "// AddHandleReplacement - Note the pending replacement node for a\n" - << "// handle node in ReplaceMap.\n"; - OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, " - << "unsigned RNum) {\n"; - OS << " SDOperand N(H, HNum);\n"; - OS << " std::map::iterator HMI = HandleMap.find(N);\n"; - OS << " if (HMI != HandleMap.end()) {\n"; - OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n"; - OS << " HandleMap.erase(N);\n"; - OS << " }\n"; + OS << "inline void setQueued(int Id) {\n"; + OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n"; OS << "}\n"; - - OS << "\n"; - OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n"; - OS << "// handles.Some handles do not yet have replacements because the\n"; - OS << "// nodes they replacements have only dead readers.\n"; - OS << "void SelectDanglingHandles() {\n"; - OS << " for (std::map::iterator I = " - << "HandleMap.begin(),\n" - << " E = HandleMap.end(); I != E; ++I) {\n"; - OS << " SDOperand N = I->first;\n"; - OS << " SDOperand R;\n"; - OS << " Select(R, N.getValue(0));\n"; - OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n"; - OS << " }\n"; + OS << "inline bool isQueued(int Id) {\n"; + OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n"; OS << "}\n"; - OS << "\n"; - OS << "// ReplaceHandles - Replace all the handles with the real target\n"; - OS << "// specific nodes.\n"; - OS << "void ReplaceHandles() {\n"; - OS << " for (std::map::iterator I = " - << "ReplaceMap.begin(),\n" - << " E = ReplaceMap.end(); I != E; ++I) {\n"; - OS << " SDOperand From = I->first;\n"; - OS << " SDOperand To = I->second;\n"; - OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), " - << "E = From.Val->use_end(); UI != E; ++UI) {\n"; - OS << " SDNode *Use = *UI;\n"; - OS << " std::vector Ops;\n"; - OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n"; - OS << " SDOperand O = Use->getOperand(i);\n"; - OS << " if (O.Val == From.Val)\n"; - OS << " Ops.push_back(To);\n"; - OS << " else\n"; - OS << " Ops.push_back(O);\n"; - OS << " }\n"; - OS << " SDOperand U = SDOperand(Use, 0);\n"; - OS << " CurDAG->UpdateNodeOperands(U, Ops);\n"; - OS << " }\n"; - OS << " }\n"; + OS << "inline void setSelected(int Id) {\n"; + OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n"; OS << "}\n"; + OS << "inline bool isSelected(int Id) {\n"; + OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n"; + OS << "}\n\n"; + + OS << "inline void AddToQueue(SDOperand &Result, SDOperand N) {\n"; + OS << " Result = N;\n"; + OS << " int Id = N.Val->getNodeId();\n"; + OS << " if (Id != -1 && !isQueued(Id)) {\n"; + OS << " ISelQueue.push_back(N.Val);\n"; + OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; + OS << " setQueued(Id);\n"; + OS << " }\n"; + OS << "}\n\n"; + + OS << "inline void RemoveKilled() {\n"; +OS << " unsigned NumKilled = ISelKilled.size();\n"; + OS << " if (NumKilled) {\n"; + OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n"; + OS << " SDNode *Temp = ISelKilled[i];\n"; + OS << " std::remove(ISelQueue.begin(), ISelQueue.end(), Temp);\n"; + OS << " };\n"; + OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; + OS << " ISelKilled.clear();\n"; + OS << " }\n"; + OS << "}\n\n"; + + OS << "inline void ReplaceUses(SDOperand F, SDOperand T) {\n"; + OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n"; + OS << " setSelected(F.Val->getNodeId());\n"; + OS << " RemoveKilled();\n"; + OS << "}\n\n"; - OS << "\n"; OS << "// SelectRoot - Top level entry to DAG isel.\n"; - OS << "SDOperand SelectRoot(SDOperand N) {\n"; + OS << "SDOperand SelectRoot(SDOperand Root) {\n"; + OS << " SelectRootInit();\n"; + OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n"; + OS << " ISelQueued = new unsigned char[NumBytes];\n"; + OS << " ISelSelected = new unsigned char[NumBytes];\n"; + OS << " memset(ISelQueued, 0, NumBytes);\n"; + OS << " memset(ISelSelected, 0, NumBytes);\n"; + OS << "\n"; OS << " SDOperand ResNode;\n"; - OS << " Select(ResNode, N);\n"; - OS << " SelectDanglingHandles();\n"; - OS << " ReplaceHandles();\n"; - OS << " ReplaceMap.clear();\n"; + OS << " Select(ResNode, Root);\n"; + OS << " while (!ISelQueue.empty()) {\n"; + OS << " SDOperand Tmp;\n"; + OS << " SDNode *Node = ISelQueue.front();\n"; + OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; + OS << " ISelQueue.pop_back();\n"; + OS << " if (!isSelected(Node->getNodeId()))\n"; + OS << " Select(Tmp, SDOperand(Node, 0));\n"; + OS << " }\n"; + OS << "\n"; + OS << " delete[] ISelQueued;\n"; + OS << " ISelQueued = NULL;\n"; + OS << " delete[] ISelSelected;\n"; + OS << " ISelSelected = NULL;\n"; OS << " return ResNode;\n"; OS << "}\n"; Index: llvm/utils/TableGen/DAGISelEmitter.h diff -u llvm/utils/TableGen/DAGISelEmitter.h:1.66 llvm/utils/TableGen/DAGISelEmitter.h:1.67 --- llvm/utils/TableGen/DAGISelEmitter.h:1.66 Sun Jul 16 01:12:52 2006 +++ llvm/utils/TableGen/DAGISelEmitter.h Mon Aug 7 17:17:58 2006 @@ -523,8 +523,7 @@ std::vector > &GeneratedCode, std::set > &GeneratedDecl, std::vector &TargetOpcodes, - std::vector &TargetVTs, - bool DoReplace); + std::vector &TargetVTs); void EmitPatterns(std::vector > > > &Patterns, unsigned Indent, std::ostream &OS); From evan.cheng at apple.com Mon Aug 7 17:22:30 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:22:30 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp Message-ID: <200608072222.k77MMURD012335@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/ARM: ARMISelDAGToDAG.cpp updated: 1.22 -> 1.23 --- Log message: Match tablegen isel changes. --- Diffs of the changes: (+1 -3) ARMISelDAGToDAG.cpp | 4 +--- 1 files changed, 1 insertion(+), 3 deletions(-) Index: llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp diff -u llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp:1.22 llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp:1.23 --- llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp:1.22 Fri Aug 4 07:48:42 2006 +++ llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp Mon Aug 7 17:22:14 2006 @@ -26,6 +26,7 @@ #include "llvm/Target/TargetLowering.h" #include "llvm/Support/Debug.h" #include +#include #include using namespace llvm; @@ -306,9 +307,6 @@ DEBUG(BB->dump()); DAG.setRoot(SelectRoot(DAG.getRoot())); - CodeGenMap.clear(); - HandleMap.clear(); - ReplaceMap.clear(); DAG.RemoveDeadNodes(); ScheduleAndEmitDAG(DAG); From evan.cheng at apple.com Mon Aug 7 17:23:34 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:23:34 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/Alpha/AlphaISelDAGToDAG.cpp Message-ID: <200608072223.k77MNYJR013869@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/Alpha: AlphaISelDAGToDAG.cpp updated: 1.48 -> 1.49 --- Log message: Match tablegen isel changes. --- Diffs of the changes: (+26 -26) AlphaISelDAGToDAG.cpp | 52 +++++++++++++++++++++++++------------------------- 1 files changed, 26 insertions(+), 26 deletions(-) Index: llvm/lib/Target/Alpha/AlphaISelDAGToDAG.cpp diff -u llvm/lib/Target/Alpha/AlphaISelDAGToDAG.cpp:1.48 llvm/lib/Target/Alpha/AlphaISelDAGToDAG.cpp:1.49 --- llvm/lib/Target/Alpha/AlphaISelDAGToDAG.cpp:1.48 Thu Jul 27 19:46:29 2006 +++ llvm/lib/Target/Alpha/AlphaISelDAGToDAG.cpp Mon Aug 7 17:23:20 2006 @@ -30,6 +30,7 @@ #include "llvm/Support/MathExtras.h" #include #include +#include #include using namespace llvm; @@ -129,7 +130,7 @@ switch (ConstraintCode) { default: return true; case 'm': // memory - Select(Op0, Op); + AddToQueue(Op0, Op); break; } @@ -172,9 +173,6 @@ // Select target instructions for the DAG. DAG.setRoot(SelectRoot(DAG.getRoot())); - CodeGenMap.clear(); - HandleMap.clear(); - ReplaceMap.clear(); DAG.RemoveDeadNodes(); // Emit machine code to BB. @@ -191,13 +189,6 @@ return; // Already selected. } - // If this has already been converted, use it. - std::map::iterator CGMI = CodeGenMap.find(Op); - if (CGMI != CodeGenMap.end()) { - Result = CGMI->second; - return; - } - switch (N->getOpcode()) { default: break; case AlphaISD::CALL: @@ -213,17 +204,19 @@ } case AlphaISD::GlobalBaseReg: Result = getGlobalBaseReg(); + ReplaceUses(Op, Result); return; case AlphaISD::GlobalRetAddr: Result = getGlobalRetAddr(); + ReplaceUses(Op, Result); return; case AlphaISD::DivCall: { SDOperand Chain = CurDAG->getEntryNode(); SDOperand N0, N1, N2; - Select(N0, Op.getOperand(0)); - Select(N1, Op.getOperand(1)); - Select(N2, Op.getOperand(2)); + AddToQueue(N0, Op.getOperand(0)); + AddToQueue(N1, Op.getOperand(1)); + AddToQueue(N2, Op.getOperand(2)); Chain = CurDAG->getCopyToReg(Chain, Alpha::R24, N1, SDOperand(0,0)); Chain = CurDAG->getCopyToReg(Chain, Alpha::R25, N2, @@ -241,8 +234,11 @@ case ISD::READCYCLECOUNTER: { SDOperand Chain; - Select(Chain, N->getOperand(0)); //Select chain - Result = CurDAG->SelectNodeTo(N, Alpha::RPCC, MVT::i64, Chain); + AddToQueue(Chain, N->getOperand(0)); //Select chain + Result = SDOperand(CurDAG->getTargetNode(Alpha::RPCC, MVT::i64, MVT::Other, + Chain), Op.ResNo); + ReplaceUses(Op.getValue(0), Result.getValue(0)); + ReplaceUses(Op.getValue(1), Result.getValue(1)); return; } @@ -252,6 +248,7 @@ if (uval == 0) { Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), Alpha::R31, MVT::i64); + ReplaceUses(Op, Result); return; } @@ -311,8 +308,8 @@ case ISD::SETNE: case ISD::SETONE: case ISD::SETUNE: Opc = Alpha::CMPTEQ; isNE = true; break; }; SDOperand tmp1, tmp2; - Select(tmp1, N->getOperand(0)); - Select(tmp2, N->getOperand(1)); + AddToQueue(tmp1, N->getOperand(0)); + AddToQueue(tmp2, N->getOperand(1)); SDNode *cmp = CurDAG->getTargetNode(Opc, MVT::f64, rev?tmp2:tmp1, rev?tmp1:tmp2); @@ -338,6 +335,7 @@ Result = SDOperand(CurDAG->getTargetNode(Alpha::CMPULT, MVT::i64, CurDAG->getRegister(Alpha::R31, MVT::i64), LD), 0); + ReplaceUses(Op, Result); return; } break; @@ -352,9 +350,9 @@ //move int to fp bool isDouble = N->getValueType(0) == MVT::f64; SDOperand LD, cond, TV, FV; - Select(cond, N->getOperand(0)); - Select(TV, N->getOperand(1)); - Select(FV, N->getOperand(2)); + AddToQueue(cond, N->getOperand(0)); + AddToQueue(TV, N->getOperand(1)); + AddToQueue(FV, N->getOperand(2)); if (AlphaLowering.hasITOF()) { LD = CurDAG->getNode(AlphaISD::ITOFT_, MVT::f64, cond); @@ -371,6 +369,7 @@ } Result = SDOperand(CurDAG->getTargetNode(isDouble?Alpha::FCMOVNET:Alpha::FCMOVNES, MVT::f64, FV, TV, LD), 0); + ReplaceUses(Op, Result); return; } break; @@ -396,12 +395,13 @@ if (get_zapImm(mask)) { SDOperand Src; - Select(Src, N->getOperand(0).getOperand(0)); + AddToQueue(Src, N->getOperand(0).getOperand(0)); SDOperand Z = SDOperand(CurDAG->getTargetNode(Alpha::ZAPNOTi, MVT::i64, Src, getI64Imm(get_zapImm(mask))), 0); Result = SDOperand(CurDAG->getTargetNode(Alpha::SRL, MVT::i64, Z, getI64Imm(sval)), 0); + ReplaceUses(Op, Result); return; } } @@ -420,7 +420,7 @@ SDOperand Chain; SDOperand Addr = N->getOperand(1); SDOperand InFlag(0,0); // Null incoming flag value. - Select(Chain, N->getOperand(0)); + AddToQueue(Chain, N->getOperand(0)); std::vector CallOperands; std::vector TypeOperands; @@ -429,7 +429,7 @@ for(int i = 2, e = N->getNumOperands(); i < e; ++i) { SDOperand Tmp; TypeOperands.push_back(N->getOperand(i).getValueType()); - Select(Tmp, N->getOperand(i)); + AddToQueue(Tmp, N->getOperand(i)); CallOperands.push_back(Tmp); } int count = N->getNumOperands() - 2; @@ -474,7 +474,7 @@ Chain = SDOperand(CurDAG->getTargetNode(Alpha::BSR, MVT::Other, MVT::Flag, Addr.getOperand(0), Chain, InFlag), 0); } else { - Select(Addr, Addr); + AddToQueue(Addr, Addr); Chain = CurDAG->getCopyToReg(Chain, Alpha::R27, Addr, InFlag); InFlag = Chain.getValue(1); Chain = SDOperand(CurDAG->getTargetNode(Alpha::JSR, MVT::Other, MVT::Flag, @@ -503,7 +503,7 @@ CallResults.push_back(Chain); for (unsigned i = 0, e = CallResults.size(); i != e; ++i) - CodeGenMap[Op.getValue(i)] = CallResults[i]; + ReplaceUses(Op.getValue(i), CallResults[i]); return CallResults[Op.ResNo]; } From evan.cheng at apple.com Mon Aug 7 17:23:55 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:23:55 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/IA64/IA64ISelDAGToDAG.cpp Message-ID: <200608072223.k77MNt7K014153@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/IA64: IA64ISelDAGToDAG.cpp updated: 1.46 -> 1.47 --- Log message: Match tablegen isel changes. --- Diffs of the changes: (+28 -70) IA64ISelDAGToDAG.cpp | 98 ++++++++++++++------------------------------------- 1 files changed, 28 insertions(+), 70 deletions(-) Index: llvm/lib/Target/IA64/IA64ISelDAGToDAG.cpp diff -u llvm/lib/Target/IA64/IA64ISelDAGToDAG.cpp:1.46 llvm/lib/Target/IA64/IA64ISelDAGToDAG.cpp:1.47 --- llvm/lib/Target/IA64/IA64ISelDAGToDAG.cpp:1.46 Thu Jul 27 19:46:44 2006 +++ llvm/lib/Target/IA64/IA64ISelDAGToDAG.cpp Mon Aug 7 17:23:40 2006 @@ -28,6 +28,7 @@ #include "llvm/Support/Debug.h" #include "llvm/Support/MathExtras.h" #include +#include #include using namespace llvm; @@ -101,50 +102,9 @@ /// SelectionDAGISel when it has created a SelectionDAG for us to codegen. void IA64DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) { DEBUG(BB->dump()); - - // The selection process is inherently a bottom-up recursive process (users - // select their uses before themselves). Given infinite stack space, we - // could just start selecting on the root and traverse the whole graph. In - // practice however, this causes us to run out of stack space on large basic - // blocks. To avoid this problem, select the entry node, then all its uses, - // iteratively instead of recursively. - std::vector Worklist; - Worklist.push_back(DAG.getEntryNode()); - - // Note that we can do this in the IA64 target (scanning forward across token - // chain edges) because no nodes ever get folded across these edges. On a - // target like X86 which supports load/modify/store operations, this would - // have to be more careful. - while (!Worklist.empty()) { - SDOperand Node = Worklist.back(); - Worklist.pop_back(); - - if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END && - Node.Val->getOpcode() < IA64ISD::FIRST_NUMBER) || - CodeGenMap.count(Node)) continue; - - for (SDNode::use_iterator UI = Node.Val->use_begin(), - E = Node.Val->use_end(); UI != E; ++UI) { - // Scan the values. If this use has a value that is a token chain, add it - // to the worklist. - SDNode *User = *UI; - for (unsigned i = 0, e = User->getNumValues(); i != e; ++i) - if (User->getValueType(i) == MVT::Other) { - Worklist.push_back(SDOperand(User, i)); - break; - } - } - // Finally, legalize this node. - SDOperand Dummy; - Select(Dummy, Node); - } - // Select target instructions for the DAG. DAG.setRoot(SelectRoot(DAG.getRoot())); - CodeGenMap.clear(); - HandleMap.clear(); - ReplaceMap.clear(); DAG.RemoveDeadNodes(); // Emit machine code to BB. @@ -154,10 +114,10 @@ SDOperand IA64DAGToDAGISel::SelectDIV(SDOperand Op) { SDNode *N = Op.Val; SDOperand Chain, Tmp1, Tmp2; - Select(Chain, N->getOperand(0)); + AddToQueue(Chain, N->getOperand(0)); - Select(Tmp1, N->getOperand(0)); - Select(Tmp2, N->getOperand(1)); + AddToQueue(Tmp1, N->getOperand(0)); + AddToQueue(Tmp2, N->getOperand(1)); bool isFP=false; @@ -344,13 +304,6 @@ return; // Already selected. } - // If this has already been converted, use it. - std::map::iterator CGMI = CodeGenMap.find(Op); - if (CGMI != CodeGenMap.end()) { - Result = CGMI->second; - return; - } - switch (N->getOpcode()) { default: break; @@ -358,9 +311,9 @@ SDOperand Chain; SDOperand InFlag; // Null incoming flag value. - Select(Chain, N->getOperand(0)); + AddToQueue(Chain, N->getOperand(0)); if(N->getNumOperands()==3) // we have an incoming chain, callee and flag - Select(InFlag, N->getOperand(2)); + AddToQueue(InFlag, N->getOperand(2)); unsigned CallOpcode; SDOperand CallOperand; @@ -382,7 +335,7 @@ // load the branch target (function)'s entry point and GP, // branch (call) then restore the GP SDOperand FnDescriptor; - Select(FnDescriptor, N->getOperand(1)); + AddToQueue(FnDescriptor, N->getOperand(1)); // load the branch target's entry point [mem] and // GP value [mem+8] @@ -421,16 +374,16 @@ CallResults.push_back(InFlag); for (unsigned i = 0, e = CallResults.size(); i != e; ++i) - CodeGenMap[Op.getValue(i)] = CallResults[i]; + ReplaceUses(Op.getValue(i), CallResults[i]); Result = CallResults[Op.ResNo]; return; } case IA64ISD::GETFD: { SDOperand Input; - Select(Input, N->getOperand(0)); + AddToQueue(Input, N->getOperand(0)); Result = SDOperand(CurDAG->getTargetNode(IA64::GETFD, MVT::i64, Input), 0); - CodeGenMap[Op] = Result; + ReplaceUses(Op, Result); return; } @@ -440,6 +393,7 @@ case ISD::SREM: case ISD::UREM: Result = SelectDIV(Op); + ReplaceUses(Op, Result); return; case ISD::TargetConstantFP: { @@ -459,9 +413,11 @@ if (N->hasOneUse()) Result = CurDAG->SelectNodeTo(N, IA64::MOV, MVT::i64, CurDAG->getTargetFrameIndex(FI, MVT::i64)); - else - Result = CodeGenMap[Op] = SDOperand(CurDAG->getTargetNode(IA64::MOV, MVT::i64, + else { + Result = SDOperand(CurDAG->getTargetNode(IA64::MOV, MVT::i64, CurDAG->getTargetFrameIndex(FI, MVT::i64)), 0); + ReplaceUses(Op, Result); + } return; } @@ -473,6 +429,7 @@ CP->getAlignment()); Result = SDOperand(CurDAG->getTargetNode(IA64::ADDL_GA, MVT::i64, // ? CurDAG->getRegister(IA64::r1, MVT::i64), CPI), 0); + ReplaceUses(Op, Result); return; } @@ -482,6 +439,7 @@ SDOperand Tmp = SDOperand(CurDAG->getTargetNode(IA64::ADDL_GA, MVT::i64, CurDAG->getRegister(IA64::r1, MVT::i64), GA), 0); Result = SDOperand(CurDAG->getTargetNode(IA64::LD8, MVT::i64, Tmp), 0); + ReplaceUses(Op, Result); return; } @@ -498,8 +456,8 @@ case ISD::EXTLOAD: // FIXME: load -1, not 1, for bools? case ISD::ZEXTLOAD: { SDOperand Chain, Address; - Select(Chain, N->getOperand(0)); - Select(Address, N->getOperand(1)); + AddToQueue(Chain, N->getOperand(0)); + AddToQueue(Address, N->getOperand(1)); MVT::ValueType TypeBeingLoaded = (N->getOpcode() == ISD::LOAD) ? N->getValueType(0) : cast(N->getOperand(3))->getVT(); @@ -540,8 +498,8 @@ case ISD::TRUNCSTORE: case ISD::STORE: { SDOperand Address, Chain; - Select(Address, N->getOperand(2)); - Select(Chain, N->getOperand(0)); + AddToQueue(Address, N->getOperand(2)); + AddToQueue(Chain, N->getOperand(0)); unsigned Opc; if (N->getOpcode() == ISD::STORE) { @@ -554,7 +512,7 @@ Chain = Initial.getValue(1); // then load 1 into the same reg iff the predicate to store is 1 SDOperand Tmp; - Select(Tmp, N->getOperand(1)); + AddToQueue(Tmp, N->getOperand(1)); Tmp = SDOperand(CurDAG->getTargetNode(IA64::TPCADDS, MVT::i64, Initial, CurDAG->getConstant(1, MVT::i64), Tmp), 0); @@ -575,16 +533,16 @@ } SDOperand N1, N2; - Select(N1, N->getOperand(1)); - Select(N2, N->getOperand(2)); + AddToQueue(N1, N->getOperand(1)); + AddToQueue(N2, N->getOperand(2)); Result = CurDAG->SelectNodeTo(N, Opc, MVT::Other, N2, N1, Chain); return; } case ISD::BRCOND: { SDOperand Chain, CC; - Select(Chain, N->getOperand(0)); - Select(CC, N->getOperand(1)); + AddToQueue(Chain, N->getOperand(0)); + AddToQueue(CC, N->getOperand(1)); MachineBasicBlock *Dest = cast(N->getOperand(2))->getBasicBlock(); //FIXME - we do NOT need long branches all the time @@ -599,7 +557,7 @@ unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ? IA64::ADJUSTCALLSTACKDOWN : IA64::ADJUSTCALLSTACKUP; SDOperand N0; - Select(N0, N->getOperand(0)); + AddToQueue(N0, N->getOperand(0)); Result = CurDAG->SelectNodeTo(N, Opc, MVT::Other, getI64Imm(Amt), N0); return; } @@ -607,7 +565,7 @@ case ISD::BR: // FIXME: we don't need long branches all the time! SDOperand N0; - Select(N0, N->getOperand(0)); + AddToQueue(N0, N->getOperand(0)); Result = CurDAG->SelectNodeTo(N, IA64::BRL_NOTCALL, MVT::Other, N->getOperand(1), N0); return; From evan.cheng at apple.com Mon Aug 7 17:24:11 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:24:11 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp Message-ID: <200608072224.k77MOBfg014224@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/PowerPC: PPCISelDAGToDAG.cpp updated: 1.199 -> 1.200 --- Log message: Match tablegen isel changes. --- Diffs of the changes: (+50 -101) PPCISelDAGToDAG.cpp | 151 +++++++++++++++++----------------------------------- 1 files changed, 50 insertions(+), 101 deletions(-) Index: llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp diff -u llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp:1.199 llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp:1.200 --- llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp:1.199 Thu Jul 27 19:47:04 2006 +++ llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp Mon Aug 7 17:23:56 2006 @@ -30,6 +30,7 @@ #include "llvm/Support/MathExtras.h" #include "llvm/Support/Visibility.h" #include +#include #include using namespace llvm; @@ -123,7 +124,7 @@ break; case 'o': // offsetable if (!SelectAddrImm(Op, Op0, Op1)) { - Select(Op0, Op); // r+0. + AddToQueue(Op0, Op); // r+0. Op1 = getSmallIPtrImm(0); } break; @@ -174,50 +175,9 @@ /// SelectionDAGISel when it has created a SelectionDAG for us to codegen. void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) { DEBUG(BB->dump()); - - // The selection process is inherently a bottom-up recursive process (users - // select their uses before themselves). Given infinite stack space, we - // could just start selecting on the root and traverse the whole graph. In - // practice however, this causes us to run out of stack space on large basic - // blocks. To avoid this problem, select the entry node, then all its uses, - // iteratively instead of recursively. - std::vector Worklist; - Worklist.push_back(DAG.getEntryNode()); - - // Note that we can do this in the PPC target (scanning forward across token - // chain edges) because no nodes ever get folded across these edges. On a - // target like X86 which supports load/modify/store operations, this would - // have to be more careful. - while (!Worklist.empty()) { - SDOperand Node = Worklist.back(); - Worklist.pop_back(); - - if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END && - Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) || - CodeGenMap.count(Node)) continue; - - for (SDNode::use_iterator UI = Node.Val->use_begin(), - E = Node.Val->use_end(); UI != E; ++UI) { - // Scan the values. If this use has a value that is a token chain, add it - // to the worklist. - SDNode *User = *UI; - for (unsigned i = 0, e = User->getNumValues(); i != e; ++i) - if (User->getValueType(i) == MVT::Other) { - Worklist.push_back(SDOperand(User, i)); - break; - } - } - // Finally, legalize this node. - SDOperand Dummy; - Select(Dummy, Node); - } - // Select target instructions for the DAG. DAG.setRoot(SelectRoot(DAG.getRoot())); - CodeGenMap.clear(); - HandleMap.clear(); - ReplaceMap.clear(); DAG.RemoveDeadNodes(); // Emit machine code to BB. @@ -493,8 +453,8 @@ } Tmp3 = (Op0Opc == ISD::AND && DisjointMask) ? Op0.getOperand(0) : Op0; - Select(Tmp1, Tmp3); - Select(Tmp2, Op1); + AddToQueue(Tmp1, Tmp3); + AddToQueue(Tmp2, Op1); SH &= 31; return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME)); @@ -732,7 +692,7 @@ SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC) { // Always select the LHS. - Select(LHS, LHS); + AddToQueue(LHS, LHS); unsigned Opc; if (LHS.getValueType() == MVT::i32) { @@ -771,7 +731,7 @@ assert(LHS.getValueType() == MVT::f64 && "Unknown vt!"); Opc = PPC::FCMPUD; } - Select(RHS, RHS); + AddToQueue(RHS, RHS); return SDOperand(CurDAG->getTargetNode(Opc, MVT::i32, LHS, RHS), 0); } @@ -845,7 +805,7 @@ // setcc op, 0 if (Imm == 0) { SDOperand Op; - Select(Op, N->getOperand(0)); + AddToQueue(Op, N->getOperand(0)); switch (CC) { default: break; case ISD::SETEQ: @@ -872,7 +832,7 @@ } } else if (Imm == ~0U) { // setcc op, -1 SDOperand Op; - Select(Op, N->getOperand(0)); + AddToQueue(Op, N->getOperand(0)); switch (CC) { default: break; case ISD::SETEQ: @@ -948,13 +908,6 @@ return; // Already selected. } - // If this has already been converted, use it. - std::map::iterator CGMI = CodeGenMap.find(Op); - if (CGMI != CodeGenMap.end()) { - Result = CGMI->second; - return; - } - switch (N->getOpcode()) { default: break; case ISD::SETCC: @@ -962,6 +915,7 @@ return; case PPCISD::GlobalBaseReg: Result = getGlobalBaseReg(); + ReplaceUses(Op, Result); return; case ISD::FrameIndex: { @@ -973,22 +927,23 @@ getSmallIPtrImm(0)); return; } - Result = CodeGenMap[Op] = + Result = SDOperand(CurDAG->getTargetNode(Opc, Op.getValueType(), TFI, getSmallIPtrImm(0)), 0); + ReplaceUses(Op, Result); return; } case PPCISD::MFCR: { SDOperand InFlag; - Select(InFlag, N->getOperand(1)); + AddToQueue(InFlag, N->getOperand(1)); // Use MFOCRF if supported. if (TLI.getTargetMachine().getSubtarget().isGigaProcessor()) Result = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, N->getOperand(0), InFlag), 0); else Result = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, InFlag), 0); - CodeGenMap[Op] = Result; + ReplaceUses(Op, Result); return; } @@ -1001,7 +956,7 @@ unsigned Imm; if (isInt32Immediate(N->getOperand(1), Imm)) { SDOperand N0; - Select(N0, N->getOperand(0)); + AddToQueue(N0, N->getOperand(0)); if ((signed)Imm > 0 && isPowerOf2_32(Imm)) { SDNode *Op = CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag, @@ -1033,13 +988,13 @@ SDOperand Val; unsigned SH, MB, ME; if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) { - Select(Val, N->getOperand(0).getOperand(0)); + AddToQueue(Val, N->getOperand(0).getOperand(0)); } else if (Imm == 0) { // AND X, 0 -> 0, not "rlwinm 32". - Select(Result, N->getOperand(1)); + AddToQueue(Result, N->getOperand(1)); return ; } else { - Select(Val, N->getOperand(0)); + AddToQueue(Val, N->getOperand(0)); isRunOfOnes(Imm, MB, ME); SH = 0; } @@ -1057,12 +1012,13 @@ Imm = ~(Imm^Imm2); if (isRunOfOnes(Imm, MB, ME)) { SDOperand Tmp1, Tmp2; - Select(Tmp1, N->getOperand(0).getOperand(0)); - Select(Tmp2, N->getOperand(0).getOperand(1)); + AddToQueue(Tmp1, N->getOperand(0).getOperand(0)); + AddToQueue(Tmp2, N->getOperand(0).getOperand(1)); Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2, getI32Imm(0), getI32Imm(MB), getI32Imm(ME)), 0); + ReplaceUses(Op, Result); return; } } @@ -1073,7 +1029,8 @@ case ISD::OR: if (N->getValueType(0) == MVT::i32) if (SDNode *I = SelectBitfieldInsert(N)) { - Result = CodeGenMap[Op] = SDOperand(I, 0); + Result = SDOperand(I, 0); + ReplaceUses(Op, Result); return; } @@ -1084,7 +1041,7 @@ if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) && isRotateAndMask(N, Imm, true, SH, MB, ME)) { SDOperand Val; - Select(Val, N->getOperand(0).getOperand(0)); + AddToQueue(Val, N->getOperand(0).getOperand(0)); Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME)); @@ -1099,7 +1056,7 @@ if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) && isRotateAndMask(N, Imm, true, SH, MB, ME)) { SDOperand Val; - Select(Val, N->getOperand(0).getOperand(0)); + AddToQueue(Val, N->getOperand(0).getOperand(0)); Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME)); @@ -1121,7 +1078,7 @@ // FIXME: Implement this optzn for PPC64. N->getValueType(0) == MVT::i32) { SDOperand LHS; - Select(LHS, N->getOperand(0)); + AddToQueue(LHS, N->getOperand(0)); SDNode *Tmp = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag, LHS, getI32Imm(~0U)); @@ -1148,15 +1105,15 @@ SelectCCOp = PPC::SELECT_CC_VRRC; SDOperand N2, N3; - Select(N2, N->getOperand(2)); - Select(N3, N->getOperand(3)); + AddToQueue(N2, N->getOperand(2)); + AddToQueue(N3, N->getOperand(3)); Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg, N2, N3, getI32Imm(BROpc)); return; } case ISD::BR_CC: { SDOperand Chain; - Select(Chain, N->getOperand(0)); + AddToQueue(Chain, N->getOperand(0)); ISD::CondCode CC = cast(N->getOperand(1))->get(); SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC); Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, @@ -1167,8 +1124,8 @@ case ISD::BRIND: { // FIXME: Should custom lower this. SDOperand Chain, Target; - Select(Chain, N->getOperand(0)); - Select(Target,N->getOperand(1)); + AddToQueue(Chain, N->getOperand(0)); + AddToQueue(Target,N->getOperand(1)); unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8; Chain = SDOperand(CurDAG->getTargetNode(Opc, MVT::Other, Target, Chain), 0); @@ -1198,25 +1155,23 @@ std::vector Ops; // Push varargs arguments, including optional flag. for (unsigned i = 1, e = N.getNumOperands()-hasFlag; i != e; ++i) { - Select(Chain, N.getOperand(i)); + AddToQueue(Chain, N.getOperand(i)); Ops.push_back(Chain); } - Select(Chain, N.getOperand(0)); + AddToQueue(Chain, N.getOperand(0)); Ops.push_back(Chain); if (hasFlag) { - Select(Chain, N.getOperand(N.getNumOperands()-1)); + AddToQueue(Chain, N.getOperand(N.getNumOperands()-1)); Ops.push_back(Chain); } ResNode = CurDAG->getTargetNode(PPC::BCTRL, MVT::Other, MVT::Flag, Ops); Chain = SDOperand(ResNode, 0); InFlag = SDOperand(ResNode, 1); - SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val, - Chain.ResNo); - SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val, - InFlag.ResNo); + ReplaceUses(SDOperand(N.Val, 0), Chain); + ReplaceUses(SDOperand(N.Val, 1), InFlag); Result = SDOperand(ResNode, N.ResNo); return; } @@ -1246,23 +1201,21 @@ // Push varargs arguments, not including optional flag. for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) { - Select(Chain, N.getOperand(i)); + AddToQueue(Chain, N.getOperand(i)); Ops.push_back(Chain); } - Select(Chain, N.getOperand(0)); + AddToQueue(Chain, N.getOperand(0)); Ops.push_back(Chain); if (hasFlag) { - Select(Chain, N.getOperand(N.getNumOperands()-1)); + AddToQueue(Chain, N.getOperand(N.getNumOperands()-1)); Ops.push_back(Chain); } ResNode = CurDAG->getTargetNode(PPC::BLA, MVT::Other, MVT::Flag, Ops); Chain = SDOperand(ResNode, 0); InFlag = SDOperand(ResNode, 1); - SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val, - Chain.ResNo); - SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val, - InFlag.ResNo); + ReplaceUses(SDOperand(N.Val, 0), Chain); + ReplaceUses(SDOperand(N.Val, 1), InFlag); Result = SDOperand(ResNode, N.ResNo); return; } @@ -1279,13 +1232,13 @@ // Push varargs arguments, not including optional flag. for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) { - Select(Chain, N.getOperand(i)); + AddToQueue(Chain, N.getOperand(i)); Ops.push_back(Chain); } - Select(Chain, N.getOperand(0)); + AddToQueue(Chain, N.getOperand(0)); Ops.push_back(Chain); if (hasFlag) { - Select(Chain, N.getOperand(N.getNumOperands()-1)); + AddToQueue(Chain, N.getOperand(N.getNumOperands()-1)); Ops.push_back(Chain); } @@ -1293,10 +1246,8 @@ Chain = SDOperand(ResNode, 0); InFlag = SDOperand(ResNode, 1); - SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val, - Chain.ResNo); - SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val, - InFlag.ResNo); + ReplaceUses(SDOperand(N.Val, 0), Chain); + ReplaceUses(SDOperand(N.Val, 1), InFlag); Result = SDOperand(ResNode, N.ResNo); return; } @@ -1313,13 +1264,13 @@ // Push varargs arguments, not including optional flag. for (unsigned i = 2, e = N.getNumOperands()-hasFlag; i != e; ++i) { - Select(Chain, N.getOperand(i)); + AddToQueue(Chain, N.getOperand(i)); Ops.push_back(Chain); } - Select(Chain, N.getOperand(0)); + AddToQueue(Chain, N.getOperand(0)); Ops.push_back(Chain); if (hasFlag) { - Select(Chain, N.getOperand(N.getNumOperands()-1)); + AddToQueue(Chain, N.getOperand(N.getNumOperands()-1)); Ops.push_back(Chain); } @@ -1327,10 +1278,8 @@ Chain = SDOperand(ResNode, 0); InFlag = SDOperand(ResNode, 1); - SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, Chain.Val, - Chain.ResNo); - SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, InFlag.Val, - InFlag.ResNo); + ReplaceUses(SDOperand(N.Val, 0), Chain); + ReplaceUses(SDOperand(N.Val, 1), InFlag); Result = SDOperand(ResNode, N.ResNo); return; } From evan.cheng at apple.com Mon Aug 7 17:24:34 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:24:34 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp Message-ID: <200608072224.k77MOYAT014370@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/Sparc: SparcISelDAGToDAG.cpp updated: 1.100 -> 1.101 --- Log message: Match tablegen isel changes. --- Diffs of the changes: (+5 -14) SparcISelDAGToDAG.cpp | 19 +++++-------------- 1 files changed, 5 insertions(+), 14 deletions(-) Index: llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp diff -u llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp:1.100 llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp:1.101 --- llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp:1.100 Thu Jul 27 19:47:19 2006 +++ llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp Mon Aug 7 17:24:18 2006 @@ -25,6 +25,7 @@ #include "llvm/Target/TargetLowering.h" #include "llvm/Support/Debug.h" #include +#include #include using namespace llvm; @@ -1001,9 +1002,6 @@ // Select target instructions for the DAG. DAG.setRoot(SelectRoot(DAG.getRoot())); - CodeGenMap.clear(); - HandleMap.clear(); - ReplaceMap.clear(); DAG.RemoveDeadNodes(); // Emit machine code to BB. @@ -1083,21 +1081,14 @@ return; // Already selected. } - // If this has already been converted, use it. - std::map::iterator CGMI = CodeGenMap.find(Op); - if (CGMI != CodeGenMap.end()) { - Result = CGMI->second; - return; - } - switch (N->getOpcode()) { default: break; case ISD::SDIV: case ISD::UDIV: { // FIXME: should use a custom expander to expose the SRA to the dag. SDOperand DivLHS, DivRHS; - Select(DivLHS, N->getOperand(0)); - Select(DivRHS, N->getOperand(1)); + AddToQueue(DivLHS, N->getOperand(0)); + AddToQueue(DivRHS, N->getOperand(1)); // Set the Y register to the high-part. SDOperand TopPart; @@ -1119,8 +1110,8 @@ case ISD::MULHS: { // FIXME: Handle mul by immediate. SDOperand MulLHS, MulRHS; - Select(MulLHS, N->getOperand(0)); - Select(MulRHS, N->getOperand(1)); + AddToQueue(MulLHS, N->getOperand(0)); + AddToQueue(MulRHS, N->getOperand(1)); unsigned Opcode = N->getOpcode() == ISD::MULHU ? SP::UMULrr : SP::SMULrr; SDNode *Mul = CurDAG->getTargetNode(Opcode, MVT::i32, MVT::Flag, MulLHS, MulRHS); From evan.cheng at apple.com Mon Aug 7 17:28:36 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 17:28:36 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/X86/X86ISelDAGToDAG.cpp Message-ID: <200608072228.k77MSara015321@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/X86: X86ISelDAGToDAG.cpp updated: 1.88 -> 1.89 --- Log message: Match tablegen isel changes. --- Diffs of the changes: (+54 -101) X86ISelDAGToDAG.cpp | 155 ++++++++++++++++++---------------------------------- 1 files changed, 54 insertions(+), 101 deletions(-) Index: llvm/lib/Target/X86/X86ISelDAGToDAG.cpp diff -u llvm/lib/Target/X86/X86ISelDAGToDAG.cpp:1.88 llvm/lib/Target/X86/X86ISelDAGToDAG.cpp:1.89 --- llvm/lib/Target/X86/X86ISelDAGToDAG.cpp:1.88 Wed Aug 2 17:01:32 2006 +++ llvm/lib/Target/X86/X86ISelDAGToDAG.cpp Mon Aug 7 17:28:20 2006 @@ -12,7 +12,7 @@ // //===----------------------------------------------------------------------===// -#define DEBUG_TYPE "isel" +#define DEBUG_TYPE "x86-isel" #include "X86.h" #include "X86InstrBuilder.h" #include "X86ISelLowering.h" @@ -35,6 +35,7 @@ #include "llvm/ADT/Statistic.h" #include #include +#include #include using namespace llvm; @@ -99,7 +100,7 @@ : SelectionDAGISel(X86Lowering), X86Lowering(*TM.getTargetLowering()), Subtarget(&TM.getSubtarget()), - DAGSize(0), ReachabilityMatrix(NULL), ReachMatrixRange(NULL) {} + ReachabilityMatrix(NULL) {} virtual bool runOnFunction(Function &Fn) { // Make sure we re-emit a set of the global base reg if necessary @@ -123,7 +124,7 @@ #include "X86GenDAGISel.inc" private: - void DetermineReachability(SDNode *f, SDNode *t); + void DetermineReachability(); void Select(SDOperand &Result, SDOperand N); @@ -135,6 +136,18 @@ bool TryFoldLoad(SDOperand P, SDOperand N, SDOperand &Base, SDOperand &Scale, SDOperand &Index, SDOperand &Disp); + + virtual void SelectRootInit() { + DAGSize = CurDAG->AssignTopologicalOrder(TopOrder); + unsigned NumBytes = (DAGSize + 7) / 8; + UnfoldableSet = new unsigned char[NumBytes]; + memset(UnfoldableSet, 0, NumBytes); + unsigned RMSize = (DAGSize * DAGSize + 7) / 8; + ReachabilityMatrix = new unsigned char[RMSize]; + memset(ReachabilityMatrix, 0, RMSize); + DetermineReachability(); + } + /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for /// inline asm expressions. virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op, @@ -179,22 +192,10 @@ /// base register. Return the virtual register that holds this value. SDOperand getGlobalBaseReg(); - /// DAGSize - Number of nodes in the DAG. - /// - unsigned DAGSize; - - /// TopOrder - Topological ordering of all nodes in the DAG. - /// - std::vector TopOrder; - /// ReachabilityMatrix - A N x N matrix representing all pairs reachability /// information. One bit per potential edge. unsigned char *ReachabilityMatrix; - /// ReachMatrixRange - The range of reachability information available for - /// the particular source node. - unsigned *ReachMatrixRange; - inline void setReachable(SDNode *f, SDNode *t) { unsigned Idx = f->getNodeId() * DAGSize + t->getNodeId(); ReachabilityMatrix[Idx / 8] |= 1 << (Idx % 8); @@ -243,7 +244,6 @@ // / [X] // | ^ // [U]--------| - DetermineReachability(U, N); assert(isReachable(U, N) && "Attempting to fold a non-operand node?"); for (SDNode::op_iterator I = U->op_begin(), E = U->op_end(); I != E; ++I) { SDNode *P = I->Val; @@ -255,23 +255,15 @@ /// DetermineReachability - Determine reachability between all pairs of nodes /// between f and t in topological order. -void X86DAGToDAGISel::DetermineReachability(SDNode *f, SDNode *t) { - unsigned Orderf = f->getNodeId(); - unsigned Ordert = t->getNodeId(); - unsigned Range = ReachMatrixRange[Orderf]; - if (Range >= Ordert) - return; - if (Range < Orderf) - Range = Orderf; - - for (unsigned i = Range; i < Ordert; ++i) { +void X86DAGToDAGISel::DetermineReachability() { + for (unsigned i = 0; i < DAGSize; ++i) { SDNode *N = TopOrder[i]; setReachable(N, N); // If N is a leaf node, there is nothing more to do. if (N->getNumOperands() == 0) continue; - for (unsigned i2 = Range; ; ++i2) { + for (unsigned i2 = 0; ; ++i2) { SDNode *M = TopOrder[i2]; if (isReachable(M, N)) { // Update reachability from M to N's operands. @@ -284,8 +276,6 @@ if (M == N) break; } } - - ReachMatrixRange[Orderf] = Ordert; } /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel @@ -294,16 +284,6 @@ DEBUG(BB->dump()); MachineFunction::iterator FirstMBB = BB; - DAGSize = DAG.AssignTopologicalOrder(TopOrder); - unsigned RMSize = (DAGSize * DAGSize + 7) / 8; - ReachabilityMatrix = new unsigned char[RMSize]; - memset(ReachabilityMatrix, 0, RMSize); - ReachMatrixRange = new unsigned[DAGSize]; - memset(ReachMatrixRange, 0, DAGSize * sizeof(unsigned)); - unsigned NumBytes = (DAGSize + 7) / 8; - UnfoldableSet = new unsigned char[NumBytes]; - memset(UnfoldableSet, 0, NumBytes); - // Codegen the basic block. #ifndef NDEBUG DEBUG(std::cerr << "===== Instruction selection begins:\n"); @@ -315,15 +295,9 @@ #endif delete[] ReachabilityMatrix; - delete[] ReachMatrixRange; delete[] UnfoldableSet; ReachabilityMatrix = NULL; - ReachMatrixRange = NULL; UnfoldableSet = NULL; - TopOrder.clear(); - CodeGenMap.clear(); - HandleMap.clear(); - ReplaceMap.clear(); DAG.RemoveDeadNodes(); // Emit machine code to BB. @@ -414,13 +388,8 @@ /// addressing mode bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM, bool isRoot) { - bool Available = false; - // If N has already been selected, reuse the result unless in some very - // specific cases. - std::map::iterator CGMI= CodeGenMap.find(N.getValue(0)); - if (CGMI != CodeGenMap.end()) { - Available = true; - } + int id = N.Val->getNodeId(); + bool Available = isSelected(id); switch (N.getOpcode()) { default: break; @@ -664,7 +633,6 @@ SDOperand &Index, SDOperand &Disp) { if (N.getOpcode() == ISD::LOAD && N.hasOneUse() && - !CodeGenMap.count(N.getValue(0)) && !CanBeFoldedBy(N.Val, P.Val)) return SelectAddr(N.getOperand(1), Base, Scale, Index, Disp); return false; @@ -727,23 +695,11 @@ return; // Already selected. } - std::map::iterator CGMI = CodeGenMap.find(N); - if (CGMI != CodeGenMap.end()) { - Result = CGMI->second; -#ifndef NDEBUG - DEBUG(std::cerr << std::string(Indent-2, ' ')); - DEBUG(std::cerr << "== "); - DEBUG(Result.Val->dump(CurDAG)); - DEBUG(std::cerr << "\n"); - Indent -= 2; -#endif - return; - } - switch (Opcode) { default: break; case X86ISD::GlobalBaseReg: Result = getGlobalBaseReg(); + ReplaceUses(N, Result); return; case ISD::ADD: { @@ -774,7 +730,8 @@ Result = CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, MVT::i32, C); } else { SDNode *ResNode = CurDAG->getTargetNode(X86::MOV32ri, MVT::i32, C); - Result = CodeGenMap[N] = SDOperand(ResNode, 0); + Result = SDOperand(ResNode, 0); + ReplaceUses(N, Result); } return; } @@ -826,42 +783,40 @@ SDOperand Chain; if (foldedLoad) - Select(Chain, N1.getOperand(0)); + AddToQueue(Chain, N1.getOperand(0)); else Chain = CurDAG->getEntryNode(); SDOperand InFlag(0, 0); - Select(N0, N0); + AddToQueue(N0, N0); Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT), N0, InFlag); InFlag = Chain.getValue(1); if (foldedLoad) { - Select(Tmp0, Tmp0); - Select(Tmp1, Tmp1); - Select(Tmp2, Tmp2); - Select(Tmp3, Tmp3); + AddToQueue(Tmp0, Tmp0); + AddToQueue(Tmp1, Tmp1); + AddToQueue(Tmp2, Tmp2); + AddToQueue(Tmp3, Tmp3); SDNode *CNode = CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag); Chain = SDOperand(CNode, 0); InFlag = SDOperand(CNode, 1); } else { - Select(N1, N1); + AddToQueue(N1, N1); InFlag = SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0); } Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag); - CodeGenMap[N.getValue(0)] = Result; - if (foldedLoad) { - CodeGenMap[N1.getValue(1)] = Result.getValue(1); - AddHandleReplacement(N1.Val, 1, Result.Val, 1); - } + ReplaceUses(N.getValue(0), Result); + if (foldedLoad) + ReplaceUses(N1.getValue(1), Result.getValue(1)); #ifndef NDEBUG DEBUG(std::cerr << std::string(Indent-2, ' ')); - DEBUG(std::cerr << "== "); + DEBUG(std::cerr << "=> "); DEBUG(Result.Val->dump(CurDAG)); DEBUG(std::cerr << "\n"); Indent -= 2; @@ -919,12 +874,12 @@ foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3); SDOperand Chain; if (foldedLoad) - Select(Chain, N1.getOperand(0)); + AddToQueue(Chain, N1.getOperand(0)); else Chain = CurDAG->getEntryNode(); SDOperand InFlag(0, 0); - Select(N0, N0); + AddToQueue(N0, N0); Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT), N0, InFlag); InFlag = Chain.getValue(1); @@ -942,32 +897,30 @@ } if (foldedLoad) { - Select(Tmp0, Tmp0); - Select(Tmp1, Tmp1); - Select(Tmp2, Tmp2); - Select(Tmp3, Tmp3); + AddToQueue(Tmp0, Tmp0); + AddToQueue(Tmp1, Tmp1); + AddToQueue(Tmp2, Tmp2); + AddToQueue(Tmp3, Tmp3); SDNode *CNode = CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag); Chain = SDOperand(CNode, 0); InFlag = SDOperand(CNode, 1); } else { - Select(N1, N1); + AddToQueue(N1, N1); InFlag = SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0); } Result = CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg, NVT, InFlag); - CodeGenMap[N.getValue(0)] = Result; - if (foldedLoad) { - CodeGenMap[N1.getValue(1)] = Result.getValue(1); - AddHandleReplacement(N1.Val, 1, Result.Val, 1); - } + ReplaceUses(N.getValue(0), Result); + if (foldedLoad) + ReplaceUses(N1.getValue(1), Result.getValue(1)); #ifndef NDEBUG DEBUG(std::cerr << std::string(Indent-2, ' ')); - DEBUG(std::cerr << "== "); + DEBUG(std::cerr << "=> "); DEBUG(Result.Val->dump(CurDAG)); DEBUG(std::cerr << "\n"); Indent -= 2; @@ -994,14 +947,14 @@ } SDOperand Tmp0, Tmp1; - Select(Tmp0, Node->getOperand(0)); + AddToQueue(Tmp0, Node->getOperand(0)); Tmp1 = SDOperand(CurDAG->getTargetNode(Opc, VT, Tmp0), 0); - Result = CodeGenMap[N] = - SDOperand(CurDAG->getTargetNode(Opc2, NVT, Tmp1), 0); + Result = SDOperand(CurDAG->getTargetNode(Opc2, NVT, Tmp1), 0); + ReplaceUses(N, Result); #ifndef NDEBUG DEBUG(std::cerr << std::string(Indent-2, ' ')); - DEBUG(std::cerr << "== "); + DEBUG(std::cerr << "=> "); DEBUG(Result.Val->dump(CurDAG)); DEBUG(std::cerr << "\n"); Indent -= 2; @@ -1038,10 +991,10 @@ } OutOps.resize(4); - Select(OutOps[0], Op0); - Select(OutOps[1], Op1); - Select(OutOps[2], Op2); - Select(OutOps[3], Op3); + AddToQueue(OutOps[0], Op0); + AddToQueue(OutOps[1], Op1); + AddToQueue(OutOps[2], Op2); + AddToQueue(OutOps[3], Op3); return false; } From lattner at cs.uiuc.edu Mon Aug 7 18:03:19 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 18:03:19 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/CodeGen/SelectionDAG.h SelectionDAGNodes.h Message-ID: <200608072303.k77N3JXd021477@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/CodeGen: SelectionDAG.h updated: 1.108 -> 1.109 SelectionDAGNodes.h updated: 1.137 -> 1.138 --- Log message: Revamp the "CSEMap" datastructure used in the SelectionDAG class. This eliminates a bunch of std::map's in the SelectionDAG, replacing them with a home-grown hashtable. This is still a work in progress: not all the maps have been moved over and the hashtable never resizes. That said, this still speeds up llc 20% on kimwitu++ with -fast -regalloc=local using a release build. --- Diffs of the changes: (+24 -24) SelectionDAG.h | 29 ++++++++++------------------- SelectionDAGNodes.h | 19 ++++++++++++++----- 2 files changed, 24 insertions(+), 24 deletions(-) Index: llvm/include/llvm/CodeGen/SelectionDAG.h diff -u llvm/include/llvm/CodeGen/SelectionDAG.h:1.108 llvm/include/llvm/CodeGen/SelectionDAG.h:1.109 --- llvm/include/llvm/CodeGen/SelectionDAG.h:1.108 Fri Aug 4 12:45:20 2006 +++ llvm/include/llvm/CodeGen/SelectionDAG.h Mon Aug 7 18:03:03 2006 @@ -16,6 +16,7 @@ #define LLVM_CODEGEN_SELECTIONDAG_H #include "llvm/CodeGen/SelectionDAGNodes.h" +#include "llvm/CodeGen/SelectionDAGCSEMap.h" #include "llvm/ADT/ilist" #include @@ -441,13 +442,16 @@ private: void RemoveNodeFromCSEMaps(SDNode *N); SDNode *AddNonLeafNodeToCSEMaps(SDNode *N); - SDNode **FindModifiedNodeSlot(SDNode *N, SDOperand Op); - SDNode **FindModifiedNodeSlot(SDNode *N, SDOperand Op1, SDOperand Op2); - SDNode **FindModifiedNodeSlot(SDNode *N, const std::vector &Ops); + SDNode *FindModifiedNodeSlot(SDNode *N, SDOperand Op, void *&InsertPos); + SDNode *FindModifiedNodeSlot(SDNode *N, SDOperand Op1, SDOperand Op2, + void *&InsertPos); + SDNode *FindModifiedNodeSlot(SDNode *N, const std::vector &Ops, + void *&InsertPos); void DeleteNodeNotInCSEMaps(SDNode *N); - void setNodeValueTypes(SDNode *N, std::vector &RetVals); - void setNodeValueTypes(SDNode *N, MVT::ValueType VT1, MVT::ValueType VT2); + MVT::ValueType *getNodeValueTypes(MVT::ValueType VT1); + MVT::ValueType *getNodeValueTypes(MVT::ValueType VT1, MVT::ValueType VT2); + MVT::ValueType *getNodeValueTypes(std::vector &RetVals); /// SimplifySetCC - Try to simplify a setcc built with the specified operands @@ -460,17 +464,10 @@ // Maps to auto-CSE operations. std::map, SDNode *> NullaryOps; - std::map >, - SDNode *> UnaryOps; - std::map >, - SDNode *> BinaryOps; std::map, RegisterSDNode*> RegNodes; std::vector CondCodeNodes; - std::map >, - SDNode *> Loads; - std::map, SDNode*> GlobalValues; std::map, SDNode*> TargetGlobalValues; std::map, SDNode*> Constants; @@ -488,13 +485,7 @@ std::map ExternalSymbols; std::map TargetExternalSymbols; std::map StringNodes; - std::map > >, - SDNode*> OneResultNodes; - std::map, - std::vector > >, - SDNode*> ArbitraryNodes; + SelectionDAGCSEMap CSEMap; }; template <> struct GraphTraits : public GraphTraits { Index: llvm/include/llvm/CodeGen/SelectionDAGNodes.h diff -u llvm/include/llvm/CodeGen/SelectionDAGNodes.h:1.137 llvm/include/llvm/CodeGen/SelectionDAGNodes.h:1.138 --- llvm/include/llvm/CodeGen/SelectionDAGNodes.h:1.137 Thu Jul 27 01:38:21 2006 +++ llvm/include/llvm/CodeGen/SelectionDAGNodes.h Mon Aug 7 18:03:03 2006 @@ -707,6 +707,9 @@ SDNode *Prev, *Next; friend struct ilist_traits; + /// NextInBucket - This is used by the SelectionDAGCSEMap. + void *NextInBucket; + /// Uses - These are all of the SDNode's that use a value produced by this /// node. std::vector Uses; @@ -789,6 +792,11 @@ static bool classof(const SDNode *) { return true; } + + /// NextInBucket accessors, these are private to SelectionDAGCSEMap. + void *getNextInBucket() const { return NextInBucket; } + void SetNextInBucket(void *N) { NextInBucket = N; } + protected: friend class SelectionDAG; @@ -801,6 +809,7 @@ ValueList = getValueTypeList(VT); NumValues = 1; Prev = 0; Next = 0; + NextInBucket = 0; } SDNode(unsigned NT, SDOperand Op) : NodeType(NT), NodeId(-1) { @@ -811,6 +820,7 @@ ValueList = 0; NumValues = 0; Prev = 0; Next = 0; + NextInBucket = 0; } SDNode(unsigned NT, SDOperand N1, SDOperand N2) : NodeType(NT), NodeId(-1) { @@ -822,6 +832,7 @@ ValueList = 0; NumValues = 0; Prev = 0; Next = 0; + NextInBucket = 0; } SDNode(unsigned NT, SDOperand N1, SDOperand N2, SDOperand N3) : NodeType(NT), NodeId(-1) { @@ -836,6 +847,7 @@ ValueList = 0; NumValues = 0; Prev = 0; Next = 0; + NextInBucket = 0; } SDNode(unsigned NT, SDOperand N1, SDOperand N2, SDOperand N3, SDOperand N4) : NodeType(NT), NodeId(-1) { @@ -851,6 +863,7 @@ ValueList = 0; NumValues = 0; Prev = 0; Next = 0; + NextInBucket = 0; } SDNode(unsigned Opc, const std::vector &Nodes) : NodeType(Opc), NodeId(-1) { @@ -865,6 +878,7 @@ ValueList = 0; NumValues = 0; Prev = 0; Next = 0; + NextInBucket = 0; } /// MorphNodeTo - This clears the return value and operands list, and sets the @@ -884,11 +898,6 @@ NumOperands = 0; } - void setValueTypes(MVT::ValueType VT) { - assert(NumValues == 0 && "Should not have values yet!"); - ValueList = getValueTypeList(VT); - NumValues = 1; - } void setValueTypes(MVT::ValueType *List, unsigned NumVal) { assert(NumValues == 0 && "Should not have values yet!"); ValueList = List; From lattner at cs.uiuc.edu Mon Aug 7 18:03:19 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 18:03:19 -0500 Subject: [llvm-commits] CVS: llvm/lib/CodeGen/SelectionDAG/SelectionDAGCSEMap.cpp SelectionDAG.cpp Message-ID: <200608072303.k77N3Jg7021473@zion.cs.uiuc.edu> Changes in directory llvm/lib/CodeGen/SelectionDAG: SelectionDAGCSEMap.cpp added (r1.1) SelectionDAG.cpp updated: 1.318 -> 1.319 --- Log message: Revamp the "CSEMap" datastructure used in the SelectionDAG class. This eliminates a bunch of std::map's in the SelectionDAG, replacing them with a home-grown hashtable. This is still a work in progress: not all the maps have been moved over and the hashtable never resizes. That said, this still speeds up llc 20% on kimwitu++ with -fast -regalloc=local using a release build. --- Diffs of the changes: (+517 -312) SelectionDAG.cpp | 590 +++++++++++++++++++++++-------------------------- SelectionDAGCSEMap.cpp | 239 +++++++++++++++++++ 2 files changed, 517 insertions(+), 312 deletions(-) Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAGCSEMap.cpp diff -c /dev/null llvm/lib/CodeGen/SelectionDAG/SelectionDAGCSEMap.cpp:1.1 *** /dev/null Mon Aug 7 18:03:13 2006 --- llvm/lib/CodeGen/SelectionDAG/SelectionDAGCSEMap.cpp Mon Aug 7 18:03:03 2006 *************** *** 0 **** --- 1,239 ---- + //===-- SelectionDAGCSEMap.cpp - Implement the SelectionDAG CSE Map -------===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Chris Lattner and is distributed under + // the University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This implements the SelectionDAGCSEMap class. + // + //===----------------------------------------------------------------------===// + + #include "llvm/CodeGen/SelectionDAG.h" + using namespace llvm; + + //===----------------------------------------------------------------------===// + // SelectionDAGCSEMap::NodeID Implementation + + SelectionDAGCSEMap::NodeID::NodeID(SDNode *N) { + SetOpcode(N->getOpcode()); + // Add the return value info. + SetValueTypes(N->value_begin()); + // Add the operand info. + SetOperands(N->op_begin(), N->getNumOperands()); + } + + SelectionDAGCSEMap::NodeID::NodeID(unsigned short ID, const void *VTList) { + SetOpcode(ID); + SetValueTypes(VTList); + SetOperands(); + } + SelectionDAGCSEMap::NodeID::NodeID(unsigned short ID, const void *VTList, + SDOperand Op) { + SetOpcode(ID); + SetValueTypes(VTList); + SetOperands(Op); + } + SelectionDAGCSEMap::NodeID::NodeID(unsigned short ID, const void *VTList, + SDOperand Op1, SDOperand Op2) { + SetOpcode(ID); + SetValueTypes(VTList); + SetOperands(Op1, Op2); + } + SelectionDAGCSEMap::NodeID::NodeID(unsigned short ID, const void *VTList, + SDOperand Op1, SDOperand Op2, + SDOperand Op3) { + SetOpcode(ID); + SetValueTypes(VTList); + SetOperands(Op1, Op2, Op3); + } + SelectionDAGCSEMap::NodeID::NodeID(unsigned short ID, const void *VTList, + const SDOperand *OpList, unsigned N) { + SetOpcode(ID); + SetValueTypes(VTList); + SetOperands(OpList, N); + } + + void SelectionDAGCSEMap::NodeID::AddPointer(const void *Ptr) { + // Note: this adds pointers to the hash using sizes and endianness that depend + // on the host. It doesn't matter however, because hashing on pointer values + // in inherently unstable. Nothing in the SelectionDAG should depend on the + // ordering of nodes in the CSEMap. + union { + intptr_t PtrI; + unsigned char PtrA[sizeof(intptr_t)]; + }; + PtrI = (intptr_t)Ptr; + Bits.append(PtrA, PtrA+sizeof(intptr_t)); + } + + void SelectionDAGCSEMap::NodeID::AddOperand(SDOperand Op) { + AddPointer(Op.Val); + // 2 bytes of resno might be too small, three should certainly be enough. :) + assert(Op.ResNo < (1 << 24) && "ResNo too large for CSE Map to handle!"); + Bits.push_back((Op.ResNo >> 0) & 0xFF); + Bits.push_back((Op.ResNo >> 8) & 0xFF); + Bits.push_back((Op.ResNo >> 16) & 0xFF); + } + + void SelectionDAGCSEMap::NodeID::SetOperands(const SDOperand *Ops, + unsigned NumOps) { + for (; NumOps; --NumOps, ++Ops) + AddOperand(*Ops); + } + + + /// ComputeHash - Compute a strong hash value for this NodeID, for lookup in + /// the SelectionDAGCSEMap. + unsigned SelectionDAGCSEMap::NodeID::ComputeHash() const { + // FIXME: this hash function sucks. + unsigned Hash = 0; + for (unsigned i = 0, e = Bits.size(); i != e; ++i) + Hash += Bits[i]; + return Hash; + } + + bool SelectionDAGCSEMap::NodeID::operator==(const NodeID &RHS) const { + if (Bits.size() != RHS.Bits.size()) return false; + return memcmp(&Bits[0], &RHS.Bits[0], Bits.size()) == 0; + } + + + //===----------------------------------------------------------------------===// + // SelectionDAGCSEMap Implementation + + SelectionDAGCSEMap::SelectionDAGCSEMap() { + NumBuckets = 256; + Buckets = new void*[NumBuckets]; + memset(Buckets, 0, NumBuckets*sizeof(void*)); + } + SelectionDAGCSEMap::~SelectionDAGCSEMap() { + delete [] Buckets; + } + + /// GetNextPtr - In order to save space, each bucket is a singly-linked-list. In + /// order to make deletion more efficient, we make the list circular, so we can + /// delete a node without computing its hash. The problem with this is that the + /// start of the hash buckets are not SDNodes. If NextInBucketPtr is a bucket + /// pointer, this method returns null: use GetBucketPtr when this happens. + SDNode *SelectionDAGCSEMap::GetNextPtr(void *NextInBucketPtr) { + if (NextInBucketPtr >= Buckets && NextInBucketPtr < Buckets+NumBuckets) + return 0; + return static_cast(NextInBucketPtr); + } + + void **SelectionDAGCSEMap::GetBucketPtr(void *NextInBucketPtr) { + assert(NextInBucketPtr >= Buckets && NextInBucketPtr < Buckets+NumBuckets && + "NextInBucketPtr is not a bucket ptr"); + return static_cast(NextInBucketPtr); + } + + /// GetBucketFor - Hash the specified node ID and return the hash bucket for the + /// specified ID. + void **SelectionDAGCSEMap::GetBucketFor(const NodeID &ID) const { + // TODO: if load is high, resize hash table. + + // NumBuckets is always a power of 2. + unsigned BucketNum = ID.ComputeHash() & (NumBuckets-1); + return Buckets+BucketNum; + } + + /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists, + /// return it. If not, return the insertion token that will make insertion + /// faster. + SDNode *SelectionDAGCSEMap::FindNodeOrInsertPos(const NodeID &ID, + void *&InsertPos) { + void **Bucket = GetBucketFor(ID); + void *Probe = *Bucket; + + InsertPos = 0; + + unsigned Opc = ID.getOpcode(); + while (SDNode *NodeInBucket = GetNextPtr(Probe)) { + // If we found a node with the same opcode, it might be a matching node. + // Because it is in the same bucket as this one, we know the hash values + // match. Compute the NodeID for the possible match and do a final compare. + if (NodeInBucket->getOpcode() == Opc) { + NodeID OtherID(NodeInBucket); + if (OtherID == ID) + return NodeInBucket; + } + + Probe = NodeInBucket->getNextInBucket(); + } + + // Didn't find the node, return null with the bucket as the InsertPos. + InsertPos = Bucket; + return 0; + } + + /// InsertNode - Insert the specified node into the CSE Map, knowing that it + /// is not already in the map. InsertPos must be obtained from + /// FindNodeOrInsertPos. + void SelectionDAGCSEMap::InsertNode(SDNode *N, void *InsertPos) { + /// The insert position is actually a bucket pointer. + void **Bucket = static_cast(InsertPos); + + void *Next = *Bucket; + + // If this is the first insertion into this bucket, its next pointer will be + // null. Pretend as if it pointed to itself. + if (Next == 0) + Next = Bucket; + + // Set the nodes next pointer, and make the bucket point to the node. + N->SetNextInBucket(Next); + *Bucket = N; + } + + + /// RemoveNode - Remove a node from the CSE map, returning true if one was + /// removed or false if the node was not in the CSE map. + bool SelectionDAGCSEMap::RemoveNode(SDNode *N) { + // Because each bucket is a circular list, we don't need to compute N's hash + // to remove it. Chase around the list until we find the node (or bucket) + // which points to N. + void *Ptr = N->getNextInBucket(); + if (Ptr == 0) return false; // Not in CSEMap. + + void *NodeNextPtr = Ptr; + N->SetNextInBucket(0); + while (1) { + if (SDNode *NodeInBucket = GetNextPtr(Ptr)) { + // Advance pointer. + Ptr = NodeInBucket->getNextInBucket(); + + // We found a node that points to N, change it to point to N's next node, + // removing N from the list. + if (Ptr == N) { + NodeInBucket->SetNextInBucket(NodeNextPtr); + return true; + } + } else { + void **Bucket = GetBucketPtr(Ptr); + Ptr = *Bucket; + + // If we found that the bucket points to N, update the bucket to point to + // whatever is next. + if (Ptr == N) { + *Bucket = NodeNextPtr; + return true; + } + } + } + } + + /// GetOrInsertSimpleNode - If there is an existing simple SDNode exactly + /// equal to the specified node, return it. Otherwise, insert 'N' and it + /// instead. This only works on *simple* SDNodes, not ConstantSDNode or any + /// other classes derived from SDNode. + SDNode *SelectionDAGCSEMap::GetOrInsertNode(SDNode *N) { + SelectionDAGCSEMap::NodeID ID(N); + void *IP; + if (SDNode *E = FindNodeOrInsertPos(ID, IP)) + return E; + InsertNode(N, IP); + return N; + } Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp diff -u llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.318 llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.319 --- llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.318 Mon Aug 7 17:13:29 2006 +++ llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp Mon Aug 7 18:03:03 2006 @@ -29,7 +29,6 @@ #include #include #include -#include using namespace llvm; static bool isCommutativeBinOp(unsigned Opcode) { @@ -430,40 +429,18 @@ Erased =ValueNodes.erase(std::make_pair(SVN->getValue(), SVN->getOffset())); break; } - case ISD::LOAD: - Erased = Loads.erase(std::make_pair(N->getOperand(1), - std::make_pair(N->getOperand(0), - N->getValueType(0)))); - break; default: if (N->getNumValues() == 1) { if (N->getNumOperands() == 0) { Erased = NullaryOps.erase(std::make_pair(N->getOpcode(), N->getValueType(0))); - } else if (N->getNumOperands() == 1) { - Erased = - UnaryOps.erase(std::make_pair(N->getOpcode(), - std::make_pair(N->getOperand(0), - N->getValueType(0)))); - } else if (N->getNumOperands() == 2) { - Erased = - BinaryOps.erase(std::make_pair(N->getOpcode(), - std::make_pair(N->getOperand(0), - N->getOperand(1)))); } else { - std::vector Ops(N->op_begin(), N->op_end()); - Erased = - OneResultNodes.erase(std::make_pair(N->getOpcode(), - std::make_pair(N->getValueType(0), - Ops))); + // Remove it from the CSE Map. + Erased = CSEMap.RemoveNode(N); } } else { - // Remove the node from the ArbitraryNodes map. - std::vector RV(N->value_begin(), N->value_end()); - std::vector Ops(N->op_begin(), N->op_end()); - Erased = - ArbitraryNodes.erase(std::make_pair(N->getOpcode(), - std::make_pair(RV, Ops))); + // Remove it from the CSE Map. + Erased = CSEMap.RemoveNode(N); } break; } @@ -495,43 +472,8 @@ if (N->getValueType(i) == MVT::Flag) return 0; // Never CSE anything that produces a flag. - if (N->getNumValues() == 1) { - if (N->getNumOperands() == 1) { - SDNode *&U = UnaryOps[std::make_pair(N->getOpcode(), - std::make_pair(N->getOperand(0), - N->getValueType(0)))]; - if (U) return U; - U = N; - } else if (N->getNumOperands() == 2) { - SDNode *&B = BinaryOps[std::make_pair(N->getOpcode(), - std::make_pair(N->getOperand(0), - N->getOperand(1)))]; - if (B) return B; - B = N; - } else { - std::vector Ops(N->op_begin(), N->op_end()); - SDNode *&ORN = OneResultNodes[std::make_pair(N->getOpcode(), - std::make_pair(N->getValueType(0), Ops))]; - if (ORN) return ORN; - ORN = N; - } - } else { - if (N->getOpcode() == ISD::LOAD) { - SDNode *&L = Loads[std::make_pair(N->getOperand(1), - std::make_pair(N->getOperand(0), - N->getValueType(0)))]; - if (L) return L; - L = N; - } else { - // Remove the node from the ArbitraryNodes map. - std::vector RV(N->value_begin(), N->value_end()); - std::vector Ops(N->op_begin(), N->op_end()); - SDNode *&AN = ArbitraryNodes[std::make_pair(N->getOpcode(), - std::make_pair(RV, Ops))]; - if (AN) return AN; - AN = N; - } - } + SDNode *New = CSEMap.GetOrInsertNode(N); + if (New != N) return New; // Node already existed. return 0; } @@ -539,7 +481,8 @@ /// were replaced with those specified. If this node is never memoized, /// return null, otherwise return a pointer to the slot it would take. If a /// node already exists with these operands, the slot will be non-null. -SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op) { +SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op, + void *&InsertPos) { if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag) return 0; // Never add these nodes. @@ -548,26 +491,20 @@ if (N->getValueType(i) == MVT::Flag) return 0; // Never CSE anything that produces a flag. - if (N->getNumValues() == 1) { - return &UnaryOps[std::make_pair(N->getOpcode(), - std::make_pair(Op, N->getValueType(0)))]; - } else { - // Remove the node from the ArbitraryNodes map. - std::vector RV(N->value_begin(), N->value_end()); - std::vector Ops; - Ops.push_back(Op); - return &ArbitraryNodes[std::make_pair(N->getOpcode(), - std::make_pair(RV, Ops))]; - } - return 0; + SelectionDAGCSEMap::NodeID ID; + ID.SetOpcode(N->getOpcode()); + ID.SetValueTypes(N->value_begin()); + ID.SetOperands(Op); + return CSEMap.FindNodeOrInsertPos(ID, InsertPos); } /// FindModifiedNodeSlot - Find a slot for the specified node if its operands /// were replaced with those specified. If this node is never memoized, /// return null, otherwise return a pointer to the slot it would take. If a /// node already exists with these operands, the slot will be non-null. -SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, - SDOperand Op1, SDOperand Op2) { +SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, + SDOperand Op1, SDOperand Op2, + void *&InsertPos) { if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag) return 0; // Never add these nodes. @@ -575,19 +512,12 @@ for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) if (N->getValueType(i) == MVT::Flag) return 0; // Never CSE anything that produces a flag. - - if (N->getNumValues() == 1) { - return &BinaryOps[std::make_pair(N->getOpcode(), - std::make_pair(Op1, Op2))]; - } else { - std::vector RV(N->value_begin(), N->value_end()); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - return &ArbitraryNodes[std::make_pair(N->getOpcode(), - std::make_pair(RV, Ops))]; - } - return 0; + + SelectionDAGCSEMap::NodeID ID; + ID.SetOpcode(N->getOpcode()); + ID.SetValueTypes(N->value_begin()); + ID.SetOperands(Op1, Op2); + return CSEMap.FindNodeOrInsertPos(ID, InsertPos); } @@ -595,8 +525,9 @@ /// were replaced with those specified. If this node is never memoized, /// return null, otherwise return a pointer to the slot it would take. If a /// node already exists with these operands, the slot will be non-null. -SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, - const std::vector &Ops) { +SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, + const std::vector &Ops, + void *&InsertPos) { if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag) return 0; // Never add these nodes. @@ -605,30 +536,11 @@ if (N->getValueType(i) == MVT::Flag) return 0; // Never CSE anything that produces a flag. - if (N->getNumValues() == 1) { - if (N->getNumOperands() == 1) { - return &UnaryOps[std::make_pair(N->getOpcode(), - std::make_pair(Ops[0], - N->getValueType(0)))]; - } else if (N->getNumOperands() == 2) { - return &BinaryOps[std::make_pair(N->getOpcode(), - std::make_pair(Ops[0], Ops[1]))]; - } else { - return &OneResultNodes[std::make_pair(N->getOpcode(), - std::make_pair(N->getValueType(0), - Ops))]; - } - } else { - if (N->getOpcode() == ISD::LOAD) { - return &Loads[std::make_pair(Ops[1], - std::make_pair(Ops[0], N->getValueType(0)))]; - } else { - std::vector RV(N->value_begin(), N->value_end()); - return &ArbitraryNodes[std::make_pair(N->getOpcode(), - std::make_pair(RV, Ops))]; - } - } - return 0; + SelectionDAGCSEMap::NodeID ID; + ID.SetOpcode(N->getOpcode()); + ID.SetValueTypes(N->value_begin()); + ID.SetOperands(&Ops[0], Ops.size()); + return CSEMap.FindNodeOrInsertPos(ID, InsertPos); } @@ -1235,14 +1147,19 @@ } SDNode *N; + MVT::ValueType *VTs = getNodeValueTypes(VT); if (VT != MVT::Flag) { // Don't CSE flag producing nodes - SDNode *&E = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))]; - if (E) return SDOperand(E, 0); - E = N = new SDNode(Opcode, Operand); + SelectionDAGCSEMap::NodeID ID(Opcode, VTs, Operand); + void *IP = 0; + if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(E, 0); + N = new SDNode(Opcode, Operand); + N->setValueTypes(VTs, 1); + CSEMap.InsertNode(N, IP); } else { N = new SDNode(Opcode, Operand); + N->setValueTypes(VTs, 1); } - N->setValueTypes(VT); AllNodes.push_back(N); return SDOperand(N, 0); } @@ -1502,16 +1419,20 @@ // Memoize this node if possible. SDNode *N; + MVT::ValueType *VTs = getNodeValueTypes(VT); if (VT != MVT::Flag) { - SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))]; - if (BON) return SDOperand(BON, 0); - - BON = N = new SDNode(Opcode, N1, N2); + SelectionDAGCSEMap::NodeID ID(Opcode, VTs, N1, N2); + void *IP = 0; + if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(E, 0); + N = new SDNode(Opcode, N1, N2); + N->setValueTypes(VTs, 1); + CSEMap.InsertNode(N, IP); } else { N = new SDNode(Opcode, N1, N2); + N->setValueTypes(VTs, 1); } - N->setValueTypes(VT); AllNodes.push_back(N); return SDOperand(N, 0); } @@ -1554,22 +1475,22 @@ break; } - std::vector Ops; - Ops.reserve(3); - Ops.push_back(N1); - Ops.push_back(N2); - Ops.push_back(N3); - // Memoize node if it doesn't produce a flag. SDNode *N; + MVT::ValueType *VTs = getNodeValueTypes(VT); + if (VT != MVT::Flag) { - SDNode *&E = OneResultNodes[std::make_pair(Opcode,std::make_pair(VT, Ops))]; - if (E) return SDOperand(E, 0); - E = N = new SDNode(Opcode, N1, N2, N3); + SelectionDAGCSEMap::NodeID ID(Opcode, VTs, N1, N2, N3); + void *IP = 0; + if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(E, 0); + N = new SDNode(Opcode, N1, N2, N3); + N->setValueTypes(VTs, 1); + CSEMap.InsertNode(N, IP); } else { N = new SDNode(Opcode, N1, N2, N3); + N->setValueTypes(VTs, 1); } - N->setValueTypes(VT); AllNodes.push_back(N); return SDOperand(N, 0); } @@ -1602,12 +1523,15 @@ SDOperand SelectionDAG::getLoad(MVT::ValueType VT, SDOperand Chain, SDOperand Ptr, SDOperand SV) { - SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))]; - if (N) return SDOperand(N, 0); - N = new SDNode(ISD::LOAD, Chain, Ptr, SV); - - // Loads have a token chain. - setNodeValueTypes(N, VT, MVT::Other); + MVT::ValueType *VTs = getNodeValueTypes(VT, MVT::Other); + + SelectionDAGCSEMap::NodeID ID(ISD::LOAD, VTs, Chain, Ptr, SV); + void *IP = 0; + if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(E, 0); + SDNode *N = new SDNode(ISD::LOAD, Chain, Ptr, SV); + N->setValueTypes(VTs, 2); + CSEMap.InsertNode(N, IP); AllNodes.push_back(N); return SDOperand(N, 0); } @@ -1720,15 +1644,19 @@ // Memoize nodes. SDNode *N; + MVT::ValueType *VTs = getNodeValueTypes(VT); if (VT != MVT::Flag) { - SDNode *&E = - OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))]; - if (E) return SDOperand(E, 0); - E = N = new SDNode(Opcode, Ops); + SelectionDAGCSEMap::NodeID ID(Opcode, VTs, &Ops[0], Ops.size()); + void *IP = 0; + if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(E, 0); + N = new SDNode(Opcode, Ops); + N->setValueTypes(VTs, 1); + CSEMap.InsertNode(N, IP); } else { N = new SDNode(Opcode, Ops); + N->setValueTypes(VTs, 1); } - N->setValueTypes(VT); AllNodes.push_back(N); return SDOperand(N, 0); } @@ -1787,25 +1715,36 @@ // Memoize the node unless it returns a flag. SDNode *N; + MVT::ValueType *VTs = getNodeValueTypes(ResultTys); if (ResultTys.back() != MVT::Flag) { - SDNode *&E = - ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys, Ops))]; - if (E) return SDOperand(E, 0); - E = N = new SDNode(Opcode, Ops); + SelectionDAGCSEMap::NodeID ID; + ID.SetOpcode(Opcode); + ID.SetValueTypes(VTs); + ID.SetOperands(&Ops[0], Ops.size()); + void *IP = 0; + if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(E, 0); + N = new SDNode(Opcode, Ops); + N->setValueTypes(VTs, ResultTys.size()); + CSEMap.InsertNode(N, IP); } else { N = new SDNode(Opcode, Ops); + N->setValueTypes(VTs, ResultTys.size()); } - setNodeValueTypes(N, ResultTys); AllNodes.push_back(N); return SDOperand(N, 0); } -void SelectionDAG::setNodeValueTypes(SDNode *N, - std::vector &RetVals) { +MVT::ValueType *SelectionDAG::getNodeValueTypes(MVT::ValueType VT) { + return SDNode::getValueTypeList(VT); +} + +MVT::ValueType *SelectionDAG::getNodeValueTypes( + std::vector &RetVals) { switch (RetVals.size()) { - case 0: return; - case 1: N->setValueTypes(RetVals[0]); return; - case 2: setNodeValueTypes(N, RetVals[0], RetVals[1]); return; + case 0: assert(0 && "Cannot have nodes without results!"); + case 1: return SDNode::getValueTypeList(RetVals[0]); + case 2: return getNodeValueTypes(RetVals[0], RetVals[1]); default: break; } @@ -1816,23 +1755,21 @@ I = VTList.begin(); } - N->setValueTypes(&(*I)[0], I->size()); + return &(*I)[0]; } -void SelectionDAG::setNodeValueTypes(SDNode *N, MVT::ValueType VT1, - MVT::ValueType VT2) { +MVT::ValueType *SelectionDAG::getNodeValueTypes(MVT::ValueType VT1, + MVT::ValueType VT2) { for (std::list >::iterator I = VTList.begin(), E = VTList.end(); I != E; ++I) { - if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2) { - N->setValueTypes(&(*I)[0], 2); - return; - } + if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2) + return &(*I)[0]; } std::vector V; V.push_back(VT1); V.push_back(VT2); VTList.push_front(V); - N->setValueTypes(&(*VTList.begin())[0], 2); + return &(*VTList.begin())[0]; } /// UpdateNodeOperands - *Mutate* the specified node in-place to have the @@ -1850,12 +1787,12 @@ if (Op == N->getOperand(0)) return InN; // See if the modified node already exists. - SDNode **NewSlot = FindModifiedNodeSlot(N, Op); - if (NewSlot && *NewSlot) - return SDOperand(*NewSlot, InN.ResNo); + void *InsertPos = 0; + if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) + return SDOperand(Existing, InN.ResNo); // Nope it doesn't. Remove the node from it's current place in the maps. - if (NewSlot) + if (InsertPos) RemoveNodeFromCSEMaps(N); // Now we update the operands. @@ -1864,7 +1801,7 @@ N->OperandList[0] = Op; // If this gets put into a CSE map, add it. - if (NewSlot) *NewSlot = N; + if (InsertPos) CSEMap.InsertNode(N, InsertPos); return InN; } @@ -1879,12 +1816,12 @@ return InN; // No operands changed, just return the input node. // See if the modified node already exists. - SDNode **NewSlot = FindModifiedNodeSlot(N, Op1, Op2); - if (NewSlot && *NewSlot) - return SDOperand(*NewSlot, InN.ResNo); + void *InsertPos = 0; + if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) + return SDOperand(Existing, InN.ResNo); // Nope it doesn't. Remove the node from it's current place in the maps. - if (NewSlot) + if (InsertPos) RemoveNodeFromCSEMaps(N); // Now we update the operands. @@ -1900,7 +1837,7 @@ } // If this gets put into a CSE map, add it. - if (NewSlot) *NewSlot = N; + if (InsertPos) CSEMap.InsertNode(N, InsertPos); return InN; } @@ -1957,12 +1894,12 @@ if (!AnyChange) return InN; // See if the modified node already exists. - SDNode **NewSlot = FindModifiedNodeSlot(N, Ops); - if (NewSlot && *NewSlot) - return SDOperand(*NewSlot, InN.ResNo); + void *InsertPos = 0; + if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) + return SDOperand(Existing, InN.ResNo); // Nope it doesn't. Remove the node from it's current place in the maps. - if (NewSlot) + if (InsertPos) RemoveNodeFromCSEMaps(N); // Now we update the operands. @@ -1975,7 +1912,7 @@ } // If this gets put into a CSE map, add it. - if (NewSlot) *NewSlot = N; + if (InsertPos) CSEMap.InsertNode(N, InsertPos); return InN; } @@ -1999,7 +1936,7 @@ RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - N->setValueTypes(VT); + N->setValueTypes(getNodeValueTypes(VT), 1); ON = N; // Memoize the new node. return SDOperand(N, 0); @@ -2008,16 +1945,17 @@ SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT::ValueType VT, SDOperand Op1) { // If an identical node already exists, use it. - SDNode *&ON = UnaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(Op1, VT))]; - if (ON) return SDOperand(ON, 0); - + MVT::ValueType *VTs = getNodeValueTypes(VT); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs, Op1); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); + RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - N->setValueTypes(VT); + N->setValueTypes(getNodeValueTypes(VT), 1); N->setOperands(Op1); - - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); return SDOperand(N, 0); } @@ -2025,16 +1963,18 @@ MVT::ValueType VT, SDOperand Op1, SDOperand Op2) { // If an identical node already exists, use it. - SDNode *&ON = BinaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(Op1, Op2))]; - if (ON) return SDOperand(ON, 0); - + MVT::ValueType *VTs = getNodeValueTypes(VT); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs, Op1, Op2); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); + RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - N->setValueTypes(VT); + N->setValueTypes(VTs, 1); N->setOperands(Op1, Op2); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } @@ -2042,18 +1982,18 @@ MVT::ValueType VT, SDOperand Op1, SDOperand Op2, SDOperand Op3) { // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3); - SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VT, OpList))]; - if (ON) return SDOperand(ON, 0); - + MVT::ValueType *VTs = getNodeValueTypes(VT); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs, Op1, Op2, Op3); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); + RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - N->setValueTypes(VT); + N->setValueTypes(VTs, 1); N->setOperands(Op1, Op2, Op3); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } @@ -2062,40 +2002,46 @@ SDOperand Op2, SDOperand Op3, SDOperand Op4) { // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3); - OpList.push_back(Op4); - SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VT, OpList))]; - if (ON) return SDOperand(ON, 0); + MVT::ValueType *VTs = getNodeValueTypes(VT); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs); + ID.AddOperand(Op1); + ID.AddOperand(Op2); + ID.AddOperand(Op3); + ID.AddOperand(Op4); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - N->setValueTypes(VT); + N->setValueTypes(VTs, 1); N->setOperands(Op1, Op2, Op3, Op4); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT::ValueType VT, SDOperand Op1, - SDOperand Op2, SDOperand Op3,SDOperand Op4, - SDOperand Op5) { - // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3); - OpList.push_back(Op4); OpList.push_back(Op5); - SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VT, OpList))]; - if (ON) return SDOperand(ON, 0); - + SDOperand Op2, SDOperand Op3, + SDOperand Op4, SDOperand Op5) { + MVT::ValueType *VTs = getNodeValueTypes(VT); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs); + ID.AddOperand(Op1); + ID.AddOperand(Op2); + ID.AddOperand(Op3); + ID.AddOperand(Op4); + ID.AddOperand(Op5); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); + RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - N->setValueTypes(VT); + N->setValueTypes(VTs, 1); N->setOperands(Op1, Op2, Op3, Op4, Op5); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } @@ -2103,20 +2049,24 @@ MVT::ValueType VT, SDOperand Op1, SDOperand Op2, SDOperand Op3,SDOperand Op4, SDOperand Op5, SDOperand Op6) { - // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3); - OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6); - SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VT, OpList))]; - if (ON) return SDOperand(ON, 0); - + MVT::ValueType *VTs = getNodeValueTypes(VT); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs); + ID.AddOperand(Op1); + ID.AddOperand(Op2); + ID.AddOperand(Op3); + ID.AddOperand(Op4); + ID.AddOperand(Op5); + ID.AddOperand(Op6); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); + RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - N->setValueTypes(VT); + N->setValueTypes(VTs, 1); N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } @@ -2125,21 +2075,26 @@ SDOperand Op2, SDOperand Op3,SDOperand Op4, SDOperand Op5, SDOperand Op6, SDOperand Op7) { + MVT::ValueType *VTs = getNodeValueTypes(VT); // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3); - OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6); - OpList.push_back(Op7); - SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VT, OpList))]; - if (ON) return SDOperand(ON, 0); - + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs); + ID.AddOperand(Op1); + ID.AddOperand(Op2); + ID.AddOperand(Op3); + ID.AddOperand(Op4); + ID.AddOperand(Op5); + ID.AddOperand(Op6); + ID.AddOperand(Op7); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); + RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - N->setValueTypes(VT); + N->setValueTypes(VTs, 1); N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, @@ -2148,41 +2103,44 @@ SDOperand Op5, SDOperand Op6, SDOperand Op7, SDOperand Op8) { // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3); - OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6); - OpList.push_back(Op7); OpList.push_back(Op8); - SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VT, OpList))]; - if (ON) return SDOperand(ON, 0); - + MVT::ValueType *VTs = getNodeValueTypes(VT); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs); + ID.AddOperand(Op1); + ID.AddOperand(Op2); + ID.AddOperand(Op3); + ID.AddOperand(Op4); + ID.AddOperand(Op5); + ID.AddOperand(Op6); + ID.AddOperand(Op7); + ID.AddOperand(Op8); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); + RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - N->setValueTypes(VT); + N->setValueTypes(VTs, 1); N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7, Op8); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, MVT::ValueType VT1, MVT::ValueType VT2, SDOperand Op1, SDOperand Op2) { - // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); - std::vector VTList; - VTList.push_back(VT1); VTList.push_back(VT2); - SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VTList, OpList))]; - if (ON) return SDOperand(ON, 0); + MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs, Op1, Op2); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - setNodeValueTypes(N, VT1, VT2); + N->setValueTypes(VTs, 2); N->setOperands(Op1, Op2); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } @@ -2191,20 +2149,19 @@ SDOperand Op1, SDOperand Op2, SDOperand Op3) { // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3); - std::vector VTList; - VTList.push_back(VT1); VTList.push_back(VT2); - SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VTList, OpList))]; - if (ON) return SDOperand(ON, 0); + MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs, + Op1, Op2, Op3); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - setNodeValueTypes(N, VT1, VT2); + N->setValueTypes(VTs, 2); N->setOperands(Op1, Op2, Op3); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } @@ -2213,21 +2170,22 @@ SDOperand Op1, SDOperand Op2, SDOperand Op3, SDOperand Op4) { // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3); - OpList.push_back(Op4); - std::vector VTList; - VTList.push_back(VT1); VTList.push_back(VT2); - SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VTList, OpList))]; - if (ON) return SDOperand(ON, 0); - + MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs); + ID.AddOperand(Op1); + ID.AddOperand(Op2); + ID.AddOperand(Op3); + ID.AddOperand(Op4); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); + RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - setNodeValueTypes(N, VT1, VT2); + N->setValueTypes(VTs, 2); N->setOperands(Op1, Op2, Op3, Op4); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } @@ -2237,21 +2195,23 @@ SDOperand Op3, SDOperand Op4, SDOperand Op5) { // If an identical node already exists, use it. - std::vector OpList; - OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3); - OpList.push_back(Op4); OpList.push_back(Op5); - std::vector VTList; - VTList.push_back(VT1); VTList.push_back(VT2); - SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, - std::make_pair(VTList, OpList))]; - if (ON) return SDOperand(ON, 0); - + MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2); + SelectionDAGCSEMap::NodeID ID(ISD::BUILTIN_OP_END+TargetOpc, VTs); + ID.AddOperand(Op1); + ID.AddOperand(Op2); + ID.AddOperand(Op3); + ID.AddOperand(Op4); + ID.AddOperand(Op5); + void *IP = 0; + if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) + return SDOperand(ON, 0); + RemoveNodeFromCSEMaps(N); N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc); - setNodeValueTypes(N, VT1, VT2); + N->setValueTypes(VTs, 2); N->setOperands(Op1, Op2, Op3, Op4, Op5); - ON = N; // Memoize the new node. + CSEMap.InsertNode(N, IP); // Memoize the new node. return SDOperand(N, 0); } @@ -2288,7 +2248,8 @@ } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT, SDOperand Op1, SDOperand Op2, SDOperand Op3, - SDOperand Op4, SDOperand Op5, SDOperand Op6) { + SDOperand Op4, SDOperand Op5, + SDOperand Op6) { std::vector Ops; Ops.reserve(6); Ops.push_back(Op1); @@ -2344,7 +2305,8 @@ return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, - MVT::ValueType VT2, SDOperand Op1, SDOperand Op2) { + MVT::ValueType VT2, SDOperand Op1, + SDOperand Op2) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); @@ -2354,8 +2316,8 @@ return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, - MVT::ValueType VT2, SDOperand Op1, SDOperand Op2, - SDOperand Op3) { + MVT::ValueType VT2, SDOperand Op1, + SDOperand Op2, SDOperand Op3) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); @@ -2366,8 +2328,9 @@ return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, - MVT::ValueType VT2, SDOperand Op1, SDOperand Op2, - SDOperand Op3, SDOperand Op4) { + MVT::ValueType VT2, SDOperand Op1, + SDOperand Op2, SDOperand Op3, + SDOperand Op4) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); @@ -2379,8 +2342,9 @@ return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, - MVT::ValueType VT2, SDOperand Op1, SDOperand Op2, - SDOperand Op3, SDOperand Op4, SDOperand Op5) { + MVT::ValueType VT2, SDOperand Op1, + SDOperand Op2, SDOperand Op3, SDOperand Op4, + SDOperand Op5) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); @@ -2393,9 +2357,9 @@ return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, - MVT::ValueType VT2, SDOperand Op1, SDOperand Op2, - SDOperand Op3, SDOperand Op4, SDOperand Op5, - SDOperand Op6) { + MVT::ValueType VT2, SDOperand Op1, + SDOperand Op2, SDOperand Op3, SDOperand Op4, + SDOperand Op5, SDOperand Op6) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); @@ -2409,9 +2373,10 @@ return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, - MVT::ValueType VT2, SDOperand Op1, SDOperand Op2, - SDOperand Op3, SDOperand Op4, SDOperand Op5, - SDOperand Op6, SDOperand Op7) { + MVT::ValueType VT2, SDOperand Op1, + SDOperand Op2, SDOperand Op3, SDOperand Op4, + SDOperand Op5, SDOperand Op6, + SDOperand Op7) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); @@ -2440,7 +2405,8 @@ SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, MVT::ValueType VT3, SDOperand Op1, SDOperand Op2, - SDOperand Op3, SDOperand Op4, SDOperand Op5) { + SDOperand Op3, SDOperand Op4, + SDOperand Op5) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); @@ -2491,7 +2457,8 @@ return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, - MVT::ValueType VT2, std::vector &Ops) { + MVT::ValueType VT2, + std::vector &Ops) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); @@ -2744,7 +2711,6 @@ void SDNode::ANCHOR() { } - /// getValueTypeList - Return a pointer to the specified value type. /// MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) { @@ -2752,7 +2718,7 @@ VTs[VT] = VT; return &VTs[VT]; } - + /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the /// indicated value. This method ignores uses of other values defined by this /// operation. From reid at x10sys.com Mon Aug 7 18:12:32 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:12:32 -0500 Subject: [llvm-commits] CVS: llvm/projects/sample/tools/sample/Makefile Message-ID: <200608072312.k77NCWuj023034@zion.cs.uiuc.edu> Changes in directory llvm/projects/sample/tools/sample: Makefile updated: 1.6 -> 1.7 --- Log message: For PR780: http://llvm.org/PR780 : 1. Change the usage of LOADABLE_MODULE so that it implies all the things necessary to make a loadable module. This reduces the user's burdern to get a loadable module correctly built. 2. Document the usage of LOADABLE_MODULE in the MakefileGuide 3. Adjust the makefile for lib/Transforms/Hello to use the new specification for building loadable modules 4. Adjust the sample project to not attempt to build a shared library for its little library. This was just wasteful and not instructive at all. --- Diffs of the changes: (+1 -1) Makefile | 2 +- 1 files changed, 1 insertion(+), 1 deletion(-) Index: llvm/projects/sample/tools/sample/Makefile diff -u llvm/projects/sample/tools/sample/Makefile:1.6 llvm/projects/sample/tools/sample/Makefile:1.7 --- llvm/projects/sample/tools/sample/Makefile:1.6 Fri Oct 22 16:02:08 2004 +++ llvm/projects/sample/tools/sample/Makefile Mon Aug 7 18:12:15 2006 @@ -14,7 +14,7 @@ # List libraries that we'll need # We use LIBS because sample is a dynamic library. # -USEDLIBS = sample +USEDLIBS = sample.a # # Include Makefile.common so we know what to do. From reid at x10sys.com Mon Aug 7 18:12:34 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:12:34 -0500 Subject: [llvm-commits] CVS: llvm/docs/MakefileGuide.html Message-ID: <200608072312.k77NCYfA023039@zion.cs.uiuc.edu> Changes in directory llvm/docs: MakefileGuide.html updated: 1.35 -> 1.36 --- Log message: For PR780: http://llvm.org/PR780 : 1. Change the usage of LOADABLE_MODULE so that it implies all the things necessary to make a loadable module. This reduces the user's burdern to get a loadable module correctly built. 2. Document the usage of LOADABLE_MODULE in the MakefileGuide 3. Adjust the makefile for lib/Transforms/Hello to use the new specification for building loadable modules 4. Adjust the sample project to not attempt to build a shared library for its little library. This was just wasteful and not instructive at all. --- Diffs of the changes: (+38 -3) MakefileGuide.html | 41 ++++++++++++++++++++++++++++++++++++++--- 1 files changed, 38 insertions(+), 3 deletions(-) Index: llvm/docs/MakefileGuide.html diff -u llvm/docs/MakefileGuide.html:1.35 llvm/docs/MakefileGuide.html:1.36 --- llvm/docs/MakefileGuide.html:1.35 Tue Jul 11 13:25:57 2006 +++ llvm/docs/MakefileGuide.html Mon Aug 7 18:12:15 2006 @@ -30,7 +30,8 @@
  1. Libraries
      -
    1. Bytecode Modules
    2. +
    3. Bytecode Modules
    4. +
    5. Loadable Modules
  2. Tools @@ -259,7 +260,7 @@ - +

    In some situations, it is desireable to build a single bytecode module from a variety of sources, instead of an archive, shared library, or bytecode @@ -280,6 +281,40 @@

    + +
    +

    In some situations, you need to create a loadable module. Loadable modules + can be loaded into programs like opt or llc to specify + additional passes to run or targets to support. Loadable modules are also + useful for debugging a pass or providing a pass with another package if that + pass can't be included in LLVM.

    +

    LLVM provides complete support for building such a module. All you need to + do is use the LOADABLE_MODULE variable in your Makefile. For example, to + build a loadable module named MyMod that uses the LLVM libraries + LLVMSupport.a and LLVMSystem.a, you would specify:

    +
    
    +     LIBRARYNAME := MyMod
    +     LOADABLE_MODULE := 1
    +     USEDLIBS := LLVMSupport.a LLVMSystem.a
    +  
    +

    Use of the LOADABLE_MODULE facility implies several things:

    +
      +
    1. There will be no "lib" prefix on the module. This differentiates it from + a standard shared library of the same name.
    2. +
    3. The SHARED_LIBRARY variable is turned + on.
    4. +
    5. The LINK_LIBS_IN_SHARED variable + is turned on.
    6. +
    7. The DONT_BUILD_RELINKED variable + is turned on.
    8. +
    +

    A loadable module is loaded by LLVM via the facilities of libtool's libltdl + library which is part of lib/System implementation.

    +
    + +

    For building executable programs (tools), you must provide the name of the @@ -1004,7 +1039,7 @@ Reid Spencer
    The LLVM Compiler Infrastructure
    - Last modified: $Date: 2006/07/11 18:25:57 $ + Last modified: $Date: 2006/08/07 23:12:15 $ From reid at x10sys.com Mon Aug 7 18:12:36 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:12:36 -0500 Subject: [llvm-commits] CVS: llvm/Makefile.rules Message-ID: <200608072312.k77NCaou023044@zion.cs.uiuc.edu> Changes in directory llvm: Makefile.rules updated: 1.392 -> 1.393 --- Log message: For PR780: http://llvm.org/PR780 : 1. Change the usage of LOADABLE_MODULE so that it implies all the things necessary to make a loadable module. This reduces the user's burdern to get a loadable module correctly built. 2. Document the usage of LOADABLE_MODULE in the MakefileGuide 3. Adjust the makefile for lib/Transforms/Hello to use the new specification for building loadable modules 4. Adjust the sample project to not attempt to build a shared library for its little library. This was just wasteful and not instructive at all. --- Diffs of the changes: (+27 -14) Makefile.rules | 41 +++++++++++++++++++++++++++-------------- 1 files changed, 27 insertions(+), 14 deletions(-) Index: llvm/Makefile.rules diff -u llvm/Makefile.rules:1.392 llvm/Makefile.rules:1.393 --- llvm/Makefile.rules:1.392 Thu Jul 27 13:19:51 2006 +++ llvm/Makefile.rules Mon Aug 7 18:12:15 2006 @@ -323,12 +323,17 @@ # Adjust LD.Flags and Libtool.Flags depending on the kind of library that is # to be built. Note that if LOADABLE_MODULE is specified then the resulting -# shared library can be opened with dlopen +# shared library can be opened with dlopen. Also, LOADABLE_MODULE implies +# several other things so we force them to be defined/on. +ifdef LOADABLE_MODULE + SHARED_LIBRARY := 1 + DONT_BUILD_RELINKED := 1 + LINK_LIBS_IN_SHARED := 1 + LD.Flags += -module +endif + ifdef SHARED_LIBRARY LD.Flags += -rpath $(LibDir) - ifdef LOADABLE_MODULE - LD.Flags += -module - endif else LibTool.Flags += --tag=disable-shared endif @@ -425,10 +430,12 @@ BCCompile.CXX = $(LLVMGXXWITHPATH) $(CPP.Flags) $(CompileCommonOpts) \ $(CXX.Flags) Preprocess.CXX= $(CXX) $(CPP.Flags) $(CompileCommonOpts) $(CXX.Flags) -E -Link = $(LIBTOOL) $(LibTool.Flags) --mode=link $(CXX) $(CPP.Flags) \ - $(CXX.Flags) $(CompileCommonOpts) $(LD.Flags) $(Strip) -Relink = $(LIBTOOL) $(LibTool.Flags) --mode=link $(CXX) $(CPP.Flags) \ - $(CXX.Flags) $(CompileCommonOpts) $(Relink.Flags) +Link = $(CXX) $(CPP.Flags) $(CXX.Flags) $(CompileCommonOpts) \ + $(LD.Flags) $(Strip) +LTLink = $(LIBTOOL) $(LibTool.Flags) --mode=link $(Link) +Relink = $(CXX) $(CPP.Flags) $(CXX.Flags) $(CompileCommonOpts) \ + $(Relink.Flags) +LTRelink = $(LIBTOOL) $(LibTool.Flags) --mode=link $(Relink) LTInstall = $(LIBTOOL) $(LibTool.Flags) --mode=install $(INSTALL) \ $(Install.Flags) ProgInstall = $(INSTALL) $(Install.StripFlag) -m 0755 @@ -772,15 +779,21 @@ all-local:: $(LibName.LA) ifdef LINK_LIBS_IN_SHARED +ifdef LOADABLE_MODULE +SharedLibKindMessage := "Lodable Module" +else +SharedLibKindMessage := "Shared Library" +endif $(LibName.LA): $(ObjectsLO) $(LibDir)/.dir - $(Echo) Linking $(BuildMode) Shared Library $(LIBRARYNAME)$(SHLIBEXT) - $(Verb) $(Link) -o $@ $(ObjectsLO) \ - $(ProjLibsOptions) $(LLVMLibsOptions) + $(Echo) Linking $(BuildMode) $(SharedLibKindMessage) \ + $(LIBRARYNAME)$(SHLIBEXT) + $(Verb) $(LTLink) -o $@ $(ObjectsLO) $(ProjLibsOptions) \ + $(LLVMLibsOptions) $(Verb) $(LTInstall) $@ $(LibDir) else $(LibName.LA): $(ObjectsLO) $(LibDir)/.dir $(Echo) Linking $(BuildMode) Shared Library $(LIBRARYNAME)$(SHLIBEXT) - $(Verb) $(Link) -o $@ $(ObjectsLO) + $(Verb) $(LTLink) -o $@ $(ObjectsLO) $(Verb) $(LTInstall) $@ $(LibDir) endif @@ -884,7 +897,7 @@ $(LibName.O): $(ObjectsO) $(LibDir)/.dir $(Echo) Linking $(BuildMode) Object Library $(notdir $@) - $(Verb) $(Relink) -o $@ $(ObjectsO) + $(Verb) $(LTRelink) -o $@ $(ObjectsO) clean-local:: ifneq ($(strip $(LibName.O)),) @@ -983,7 +996,7 @@ $(ToolBuildPath): $(ObjectsO) $(ProjLibsPaths) $(LLVMLibsPaths) $(Echo) Linking $(BuildMode) executable $(TOOLNAME) $(StripWarnMsg) - $(Verb) $(Link) -o $@ $(TOOLLINKOPTS) $(ObjectsO) $(ProjLibsOptions) \ + $(Verb) $(LTLink) -o $@ $(TOOLLINKOPTS) $(ObjectsO) $(ProjLibsOptions) \ $(LLVMLibsOptions) $(ExtraLibs) $(TOOLLINKOPTSB) $(LIBS) $(Echo) ======= Finished Linking $(BuildMode) Executable $(TOOLNAME) \ $(StripWarnMsg) From reid at x10sys.com Mon Aug 7 18:12:36 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:12:36 -0500 Subject: [llvm-commits] CVS: llvm/lib/Transforms/Hello/Makefile Message-ID: <200608072312.k77NCa52023050@zion.cs.uiuc.edu> Changes in directory llvm/lib/Transforms/Hello: Makefile updated: 1.5 -> 1.6 --- Log message: For PR780: http://llvm.org/PR780 : 1. Change the usage of LOADABLE_MODULE so that it implies all the things necessary to make a loadable module. This reduces the user's burdern to get a loadable module correctly built. 2. Document the usage of LOADABLE_MODULE in the MakefileGuide 3. Adjust the makefile for lib/Transforms/Hello to use the new specification for building loadable modules 4. Adjust the sample project to not attempt to build a shared library for its little library. This was just wasteful and not instructive at all. --- Diffs of the changes: (+1 -1) Makefile | 2 +- 1 files changed, 1 insertion(+), 1 deletion(-) Index: llvm/lib/Transforms/Hello/Makefile diff -u llvm/lib/Transforms/Hello/Makefile:1.5 llvm/lib/Transforms/Hello/Makefile:1.6 --- llvm/lib/Transforms/Hello/Makefile:1.5 Mon Jan 10 22:33:32 2005 +++ llvm/lib/Transforms/Hello/Makefile Mon Aug 7 18:12:15 2006 @@ -9,8 +9,8 @@ LEVEL = ../../.. LIBRARYNAME = LLVMHello -SHARED_LIBRARY = 1 LOADABLE_MODULE = 1 +USEDLIBS = LLVMSupport.a LLVMSystem.a include $(LEVEL)/Makefile.common From reid at x10sys.com Mon Aug 7 18:12:36 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:12:36 -0500 Subject: [llvm-commits] CVS: llvm/projects/sample/lib/sample/Makefile Message-ID: <200608072312.k77NCasF023081@zion.cs.uiuc.edu> Changes in directory llvm/projects/sample/lib/sample: Makefile updated: 1.7 -> 1.8 --- Log message: For PR780: http://llvm.org/PR780 : 1. Change the usage of LOADABLE_MODULE so that it implies all the things necessary to make a loadable module. This reduces the user's burdern to get a loadable module correctly built. 2. Document the usage of LOADABLE_MODULE in the MakefileGuide 3. Adjust the makefile for lib/Transforms/Hello to use the new specification for building loadable modules 4. Adjust the sample project to not attempt to build a shared library for its little library. This was just wasteful and not instructive at all. --- Diffs of the changes: (+2 -4) Makefile | 6 ++---- 1 files changed, 2 insertions(+), 4 deletions(-) Index: llvm/projects/sample/lib/sample/Makefile diff -u llvm/projects/sample/lib/sample/Makefile:1.7 llvm/projects/sample/lib/sample/Makefile:1.8 --- llvm/projects/sample/lib/sample/Makefile:1.7 Wed May 31 20:55:21 2006 +++ llvm/projects/sample/lib/sample/Makefile Mon Aug 7 18:12:15 2006 @@ -9,10 +9,8 @@ # Give the name of a library. This will build a dynamic version. # LIBRARYNAME=sample -SHARED_LIBRARY=1 -LOADABLE_MODULE=1 -#DONT_BUILD_RELINKED=1 -#ARCHIVE_LIBRARY=1 +DONT_BUILD_RELINKED=1 +BUILD_ARCHIVE=1 # # Include Makefile.common so we know what to do. From reid at x10sys.com Mon Aug 7 18:17:39 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:17:39 -0500 Subject: [llvm-commits] CVS: llvm/lib/Transforms/Hello/Hello.cpp Message-ID: <200608072317.k77NHd7L025505@zion.cs.uiuc.edu> Changes in directory llvm/lib/Transforms/Hello: Hello.cpp updated: 1.6 -> 1.7 --- Log message: Make this example pass use some things from lib/Support (EscapeString, SlowOperatingInfo, Statistics). Besides providing an example of how to use these facilities, it also serves to debug problems with runtime linking when dlopening a loadable module. These three support facilities exercise different combinations of Text/Weak Weak/Text and Text/Text linking between the executable and the module. --- Diffs of the changes: (+15 -2) Hello.cpp | 17 +++++++++++++++-- 1 files changed, 15 insertions(+), 2 deletions(-) Index: llvm/lib/Transforms/Hello/Hello.cpp diff -u llvm/lib/Transforms/Hello/Hello.cpp:1.6 llvm/lib/Transforms/Hello/Hello.cpp:1.7 --- llvm/lib/Transforms/Hello/Hello.cpp:1.6 Thu Apr 21 18:45:56 2005 +++ llvm/lib/Transforms/Hello/Hello.cpp Mon Aug 7 18:17:24 2006 @@ -14,14 +14,23 @@ #include "llvm/Pass.h" #include "llvm/Function.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/Support/SlowOperationInformer.h" +#include "llvm/ADT/Statistic.h" #include using namespace llvm; namespace { + Statistic HelloCounter("hellocount", + "Counts number of functions greeted"); // Hello - The first implementation, without getAnalysisUsage. struct Hello : public FunctionPass { virtual bool runOnFunction(Function &F) { - std::cerr << "Hello: " << F.getName() << "\n"; + SlowOperationInformer soi("EscapeString"); + HelloCounter++; + std::string fname = F.getName(); + EscapeString(fname); + std::cerr << "Hello: " << fname << "\n"; return false; } }; @@ -30,7 +39,11 @@ // Hello2 - The second implementation with getAnalysisUsage implemented. struct Hello2 : public FunctionPass { virtual bool runOnFunction(Function &F) { - std::cerr << "Hello: " << F.getName() << "\n"; + SlowOperationInformer soi("EscapeString"); + HelloCounter++; + std::string fname = F.getName(); + EscapeString(fname); + std::cerr << "Hello: " << fname << "\n"; return false; } From reid at x10sys.com Mon Aug 7 18:20:32 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:20:32 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/Support/SlowOperationInformer.h Message-ID: <200608072320.k77NKWaB027360@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/Support: SlowOperationInformer.h updated: 1.9 -> 1.10 --- Log message: Remove the use of "IncludeFile" from this support facility. The mechanism to build a loadable module is now correctly defined and documented so this workaround isn't needed any longer. --- Diffs of the changes: (+0 -3) SlowOperationInformer.h | 3 --- 1 files changed, 3 deletions(-) Index: llvm/include/llvm/Support/SlowOperationInformer.h diff -u llvm/include/llvm/Support/SlowOperationInformer.h:1.9 llvm/include/llvm/Support/SlowOperationInformer.h:1.10 --- llvm/include/llvm/Support/SlowOperationInformer.h:1.9 Wed Jul 26 11:18:00 2006 +++ llvm/include/llvm/Support/SlowOperationInformer.h Mon Aug 7 18:20:15 2006 @@ -32,7 +32,6 @@ #include #include #include "llvm/Support/DataTypes.h" -#include "llvm/System/IncludeFile.h" namespace llvm { class SlowOperationInformer { @@ -64,5 +63,3 @@ } // end namespace llvm #endif /* SLOW_OPERATION_INFORMER_H */ - -FORCE_DEFINING_FILE_TO_BE_LINKED(SupportSlowOperationInformer) From reid at x10sys.com Mon Aug 7 18:20:32 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:20:32 -0500 Subject: [llvm-commits] CVS: llvm/lib/Support/SlowOperationInformer.cpp Message-ID: <200608072320.k77NKW5n027358@zion.cs.uiuc.edu> Changes in directory llvm/lib/Support: SlowOperationInformer.cpp updated: 1.9 -> 1.10 --- Log message: Remove the use of "IncludeFile" from this support facility. The mechanism to build a loadable module is now correctly defined and documented so this workaround isn't needed any longer. --- Diffs of the changes: (+0 -3) SlowOperationInformer.cpp | 3 --- 1 files changed, 3 deletions(-) Index: llvm/lib/Support/SlowOperationInformer.cpp diff -u llvm/lib/Support/SlowOperationInformer.cpp:1.9 llvm/lib/Support/SlowOperationInformer.cpp:1.10 --- llvm/lib/Support/SlowOperationInformer.cpp:1.9 Wed Jul 26 11:18:00 2006 +++ llvm/lib/Support/SlowOperationInformer.cpp Mon Aug 7 18:20:15 2006 @@ -12,7 +12,6 @@ //===----------------------------------------------------------------------===// #include "llvm/Support/SlowOperationInformer.h" -#include "llvm/System/IncludeFile.h" #include "llvm/System/Alarm.h" #include #include @@ -65,5 +64,3 @@ std::cout << ToPrint+OS.str() << std::flush; return false; } - -DEFINING_FILE_FOR(SupportSlowOperationInformer) From reid at x10sys.com Mon Aug 7 18:23:55 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:23:55 -0500 Subject: [llvm-commits] CVS: llvm/Makefile.config.in Message-ID: <200608072323.k77NNtMd027786@zion.cs.uiuc.edu> Changes in directory llvm: Makefile.config.in updated: 1.63 -> 1.64 --- Log message: Make the name of the project consistent with that specified in the configure.ac file. This fixes some case-consistency issues between the name of the tarball created by "make dist" and the tarball used for source when building the LLVM RPM package. --- Diffs of the changes: (+2 -2) Makefile.config.in | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-) Index: llvm/Makefile.config.in diff -u llvm/Makefile.config.in:1.63 llvm/Makefile.config.in:1.64 --- llvm/Makefile.config.in:1.63 Fri Aug 4 13:18:07 2006 +++ llvm/Makefile.config.in Mon Aug 7 18:23:39 2006 @@ -36,13 +36,13 @@ PWD := @BINPWD@ # Set the project name to LLVM if its not defined ifndef PROJECT_NAME -PROJECT_NAME := LLVM +PROJECT_NAME := $(LLVMPackageName) endif PROJ_OBJ_DIR := $(shell $(PWD)) PROJ_OBJ_ROOT := $(shell cd $(PROJ_OBJ_DIR)/$(LEVEL); $(PWD)) -ifeq ($(PROJECT_NAME),LLVM) +ifeq ($(PROJECT_NAME),llvm) LLVM_SRC_ROOT := $(shell cd @abs_top_srcdir@; $(PWD)) LLVM_OBJ_ROOT := $(shell cd @abs_top_builddir@; $(PWD)) PROJ_SRC_ROOT := $(shell cd $(LLVM_SRC_ROOT); $(PWD)) From lattner at cs.uiuc.edu Mon Aug 7 18:31:38 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 18:31:38 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/CodeGen/SelectionDAGCSEMap.h Message-ID: <200608072331.k77NVcca030895@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/CodeGen: SelectionDAGCSEMap.h added (r1.1) --- Log message: New CSEMap datastructure impl --- Diffs of the changes: (+114 -0) SelectionDAGCSEMap.h | 114 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 114 insertions(+) Index: llvm/include/llvm/CodeGen/SelectionDAGCSEMap.h diff -c /dev/null llvm/include/llvm/CodeGen/SelectionDAGCSEMap.h:1.1 *** /dev/null Mon Aug 7 18:31:34 2006 --- llvm/include/llvm/CodeGen/SelectionDAGCSEMap.h Mon Aug 7 18:31:24 2006 *************** *** 0 **** --- 1,114 ---- + //===-- llvm/CodeGen/SelectionDAGCSEMap.h - CSE Map for SD ------*- C++ -*-===// + // + // The LLVM Compiler Infrastructure + // + // This file was developed by Chris Lattner and is distributed under + // the University of Illinois Open Source License. See LICENSE.TXT for details. + // + //===----------------------------------------------------------------------===// + // + // This file declares the SelectionDAG class, and transitively defines the + // SDNode class and subclasses. + // + //===----------------------------------------------------------------------===// + + #ifndef LLVM_CODEGEN_SELECTIONDAGCSEMAP_H + #define LLVM_CODEGEN_SELECTIONDAGCSEMAP_H + + #include "llvm/ADT/SmallVector.h" + + namespace llvm { + class SDNode; + class SDOperand; + + /// SelectionDAGCSEMap - This class is used for two purposes: + /// 1. Given information (e.g. opcode and operand info) about a node we want + /// to create, look up the unique instance of the node in the map. If + /// the node already exists, return it, otherwise return the bucket it + /// should be inserted into. + /// 2. Given a node that has already been created, remove it from the CSE + /// map. + /// + /// This class is implemented as a chained hash table, where the "buckets" are + /// actually the SDNodes themselves (the next pointer is in the SDNode). + /// + class SelectionDAGCSEMap { + void **Buckets; + unsigned NumBuckets; // Always a power of 2. + public: + class NodeID; + SelectionDAGCSEMap(); + ~SelectionDAGCSEMap(); + + /// RemoveNode - Remove a node from the CSE map, returning true if one was + /// removed or false if the node was not in the CSE map. + bool RemoveNode(SDNode *N); + + /// GetOrInsertSimpleNode - If there is an existing simple SDNode exactly + /// equal to the specified node, return it. Otherwise, insert 'N' and it + /// instead. This only works on *simple* SDNodes, not ConstantSDNode or any + /// other classes derived from SDNode. + SDNode *GetOrInsertNode(SDNode *N); + + /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists, + /// return it. If not, return the insertion token that will make insertion + /// faster. + SDNode *FindNodeOrInsertPos(const NodeID &ID, void *&InsertPos); + + /// InsertNode - Insert the specified node into the CSE Map, knowing that it + /// is not already in the map. InsertPos must be obtained from + /// FindNodeOrInsertPos. + void InsertNode(SDNode *N, void *InsertPos); + + class NodeID { + /// Use a SmallVector to avoid a heap allocation in the common case. + /// + SmallVector Bits; + public: + NodeID() {} + NodeID(SDNode *N); + NodeID(unsigned short ID, const void *VTList); + NodeID(unsigned short ID, const void *VTList, SDOperand Op); + NodeID(unsigned short ID, const void *VTList, + SDOperand Op1, SDOperand Op2); + NodeID(unsigned short ID, const void *VTList, + SDOperand Op1, SDOperand Op2, SDOperand Op3); + NodeID(unsigned short ID, const void *VTList, + const SDOperand *OpList, unsigned N); + + void SetOpcode(unsigned short ID) { + Bits.push_back(ID & 0xFF); + Bits.push_back(ID >> 8); + } + + /// getOpcode - If the opcode has been set for this NodeID, return it. + unsigned getOpcode() const { + return Bits[0] + (Bits[1] << 8); + } + + void SetValueTypes(const void *VTList) { AddPointer(VTList); } + void SetOperands() {} + void SetOperands(SDOperand Op) { AddOperand(Op); } + void SetOperands(SDOperand Op1, SDOperand Op2) { + AddOperand(Op1); AddOperand(Op2); + } + void SetOperands(SDOperand Op1, SDOperand Op2, SDOperand Op3) { + AddOperand(Op1); AddOperand(Op2); AddOperand(Op3); + } + void SetOperands(const SDOperand *Ops, unsigned NumOps); + void AddOperand(SDOperand Op); + void AddPointer(const void *Ptr); + + unsigned ComputeHash() const; + + bool operator==(const NodeID &RHS) const; + }; + + private: + SDNode *GetNextPtr(void *NextInBucketPtr); + void **GetBucketPtr(void *NextInBucketPtr); + void **GetBucketFor(const NodeID &ID) const; + }; + } // end namespace llvm + + #endif From lattner at cs.uiuc.edu Mon Aug 7 18:42:15 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 18:42:15 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/ADT/SmallVector.h Message-ID: <200608072342.k77NgFI3032118@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/ADT: SmallVector.h updated: 1.5 -> 1.6 --- Log message: Remove assertions from the SmallVector class. They slow down clients of smallvector too much in a release build. Removing them speeds up isel 4%. --- Diffs of the changes: (+0 -6) SmallVector.h | 6 ------ 1 files changed, 6 deletions(-) Index: llvm/include/llvm/ADT/SmallVector.h diff -u llvm/include/llvm/ADT/SmallVector.h:1.5 llvm/include/llvm/ADT/SmallVector.h:1.6 --- llvm/include/llvm/ADT/SmallVector.h:1.5 Mon Aug 7 00:45:34 2006 +++ llvm/include/llvm/ADT/SmallVector.h Mon Aug 7 18:41:59 2006 @@ -15,7 +15,6 @@ #define LLVM_ADT_SMALLVECTOR_H #include -#include #include #include @@ -91,20 +90,16 @@ const_iterator end() const { return End; } reference operator[](unsigned idx) { - assert(idx < size() && "out of range reference!"); return Begin[idx]; } const_reference operator[](unsigned idx) const { - assert(idx < size() && "out of range reference!"); return Begin[idx]; } reference back() { - assert(!empty() && "SmallVector is empty!"); return end()[-1]; } const_reference back() const { - assert(!empty() && "SmallVector is empty!"); return end()[-1]; } @@ -120,7 +115,6 @@ } void pop_back() { - assert(!empty() && "SmallVector is empty!"); --End; End->~T(); } From reid at x10sys.com Mon Aug 7 18:45:16 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 18:45:16 -0500 Subject: [llvm-commits] CVS: llvm/docs/MakefileGuide.html Message-ID: <200608072345.k77NjGg2032730@zion.cs.uiuc.edu> Changes in directory llvm/docs: MakefileGuide.html updated: 1.36 -> 1.37 --- Log message: Fix an anchor name. --- Diffs of the changes: (+2 -2) MakefileGuide.html | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-) Index: llvm/docs/MakefileGuide.html diff -u llvm/docs/MakefileGuide.html:1.36 llvm/docs/MakefileGuide.html:1.37 --- llvm/docs/MakefileGuide.html:1.36 Mon Aug 7 18:12:15 2006 +++ llvm/docs/MakefileGuide.html Mon Aug 7 18:44:59 2006 @@ -282,7 +282,7 @@

    In some situations, you need to create a loadable module. Loadable modules @@ -1039,7 +1039,7 @@ Reid Spencer
    The LLVM Compiler Infrastructure
    - Last modified: $Date: 2006/08/07 23:12:15 $ + Last modified: $Date: 2006/08/07 23:44:59 $ From evan.cheng at apple.com Mon Aug 7 18:59:04 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 18:59:04 -0500 Subject: [llvm-commits] CVS: llvm/test/Regression/CodeGen/X86/2006-08-07-CycleInDAG.ll Message-ID: <200608072359.k77Nx4qb002522@zion.cs.uiuc.edu> Changes in directory llvm/test/Regression/CodeGen/X86: 2006-08-07-CycleInDAG.ll added (r1.1) --- Log message: New test case. --- Diffs of the changes: (+30 -0) 2006-08-07-CycleInDAG.ll | 30 ++++++++++++++++++++++++++++++ 1 files changed, 30 insertions(+) Index: llvm/test/Regression/CodeGen/X86/2006-08-07-CycleInDAG.ll diff -c /dev/null llvm/test/Regression/CodeGen/X86/2006-08-07-CycleInDAG.ll:1.1 *** /dev/null Mon Aug 7 18:58:58 2006 --- llvm/test/Regression/CodeGen/X86/2006-08-07-CycleInDAG.ll Mon Aug 7 18:58:47 2006 *************** *** 0 **** --- 1,30 ---- + ; RUN: llvm-as < %s | llc -march=x86 -mattr=+sse2 + + fastcc int %test(%struct.foo* %v, %struct.foo* %vi) { + br bool false, label %ilog2.exit, label %cond_true.i + + cond_true.i: ; preds = %entry + ret int 0 + + ilog2.exit: ; preds = %entry + %tmp24.i = load int* null ; [#uses=1] + %tmp13.i12.i = tail call double %ldexp( double 0.000000e+00, int 0 ) ; [#uses=1] + %tmp13.i13.i = cast double %tmp13.i12.i to float ; [#uses=1] + %tmp11.i = load int* null ; [#uses=1] + %tmp11.i = cast int %tmp11.i to uint ; [#uses=1] + %n.i = cast int %tmp24.i to uint ; [#uses=1] + %tmp13.i7 = mul uint %tmp11.i, %n.i ; [#uses=1] + %tmp.i8 = tail call sbyte* %calloc( uint %tmp13.i7, uint 4 ) ; [#uses=0] + br bool false, label %bb224.preheader.i, label %bb.i + + bb.i: ; preds = %ilog2.exit + ret int 0 + + bb224.preheader.i: ; preds = %ilog2.exit + %tmp165.i = cast float %tmp13.i13.i to double ; [#uses=0] + ret int 0 + } + + declare sbyte* %calloc(uint, uint) + + declare double %ldexp(double, int) From evan.cheng at apple.com Mon Aug 7 19:31:15 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Mon, 7 Aug 2006 19:31:15 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/X86/X86ISelDAGToDAG.cpp Message-ID: <200608080031.k780VFPi027055@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/X86: X86ISelDAGToDAG.cpp updated: 1.89 -> 1.90 --- Log message: Eliminate reachability matrix. It has to be calculated before any instruction selection is done. That's rather expensive especially in situations where it isn't really needed. Move back to a searching the predecessors, but make use of topological order to trim the search space. --- Diffs of the changes: (+34 -57) X86ISelDAGToDAG.cpp | 91 +++++++++++++++++++--------------------------------- 1 files changed, 34 insertions(+), 57 deletions(-) Index: llvm/lib/Target/X86/X86ISelDAGToDAG.cpp diff -u llvm/lib/Target/X86/X86ISelDAGToDAG.cpp:1.89 llvm/lib/Target/X86/X86ISelDAGToDAG.cpp:1.90 --- llvm/lib/Target/X86/X86ISelDAGToDAG.cpp:1.89 Mon Aug 7 17:28:20 2006 +++ llvm/lib/Target/X86/X86ISelDAGToDAG.cpp Mon Aug 7 19:31:00 2006 @@ -99,8 +99,7 @@ X86DAGToDAGISel(X86TargetMachine &TM) : SelectionDAGISel(X86Lowering), X86Lowering(*TM.getTargetLowering()), - Subtarget(&TM.getSubtarget()), - ReachabilityMatrix(NULL) {} + Subtarget(&TM.getSubtarget()) {} virtual bool runOnFunction(Function &Fn) { // Make sure we re-emit a set of the global base reg if necessary @@ -124,8 +123,6 @@ #include "X86GenDAGISel.inc" private: - void DetermineReachability(); - void Select(SDOperand &Result, SDOperand N); bool MatchAddress(SDOperand N, X86ISelAddressMode &AM, bool isRoot = true); @@ -142,10 +139,6 @@ unsigned NumBytes = (DAGSize + 7) / 8; UnfoldableSet = new unsigned char[NumBytes]; memset(UnfoldableSet, 0, NumBytes); - unsigned RMSize = (DAGSize * DAGSize + 7) / 8; - ReachabilityMatrix = new unsigned char[RMSize]; - memset(ReachabilityMatrix, 0, RMSize); - DetermineReachability(); } /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for @@ -192,20 +185,6 @@ /// base register. Return the virtual register that holds this value. SDOperand getGlobalBaseReg(); - /// ReachabilityMatrix - A N x N matrix representing all pairs reachability - /// information. One bit per potential edge. - unsigned char *ReachabilityMatrix; - - inline void setReachable(SDNode *f, SDNode *t) { - unsigned Idx = f->getNodeId() * DAGSize + t->getNodeId(); - ReachabilityMatrix[Idx / 8] |= 1 << (Idx % 8); - } - - inline bool isReachable(SDNode *f, SDNode *t) { - unsigned Idx = f->getNodeId() * DAGSize + t->getNodeId(); - return ReachabilityMatrix[Idx / 8] & (1 << (Idx % 8)); - } - /// UnfoldableSet - An boolean array representing nodes which have been /// folded into addressing modes and therefore should not be folded in /// another operation. @@ -227,6 +206,38 @@ }; } +static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, + std::set &Visited) { + if (found || + Use->getNodeId() > Def->getNodeId() || + !Visited.insert(Use).second) + return; + + for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) { + SDNode *N = Use->getOperand(i).Val; + if (N != Def) { + findNonImmUse(N, Def, found, Visited); + } else { + found = true; + break; + } + } +} + +static inline bool isNonImmUse(SDNode* Use, SDNode* Def) { + std::set Visited; + bool found = false; + for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) { + SDNode *N = Use->getOperand(i).Val; + if (N != Def) { + findNonImmUse(N, Def, found, Visited); + if (found) break; + } + } + return found; +} + + bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U) { // Is it already folded by SelectAddr / SelectLEAAddr? if (isUnfoldable(N)) @@ -244,38 +255,7 @@ // / [X] // | ^ // [U]--------| - assert(isReachable(U, N) && "Attempting to fold a non-operand node?"); - for (SDNode::op_iterator I = U->op_begin(), E = U->op_end(); I != E; ++I) { - SDNode *P = I->Val; - if (P != N && isReachable(P, N)) - return false; - } - return true; -} - -/// DetermineReachability - Determine reachability between all pairs of nodes -/// between f and t in topological order. -void X86DAGToDAGISel::DetermineReachability() { - for (unsigned i = 0; i < DAGSize; ++i) { - SDNode *N = TopOrder[i]; - setReachable(N, N); - // If N is a leaf node, there is nothing more to do. - if (N->getNumOperands() == 0) - continue; - - for (unsigned i2 = 0; ; ++i2) { - SDNode *M = TopOrder[i2]; - if (isReachable(M, N)) { - // Update reachability from M to N's operands. - for (SDNode::op_iterator I = N->op_begin(),E = N->op_end(); I != E;++I){ - SDNode *P = I->Val; - if (P->getNodeId() >= 0) - setReachable(M, P); - } - } - if (M == N) break; - } - } + return !isNonImmUse(U, N); } /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel @@ -294,9 +274,6 @@ DEBUG(std::cerr << "===== Instruction selection ends:\n"); #endif - delete[] ReachabilityMatrix; - delete[] UnfoldableSet; - ReachabilityMatrix = NULL; UnfoldableSet = NULL; DAG.RemoveDeadNodes(); From lattner at cs.uiuc.edu Mon Aug 7 19:38:06 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 19:38:06 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/ADT/SmallVector.h Message-ID: <200608080038.k780c6qx027566@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/ADT: SmallVector.h updated: 1.6 -> 1.7 --- Log message: Add ctor that initializes from a range. --- Diffs of the changes: (+6 -0) SmallVector.h | 6 ++++++ 1 files changed, 6 insertions(+) Index: llvm/include/llvm/ADT/SmallVector.h diff -u llvm/include/llvm/ADT/SmallVector.h:1.6 llvm/include/llvm/ADT/SmallVector.h:1.7 --- llvm/include/llvm/ADT/SmallVector.h:1.6 Mon Aug 7 18:41:59 2006 +++ llvm/include/llvm/ADT/SmallVector.h Mon Aug 7 19:37:50 2006 @@ -51,6 +51,12 @@ SmallVector() : Begin((T*)InlineElts), End(Begin), Capacity(Begin+N) { } + template + SmallVector(ItTy S, ItTy E) + : Begin((T*)InlineElts), End(Begin), Capacity(Begin+N) { + append(S, E); + } + SmallVector(const SmallVector &RHS) { unsigned RHSSize = RHS.size(); Begin = (T*)InlineElts; From lattner at cs.uiuc.edu Mon Aug 7 20:09:46 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 20:09:46 -0500 Subject: [llvm-commits] CVS: llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp SelectionDAG.cpp Message-ID: <200608080109.k7819kjX005345@zion.cs.uiuc.edu> Changes in directory llvm/lib/CodeGen/SelectionDAG: LegalizeDAG.cpp updated: 1.384 -> 1.385 SelectionDAG.cpp updated: 1.319 -> 1.320 --- Log message: Eliminate some malloc traffic by allocating vectors on the stack. Change some method that took std::vector to take a pointer to a first operand and #operands. This speeds up isel on kc++ by about 3%. --- Diffs of the changes: (+67 -82) LegalizeDAG.cpp | 44 ++++++++++++----------- SelectionDAG.cpp | 105 +++++++++++++++++++++++-------------------------------- 2 files changed, 67 insertions(+), 82 deletions(-) Index: llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp diff -u llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:1.384 llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:1.385 --- llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:1.384 Fri Aug 4 12:45:20 2006 +++ llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp Mon Aug 7 20:09:31 2006 @@ -22,6 +22,7 @@ #include "llvm/Support/MathExtras.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Visibility.h" +#include "llvm/ADT/SmallVector.h" #include #include using namespace llvm; @@ -541,11 +542,11 @@ if (Node->getOpcode() >= ISD::BUILTIN_OP_END) { // If this is a target node, legalize it by legalizing the operands then // passing it through. - std::vector Ops; + SmallVector Ops; for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) Ops.push_back(LegalizeOp(Node->getOperand(i))); - Result = DAG.UpdateNodeOperands(Result.getValue(0), Ops); + Result = DAG.UpdateNodeOperands(Result.getValue(0), &Ops[0], Ops.size()); for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) AddLegalizedOperand(Op.getValue(i), Result.getValue(i)); @@ -621,10 +622,10 @@ case ISD::INTRINSIC_W_CHAIN: case ISD::INTRINSIC_WO_CHAIN: case ISD::INTRINSIC_VOID: { - std::vector Ops; + SmallVector Ops; for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) Ops.push_back(LegalizeOp(Node->getOperand(i))); - Result = DAG.UpdateNodeOperands(Result, Ops); + Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size()); // Allow the target to custom lower its intrinsics if it wants to. if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) == @@ -690,7 +691,7 @@ case TargetLowering::Legal: if (Tmp1 != Node->getOperand(0) || getTypeAction(Node->getOperand(1).getValueType()) == Promote) { - std::vector Ops; + SmallVector Ops; Ops.push_back(Tmp1); if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) { Ops.push_back(Node->getOperand(1)); // line # must be legal. @@ -702,7 +703,7 @@ } Ops.push_back(Node->getOperand(3)); // filename must be legal. Ops.push_back(Node->getOperand(4)); // working dir # must be legal. - Result = DAG.UpdateNodeOperands(Result, Ops); + Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size()); } break; } @@ -815,11 +816,11 @@ Tmp3 = LegalizeOp(Node->getOperand(2)); Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3); } else { - std::vector Ops; + SmallVector Ops; // Legalize the operands. for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) Ops.push_back(LegalizeOp(Node->getOperand(i))); - Result = DAG.UpdateNodeOperands(Result, Ops); + Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size()); } break; @@ -1074,9 +1075,9 @@ // Do not try to legalize the target-specific arguments (#1+). if (Tmp1 != Node->getOperand(0)) { - std::vector Ops(Node->op_begin(), Node->op_end()); + SmallVector Ops(Node->op_begin(), Node->op_end()); Ops[0] = Tmp1; - Result = DAG.UpdateNodeOperands(Result, Ops); + Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size()); } // Remember that the CALLSEQ_START is legalized. @@ -1117,18 +1118,18 @@ // an optional flag input. if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){ if (Tmp1 != Node->getOperand(0)) { - std::vector Ops(Node->op_begin(), Node->op_end()); + SmallVector Ops(Node->op_begin(), Node->op_end()); Ops[0] = Tmp1; - Result = DAG.UpdateNodeOperands(Result, Ops); + Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size()); } } else { Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1)); if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(Node->getNumOperands()-1)) { - std::vector Ops(Node->op_begin(), Node->op_end()); + SmallVector Ops(Node->op_begin(), Node->op_end()); Ops[0] = Tmp1; Ops.back() = Tmp2; - Result = DAG.UpdateNodeOperands(Result, Ops); + Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size()); } } assert(IsLegalizingCall && "Call sequence imbalance between start/end?"); @@ -1181,7 +1182,7 @@ return Op.ResNo ? Tmp2 : Tmp1; } case ISD::INLINEASM: { - std::vector Ops(Node->op_begin(), Node->op_end()); + SmallVector Ops(Node->op_begin(), Node->op_end()); bool Changed = false; // Legalize all of the operands of the inline asm, in case they are nodes // that need to be expanded or something. Note we skip the asm string and @@ -1209,7 +1210,7 @@ } if (Changed) - Result = DAG.UpdateNodeOperands(Result, Ops); + Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size()); // INLINE asm returns a chain and flag, make sure to add both to the map. AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0)); @@ -1545,7 +1546,7 @@ Result = DAG.UpdateNodeOperands(Result, Tmp1); break; default: { // ret - std::vector NewValues; + SmallVector NewValues; NewValues.push_back(Tmp1); for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2) switch (getTypeAction(Node->getOperand(i).getValueType())) { @@ -1569,9 +1570,10 @@ } if (NewValues.size() == Node->getNumOperands()) - Result = DAG.UpdateNodeOperands(Result, NewValues); + Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size()); else - Result = DAG.getNode(ISD::RET, MVT::Other, NewValues); + Result = DAG.getNode(ISD::RET, MVT::Other, + &NewValues[0], NewValues.size()); break; } } @@ -2069,14 +2071,14 @@ case ISD::SHL_PARTS: case ISD::SRA_PARTS: case ISD::SRL_PARTS: { - std::vector Ops; + SmallVector Ops; bool Changed = false; for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) { Ops.push_back(LegalizeOp(Node->getOperand(i))); Changed |= Ops.back() != Node->getOperand(i); } if (Changed) - Result = DAG.UpdateNodeOperands(Result, Ops); + Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size()); switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) { Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp diff -u llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.319 llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.320 --- llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.319 Mon Aug 7 18:03:03 2006 +++ llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp Mon Aug 7 20:09:31 2006 @@ -526,7 +526,7 @@ /// return null, otherwise return a pointer to the slot it would take. If a /// node already exists with these operands, the slot will be non-null. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, - const std::vector &Ops, + const SDOperand *Ops,unsigned NumOps, void *&InsertPos) { if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag) return 0; // Never add these nodes. @@ -539,7 +539,7 @@ SelectionDAGCSEMap::NodeID ID; ID.SetOpcode(N->getOpcode()); ID.SetValueTypes(N->value_begin()); - ID.SetOperands(&Ops[0], Ops.size()); + ID.SetOperands(Ops, NumOps); return CSEMap.FindNodeOrInsertPos(ID, InsertPos); } @@ -1498,26 +1498,15 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT, SDOperand N1, SDOperand N2, SDOperand N3, SDOperand N4) { - std::vector Ops; - Ops.reserve(4); - Ops.push_back(N1); - Ops.push_back(N2); - Ops.push_back(N3); - Ops.push_back(N4); - return getNode(Opcode, VT, Ops); + SDOperand Ops[] = { N1, N2, N3, N4 }; + return getNode(Opcode, VT, Ops, 4); } SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT, SDOperand N1, SDOperand N2, SDOperand N3, SDOperand N4, SDOperand N5) { - std::vector Ops; - Ops.reserve(5); - Ops.push_back(N1); - Ops.push_back(N2); - Ops.push_back(N3); - Ops.push_back(N4); - Ops.push_back(N5); - return getNode(Opcode, VT, Ops); + SDOperand Ops[] = { N1, N2, N3, N4, N5 }; + return getNode(Opcode, VT, Ops, 5); } SDOperand SelectionDAG::getLoad(MVT::ValueType VT, @@ -1539,17 +1528,12 @@ SDOperand SelectionDAG::getVecLoad(unsigned Count, MVT::ValueType EVT, SDOperand Chain, SDOperand Ptr, SDOperand SV) { - std::vector Ops; - Ops.reserve(5); - Ops.push_back(Chain); - Ops.push_back(Ptr); - Ops.push_back(SV); - Ops.push_back(getConstant(Count, MVT::i32)); - Ops.push_back(getValueType(EVT)); + SDOperand Ops[] = { Chain, Ptr, SV, getConstant(Count, MVT::i32), + getValueType(EVT) }; std::vector VTs; VTs.reserve(2); VTs.push_back(MVT::Vector); VTs.push_back(MVT::Other); // Add token chain. - return getNode(ISD::VLOAD, VTs, Ops); + return getNode(ISD::VLOAD, VTs, Ops, 5); } SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT, @@ -1593,8 +1577,8 @@ } SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT, - std::vector &Ops) { - switch (Ops.size()) { + const SDOperand *Ops, unsigned NumOps) { + switch (NumOps) { case 0: return getNode(Opcode, VT); case 1: return getNode(Opcode, VT, Ops[0]); case 2: return getNode(Opcode, VT, Ops[0], Ops[1]); @@ -1605,7 +1589,7 @@ switch (Opcode) { default: break; case ISD::TRUNCSTORE: { - assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!"); + assert(NumOps == 5 && "TRUNCSTORE takes 5 operands!"); MVT::ValueType EVT = cast(Ops[4])->getVT(); #if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store // If this is a truncating store of a constant, convert to the desired type @@ -1625,7 +1609,7 @@ break; } case ISD::SELECT_CC: { - assert(Ops.size() == 5 && "SELECT_CC takes 5 operands!"); + assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); assert(Ops[0].getValueType() == Ops[1].getValueType() && "LHS and RHS of condition must have same type!"); assert(Ops[2].getValueType() == Ops[3].getValueType() && @@ -1635,7 +1619,7 @@ break; } case ISD::BR_CC: { - assert(Ops.size() == 5 && "BR_CC takes 5 operands!"); + assert(NumOps == 5 && "BR_CC takes 5 operands!"); assert(Ops[2].getValueType() == Ops[3].getValueType() && "LHS/RHS of comparison should match types!"); break; @@ -1646,15 +1630,15 @@ SDNode *N; MVT::ValueType *VTs = getNodeValueTypes(VT); if (VT != MVT::Flag) { - SelectionDAGCSEMap::NodeID ID(Opcode, VTs, &Ops[0], Ops.size()); + SelectionDAGCSEMap::NodeID ID(Opcode, VTs, Ops, NumOps); void *IP = 0; if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) return SDOperand(E, 0); - N = new SDNode(Opcode, Ops); + N = new SDNode(Opcode, Ops, NumOps); N->setValueTypes(VTs, 1); CSEMap.InsertNode(N, IP); } else { - N = new SDNode(Opcode, Ops); + N = new SDNode(Opcode, Ops, NumOps); N->setValueTypes(VTs, 1); } AllNodes.push_back(N); @@ -1663,16 +1647,16 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, std::vector &ResultTys, - std::vector &Ops) { + const SDOperand *Ops, unsigned NumOps) { if (ResultTys.size() == 1) - return getNode(Opcode, ResultTys[0], Ops); + return getNode(Opcode, ResultTys[0], Ops, NumOps); switch (Opcode) { case ISD::EXTLOAD: case ISD::SEXTLOAD: case ISD::ZEXTLOAD: { MVT::ValueType EVT = cast(Ops[3])->getVT(); - assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!"); + assert(NumOps == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!"); // If they are asking for an extending load from/to the same thing, return a // normal load. if (ResultTys[0] == EVT) @@ -1720,21 +1704,33 @@ SelectionDAGCSEMap::NodeID ID; ID.SetOpcode(Opcode); ID.SetValueTypes(VTs); - ID.SetOperands(&Ops[0], Ops.size()); + ID.SetOperands(&Ops[0], NumOps); void *IP = 0; if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) return SDOperand(E, 0); - N = new SDNode(Opcode, Ops); + N = new SDNode(Opcode, Ops, NumOps); N->setValueTypes(VTs, ResultTys.size()); CSEMap.InsertNode(N, IP); } else { - N = new SDNode(Opcode, Ops); + N = new SDNode(Opcode, Ops, NumOps); N->setValueTypes(VTs, ResultTys.size()); } AllNodes.push_back(N); return SDOperand(N, 0); } +SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT, + std::vector &Ops) { + return getNode(Opcode, VT, &Ops[0], Ops.size()); +} + +SDOperand SelectionDAG::getNode(unsigned Opcode, + std::vector &ResultTys, + std::vector &Ops) { + return getNode(Opcode, ResultTys, &Ops[0], Ops.size()); +} + + MVT::ValueType *SelectionDAG::getNodeValueTypes(MVT::ValueType VT) { return SDNode::getValueTypeList(VT); } @@ -1843,45 +1839,32 @@ SDOperand SelectionDAG:: UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) { - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - return UpdateNodeOperands(N, Ops); + SDOperand Ops[] = { Op1, Op2, Op3 }; + return UpdateNodeOperands(N, Ops, 3); } SDOperand SelectionDAG:: UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3, SDOperand Op4) { - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - return UpdateNodeOperands(N, Ops); + SDOperand Ops[] = { Op1, Op2, Op3, Op4 }; + return UpdateNodeOperands(N, Ops, 4); } SDOperand SelectionDAG:: UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3, SDOperand Op4, SDOperand Op5) { - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - return UpdateNodeOperands(N, Ops); + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 }; + return UpdateNodeOperands(N, Ops, 5); } SDOperand SelectionDAG:: -UpdateNodeOperands(SDOperand InN, const std::vector &Ops) { +UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) { SDNode *N = InN.Val; - assert(N->getNumOperands() == Ops.size() && + assert(N->getNumOperands() == NumOps && "Update with wrong number of operands"); // Check to see if there is no change. - unsigned NumOps = Ops.size(); bool AnyChange = false; for (unsigned i = 0; i != NumOps; ++i) { if (Ops[i] != N->getOperand(i)) { @@ -1895,7 +1878,7 @@ // See if the modified node already exists. void *InsertPos = 0; - if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) + if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos)) return SDOperand(Existing, InN.ResNo); // Nope it doesn't. Remove the node from it's current place in the maps. From lattner at cs.uiuc.edu Mon Aug 7 20:09:47 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 20:09:47 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/CodeGen/SelectionDAG.h SelectionDAGNodes.h Message-ID: <200608080109.k7819lBS005352@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/CodeGen: SelectionDAG.h updated: 1.109 -> 1.110 SelectionDAGNodes.h updated: 1.138 -> 1.139 --- Log message: Eliminate some malloc traffic by allocating vectors on the stack. Change some method that took std::vector to take a pointer to a first operand and #operands. This speeds up isel on kc++ by about 3%. --- Diffs of the changes: (+18 -19) SelectionDAG.h | 29 ++++++++++++++--------------- SelectionDAGNodes.h | 8 ++++---- 2 files changed, 18 insertions(+), 19 deletions(-) Index: llvm/include/llvm/CodeGen/SelectionDAG.h diff -u llvm/include/llvm/CodeGen/SelectionDAG.h:1.109 llvm/include/llvm/CodeGen/SelectionDAG.h:1.110 --- llvm/include/llvm/CodeGen/SelectionDAG.h:1.109 Mon Aug 7 18:03:03 2006 +++ llvm/include/llvm/CodeGen/SelectionDAG.h Mon Aug 7 20:09:31 2006 @@ -171,10 +171,8 @@ std::vector ResultTys; ResultTys.push_back(VT); ResultTys.push_back(MVT::Other); - std::vector Ops; - Ops.push_back(Chain); - Ops.push_back(getRegister(Reg, VT)); - return getNode(ISD::CopyFromReg, ResultTys, Ops); + SDOperand Ops[] = { Chain, getRegister(Reg, VT) }; + return getNode(ISD::CopyFromReg, ResultTys, Ops, 2); } // This version of the getCopyFromReg method takes an extra operand, which @@ -186,11 +184,8 @@ ResultTys.push_back(VT); ResultTys.push_back(MVT::Other); ResultTys.push_back(MVT::Flag); - std::vector Ops; - Ops.push_back(Chain); - Ops.push_back(getRegister(Reg, VT)); - if (Flag.Val) Ops.push_back(Flag); - return getNode(ISD::CopyFromReg, ResultTys, Ops); + SDOperand Ops[] = { Chain, getRegister(Reg, VT), Flag }; + return getNode(ISD::CopyFromReg, ResultTys, Ops, Flag.Val ? 3 : 2); } SDOperand getCondCode(ISD::CondCode Cond); @@ -205,10 +200,8 @@ std::vector ResultTys; ResultTys.push_back(MVT::Other); ResultTys.push_back(MVT::Flag); - std::vector Ops; - Ops.push_back(Chain); - Ops.push_back(Op); - return getNode(ISD::CALLSEQ_START, ResultTys, Ops); + SDOperand Ops[] = { Chain, Op }; + return getNode(ISD::CALLSEQ_START, ResultTys, Ops, 2); } /// getNode - Gets or creates the specified node. @@ -229,6 +222,12 @@ SDOperand getNode(unsigned Opcode, std::vector &ResultTys, std::vector &Ops); + SDOperand getNode(unsigned Opcode, MVT::ValueType VT, + const SDOperand *Ops, unsigned NumOps); + SDOperand getNode(unsigned Opcode, std::vector &ResultTys, + const SDOperand *Ops, unsigned NumOps); + + /// getSetCC - Helper function to make it easier to build SetCC's if you just /// have an ISD::CondCode instead of an SDOperand. /// @@ -278,7 +277,7 @@ SDOperand Op3, SDOperand Op4); SDOperand UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3, SDOperand Op4, SDOperand Op5); - SDOperand UpdateNodeOperands(SDOperand N, const std::vector &Op); + SDOperand UpdateNodeOperands(SDOperand N, SDOperand *Ops, unsigned NumOps); /// SelectNodeTo - These are used for target selectors to *mutate* the /// specified node to have the specified return type, Target opcode, and @@ -445,7 +444,7 @@ SDNode *FindModifiedNodeSlot(SDNode *N, SDOperand Op, void *&InsertPos); SDNode *FindModifiedNodeSlot(SDNode *N, SDOperand Op1, SDOperand Op2, void *&InsertPos); - SDNode *FindModifiedNodeSlot(SDNode *N, const std::vector &Ops, + SDNode *FindModifiedNodeSlot(SDNode *N, const SDOperand *Ops, unsigned NumOps, void *&InsertPos); void DeleteNodeNotInCSEMaps(SDNode *N); Index: llvm/include/llvm/CodeGen/SelectionDAGNodes.h diff -u llvm/include/llvm/CodeGen/SelectionDAGNodes.h:1.138 llvm/include/llvm/CodeGen/SelectionDAGNodes.h:1.139 --- llvm/include/llvm/CodeGen/SelectionDAGNodes.h:1.138 Mon Aug 7 18:03:03 2006 +++ llvm/include/llvm/CodeGen/SelectionDAGNodes.h Mon Aug 7 20:09:31 2006 @@ -865,13 +865,13 @@ Prev = 0; Next = 0; NextInBucket = 0; } - SDNode(unsigned Opc, const std::vector &Nodes) + SDNode(unsigned Opc, const SDOperand *Ops, unsigned NumOps) : NodeType(Opc), NodeId(-1) { - NumOperands = Nodes.size(); + NumOperands = NumOps; OperandList = new SDOperand[NumOperands]; - for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { - OperandList[i] = Nodes[i]; + for (unsigned i = 0, e = NumOps; i != e; ++i) { + OperandList[i] = Ops[i]; SDNode *N = OperandList[i].Val; N->Uses.push_back(this); } From lattner at cs.uiuc.edu Mon Aug 7 20:44:36 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 20:44:36 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/ADT/SmallVector.h Message-ID: <200608080144.k781iajf013530@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/ADT: SmallVector.h updated: 1.7 -> 1.8 --- Log message: add a new assign method --- Diffs of the changes: (+9 -0) SmallVector.h | 9 +++++++++ 1 files changed, 9 insertions(+) Index: llvm/include/llvm/ADT/SmallVector.h diff -u llvm/include/llvm/ADT/SmallVector.h:1.7 llvm/include/llvm/ADT/SmallVector.h:1.8 --- llvm/include/llvm/ADT/SmallVector.h:1.7 Mon Aug 7 19:37:50 2006 +++ llvm/include/llvm/ADT/SmallVector.h Mon Aug 7 20:44:16 2006 @@ -146,6 +146,15 @@ End += NumInputs; } + void assign(unsigned NumElts, const T &Elt) { + clear(); + if (NumElts > Capacity) + grow(NumElts); + End = Begin+NumElts; + for (; NumElts; --NumElts) + new (Begin+NumElts-1) T(Elt); + } + const SmallVector &operator=(const SmallVector &RHS) { // Avoid self-assignment. if (this == &RHS) return *this; From reid at x10sys.com Mon Aug 7 20:48:32 2006 From: reid at x10sys.com (Reid Spencer) Date: Mon, 7 Aug 2006 20:48:32 -0500 Subject: [llvm-commits] CVS: llvm/docs/WritingAnLLVMPass.html Message-ID: <200608080148.k781mWIJ015733@zion.cs.uiuc.edu> Changes in directory llvm/docs: WritingAnLLVMPass.html updated: 1.45 -> 1.46 --- Log message: Update the instructions for writing a pass as a loadable module per the new definition in MakefileGuilde.html and Makefile.rules. --- Diffs of the changes: (+6 -4) WritingAnLLVMPass.html | 10 ++++++---- 1 files changed, 6 insertions(+), 4 deletions(-) Index: llvm/docs/WritingAnLLVMPass.html diff -u llvm/docs/WritingAnLLVMPass.html:1.45 llvm/docs/WritingAnLLVMPass.html:1.46 --- llvm/docs/WritingAnLLVMPass.html:1.45 Fri Aug 4 13:10:12 2006 +++ llvm/docs/WritingAnLLVMPass.html Mon Aug 7 20:48:17 2006 @@ -178,13 +178,15 @@ # Name of the library to build LIBRARYNAME = Hello -# Build a dynamically linkable shared object -SHARED_LIBRARY = 1 - # Make the shared library become a loadable module so the tools can # dlopen/dlsym on the resulting library. LOADABLE_MODULE = 1 +# Tell the build system which LLVM libraries your pass needs. You'll probably +# need at least LLVMSystem.a, LLVMSupport.a, LLVMCore.a but possibly several +# others too. +LLVMLIBS = LLVMCore.a LLVMSupport.a LLVMSystem.a + # Include the makefile implementation stuff include $(LEVEL)/Makefile.common

    @@ -1732,7 +1734,7 @@ Chris Lattner
    The LLVM Compiler Infrastructure
    - Last modified: $Date: 2006/08/04 18:10:12 $ + Last modified: $Date: 2006/08/08 01:48:17 $ From lattner at cs.uiuc.edu Mon Aug 7 20:54:32 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 20:54:32 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/ADT/SmallVector.h Message-ID: <200608080154.k781sWwU021740@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/ADT: SmallVector.h updated: 1.8 -> 1.9 --- Log message: capacity is a pointer, not a value --- Diffs of the changes: (+1 -1) SmallVector.h | 2 +- 1 files changed, 1 insertion(+), 1 deletion(-) Index: llvm/include/llvm/ADT/SmallVector.h diff -u llvm/include/llvm/ADT/SmallVector.h:1.8 llvm/include/llvm/ADT/SmallVector.h:1.9 --- llvm/include/llvm/ADT/SmallVector.h:1.8 Mon Aug 7 20:44:16 2006 +++ llvm/include/llvm/ADT/SmallVector.h Mon Aug 7 20:54:17 2006 @@ -148,7 +148,7 @@ void assign(unsigned NumElts, const T &Elt) { clear(); - if (NumElts > Capacity) + if (Begin+NumElts > Capacity) grow(NumElts); End = Begin+NumElts; for (; NumElts; --NumElts) From pjenkins at apple.com Mon Aug 7 21:04:12 2006 From: pjenkins at apple.com (Patrick Jenkins) Date: Mon, 7 Aug 2006 21:04:12 -0500 Subject: [llvm-commits] CVS: llvm/utils/NewNightlyTest.pl Message-ID: <200608080204.k7824CaO026898@zion.cs.uiuc.edu> Changes in directory llvm/utils: NewNightlyTest.pl updated: 1.45 -> 1.46 --- Log message: Removed unneccesary output from nightly tester --- Diffs of the changes: (+3 -3) NewNightlyTest.pl | 6 +++--- 1 files changed, 3 insertions(+), 3 deletions(-) Index: llvm/utils/NewNightlyTest.pl diff -u llvm/utils/NewNightlyTest.pl:1.45 llvm/utils/NewNightlyTest.pl:1.46 --- llvm/utils/NewNightlyTest.pl:1.45 Sun Aug 6 20:54:37 2006 +++ llvm/utils/NewNightlyTest.pl Mon Aug 7 21:03:53 2006 @@ -842,11 +842,11 @@ } ($SingleSourceProgramsTable, $llcbeta_options) = TestDirectory("SingleSource"); WriteFile "$Prefix-singlesourceprogramstable.txt", $SingleSourceProgramsTable; + if ( $VERBOSE ) { + print "MultiSource TEST STAGE\n"; + } ($MultiSourceProgramsTable, $llcbeta_options) = TestDirectory("MultiSource"); WriteFile "$Prefix-multisourceprogramstable.txt", $MultiSourceProgramsTable; - if ( $VERBOSE ) { - print "MultiSource returned $MultiSourceProgramsTable\n"; - } if ( ! $NOEXTERNALS ) { if ( $VERBOSE ) { print "External TEST STAGE\n"; From lattner at cs.uiuc.edu Mon Aug 7 21:24:04 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 21:24:04 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp Message-ID: <200608080224.k782O4Rk030187@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/PowerPC: PPCISelDAGToDAG.cpp updated: 1.200 -> 1.201 --- Log message: Start eliminating temporary vectors used to create DAG nodes. Instead, pass in the start of an array and a count of operands where applicable. In many cases, the number of operands is known, so this static array can be allocated on the stack, avoiding the heap. In many other cases, a SmallVector can be used, which has the same benefit in the common cases. I updated a lot of code calling getNode that takes a vector, but ran out of time. The rest of the code should be updated, and these methods should be removed. We should also do the same thing to eliminate the methods that take a vector of MVT::ValueTypes. It would be extra nice to convert the dagiselemitter to avoid creating vectors for operands when calling getTargetNode. --- Diffs of the changes: (+11 -7) PPCISelDAGToDAG.cpp | 18 +++++++++++------- 1 files changed, 11 insertions(+), 7 deletions(-) Index: llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp diff -u llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp:1.200 llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp:1.201 --- llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp:1.200 Mon Aug 7 17:23:56 2006 +++ llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp Mon Aug 7 21:23:41 2006 @@ -1152,7 +1152,7 @@ bool hasFlag = N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag; - std::vector Ops; + SmallVector Ops; // Push varargs arguments, including optional flag. for (unsigned i = 1, e = N.getNumOperands()-hasFlag; i != e; ++i) { AddToQueue(Chain, N.getOperand(i)); @@ -1167,7 +1167,8 @@ Ops.push_back(Chain); } - ResNode = CurDAG->getTargetNode(PPC::BCTRL, MVT::Other, MVT::Flag, Ops); + ResNode = CurDAG->getTargetNode(PPC::BCTRL, MVT::Other, MVT::Flag, + &Ops[0], Ops.size()); Chain = SDOperand(ResNode, 0); InFlag = SDOperand(ResNode, 1); ReplaceUses(SDOperand(N.Val, 0), Chain); @@ -1193,7 +1194,7 @@ if (N1.getOpcode() == ISD::Constant) { unsigned Tmp0C = (unsigned)cast(N1)->getValue(); - std::vector Ops; + SmallVector Ops; Ops.push_back(CurDAG->getTargetConstant(Tmp0C, MVT::i32)); bool hasFlag = @@ -1210,7 +1211,8 @@ AddToQueue(Chain, N.getOperand(N.getNumOperands()-1)); Ops.push_back(Chain); } - ResNode = CurDAG->getTargetNode(PPC::BLA, MVT::Other, MVT::Flag, Ops); + ResNode = CurDAG->getTargetNode(PPC::BLA, MVT::Other, MVT::Flag, + &Ops[0], Ops.size()); Chain = SDOperand(ResNode, 0); InFlag = SDOperand(ResNode, 1); @@ -1224,7 +1226,7 @@ // Emits: (BL:void (tglobaladdr:i32):$dst) // Pattern complexity = 4 cost = 1 if (N1.getOpcode() == ISD::TargetGlobalAddress) { - std::vector Ops; + SmallVector Ops; Ops.push_back(N1); bool hasFlag = @@ -1242,7 +1244,8 @@ Ops.push_back(Chain); } - ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag, Ops); + ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag, + &Ops[0], Ops.size()); Chain = SDOperand(ResNode, 0); InFlag = SDOperand(ResNode, 1); @@ -1274,7 +1277,8 @@ Ops.push_back(Chain); } - ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag, Ops); + ResNode = CurDAG->getTargetNode(PPC::BL, MVT::Other, MVT::Flag, + &Ops[0], Ops.size()); Chain = SDOperand(ResNode, 0); InFlag = SDOperand(ResNode, 1); From lattner at cs.uiuc.edu Mon Aug 7 21:24:04 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 21:24:04 -0500 Subject: [llvm-commits] CVS: llvm/utils/TableGen/DAGISelEmitter.cpp Message-ID: <200608080224.k782O4sh030197@zion.cs.uiuc.edu> Changes in directory llvm/utils/TableGen: DAGISelEmitter.cpp updated: 1.237 -> 1.238 --- Log message: Start eliminating temporary vectors used to create DAG nodes. Instead, pass in the start of an array and a count of operands where applicable. In many cases, the number of operands is known, so this static array can be allocated on the stack, avoiding the heap. In many other cases, a SmallVector can be used, which has the same benefit in the common cases. I updated a lot of code calling getNode that takes a vector, but ran out of time. The rest of the code should be updated, and these methods should be removed. We should also do the same thing to eliminate the methods that take a vector of MVT::ValueTypes. It would be extra nice to convert the dagiselemitter to avoid creating vectors for operands when calling getTargetNode. --- Diffs of the changes: (+3 -2) DAGISelEmitter.cpp | 5 +++-- 1 files changed, 3 insertions(+), 2 deletions(-) Index: llvm/utils/TableGen/DAGISelEmitter.cpp diff -u llvm/utils/TableGen/DAGISelEmitter.cpp:1.237 llvm/utils/TableGen/DAGISelEmitter.cpp:1.238 --- llvm/utils/TableGen/DAGISelEmitter.cpp:1.237 Mon Aug 7 17:17:58 2006 +++ llvm/utils/TableGen/DAGISelEmitter.cpp Mon Aug 7 21:23:42 2006 @@ -2683,7 +2683,7 @@ } if (HasVarOps) - Code += ", Ops"; + Code += ", &Ops[0], Ops.size()"; else if (NodeHasOptInFlag) Code = "HasInFlag ? " + Code + ", InFlag) : " + Code; @@ -3420,7 +3420,8 @@ << " std::vector VTs;\n" << " VTs.push_back(MVT::Other);\n" << " VTs.push_back(MVT::Flag);\n" - << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n" + << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], " + "Ops.size());\n" << " ReplaceUses(SDOperand(N.Val, 0), New);\n" << " ReplaceUses(SDOperand(N.Val, 1), SDOperand(New.Val, 1));\n" << " Result = New.getValue(N.ResNo);\n" From lattner at cs.uiuc.edu Mon Aug 7 21:24:05 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 21:24:05 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp Message-ID: <200608080224.k782O5bS030207@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/Sparc: SparcISelDAGToDAG.cpp updated: 1.101 -> 1.102 --- Log message: Start eliminating temporary vectors used to create DAG nodes. Instead, pass in the start of an array and a count of operands where applicable. In many cases, the number of operands is known, so this static array can be allocated on the stack, avoiding the heap. In many other cases, a SmallVector can be used, which has the same benefit in the common cases. I updated a lot of code calling getNode that takes a vector, but ran out of time. The rest of the code should be updated, and these methods should be removed. We should also do the same thing to eliminate the methods that take a vector of MVT::ValueTypes. It would be extra nice to convert the dagiselemitter to avoid creating vectors for operands when calling getTargetNode. --- Diffs of the changes: (+14 -24) SparcISelDAGToDAG.cpp | 38 ++++++++++++++------------------------ 1 files changed, 14 insertions(+), 24 deletions(-) Index: llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp diff -u llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp:1.101 llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp:1.102 --- llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp:1.101 Mon Aug 7 17:24:18 2006 +++ llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp Mon Aug 7 21:23:41 2006 @@ -444,7 +444,8 @@ } if (!OutChains.empty()) - DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains)); + DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, + &OutChains[0], OutChains.size())); // Finally, inform the code generator which regs we return values in. switch (getValueType(F.getReturnType())) { @@ -596,7 +597,7 @@ // Emit all stores, make sure the occur before any copies into physregs. if (!Stores.empty()) - Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores); + Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Stores[0],Stores.size()); static const unsigned ArgRegs[] = { SP::O0, SP::O1, SP::O2, SP::O3, SP::O4, SP::O5 @@ -621,12 +622,8 @@ std::vector NodeTys; NodeTys.push_back(MVT::Other); // Returns a chain NodeTys.push_back(MVT::Flag); // Returns a flag for retval copy to use. - std::vector Ops; - Ops.push_back(Chain); - Ops.push_back(Callee); - if (InFlag.Val) - Ops.push_back(InFlag); - Chain = DAG.getNode(SPISD::CALL, NodeTys, Ops); + SDOperand Ops[] = { Chain, Callee, InFlag }; + Chain = DAG.getNode(SPISD::CALL, NodeTys, Ops, InFlag.Val ? 3 : 2); InFlag = Chain.getValue(1); MVT::ValueType RetTyVT = getValueType(RetTy); @@ -743,10 +740,8 @@ std::vector VTs; VTs.push_back(MVT::i32); VTs.push_back(MVT::Flag); - std::vector Ops; - Ops.push_back(LHS); - Ops.push_back(RHS); - CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops).getValue(1); + SDOperand Ops[2] = { LHS, RHS }; + CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops, 2).getValue(1); if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC); Opc = SPISD::BRICC; } else { @@ -774,10 +769,8 @@ std::vector VTs; VTs.push_back(LHS.getValueType()); // subcc returns a value VTs.push_back(MVT::Flag); - std::vector Ops; - Ops.push_back(LHS); - Ops.push_back(RHS); - CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops).getValue(1); + SDOperand Ops[2] = { LHS, RHS }; + CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops, 2).getValue(1); Opc = SPISD::SELECT_ICC; if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC); } else { @@ -821,11 +814,10 @@ std::vector Tys; Tys.push_back(MVT::f64); Tys.push_back(MVT::Other); - std::vector Ops; // Bit-Convert the value to f64. - Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, MVT::f64, V)); - Ops.push_back(V.getValue(1)); - return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops); + SDOperand Ops[2] = { DAG.getNode(ISD::BIT_CONVERT, MVT::f64, V), + V.getValue(1) }; + return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2); } } case ISD::DYNAMIC_STACKALLOC: { @@ -844,10 +836,8 @@ std::vector Tys; Tys.push_back(MVT::i32); Tys.push_back(MVT::Other); - std::vector Ops; - Ops.push_back(NewVal); - Ops.push_back(Chain); - return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops); + SDOperand Ops[2] = { NewVal, Chain }; + return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2); } case ISD::RET: { SDOperand Copy; From lattner at cs.uiuc.edu Mon Aug 7 21:24:05 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 21:24:05 -0500 Subject: [llvm-commits] CVS: llvm/include/llvm/CodeGen/SelectionDAG.h Message-ID: <200608080224.k782O50r030202@zion.cs.uiuc.edu> Changes in directory llvm/include/llvm/CodeGen: SelectionDAG.h updated: 1.110 -> 1.111 --- Log message: Start eliminating temporary vectors used to create DAG nodes. Instead, pass in the start of an array and a count of operands where applicable. In many cases, the number of operands is known, so this static array can be allocated on the stack, avoiding the heap. In many other cases, a SmallVector can be used, which has the same benefit in the common cases. I updated a lot of code calling getNode that takes a vector, but ran out of time. The rest of the code should be updated, and these methods should be removed. We should also do the same thing to eliminate the methods that take a vector of MVT::ValueTypes. It would be extra nice to convert the dagiselemitter to avoid creating vectors for operands when calling getTargetNode. --- Diffs of the changes: (+15 -19) SelectionDAG.h | 34 +++++++++++++++------------------- 1 files changed, 15 insertions(+), 19 deletions(-) Index: llvm/include/llvm/CodeGen/SelectionDAG.h diff -u llvm/include/llvm/CodeGen/SelectionDAG.h:1.110 llvm/include/llvm/CodeGen/SelectionDAG.h:1.111 --- llvm/include/llvm/CodeGen/SelectionDAG.h:1.110 Mon Aug 7 20:09:31 2006 +++ llvm/include/llvm/CodeGen/SelectionDAG.h Mon Aug 7 21:23:41 2006 @@ -145,12 +145,8 @@ std::vector VTs; VTs.push_back(MVT::Other); VTs.push_back(MVT::Flag); - std::vector Ops; - Ops.push_back(Chain); - Ops.push_back(getRegister(Reg, N.getValueType())); - Ops.push_back(N); - if (Flag.Val) Ops.push_back(Flag); - return getNode(ISD::CopyToReg, VTs, Ops); + SDOperand Ops[] = { Chain, getRegister(Reg, N.getValueType()), N, Flag }; + return getNode(ISD::CopyToReg, VTs, Ops, Flag.Val ? 4 : 3); } // Similar to last getCopyToReg() except parameter Reg is a SDOperand @@ -159,12 +155,8 @@ std::vector VTs; VTs.push_back(MVT::Other); VTs.push_back(MVT::Flag); - std::vector Ops; - Ops.push_back(Chain); - Ops.push_back(Reg); - Ops.push_back(N); - if (Flag.Val) Ops.push_back(Flag); - return getNode(ISD::CopyToReg, VTs, Ops); + SDOperand Ops[] = { Chain, Reg, N, Flag }; + return getNode(ISD::CopyToReg, VTs, Ops, Flag.Val ? 4 : 3); } SDOperand getCopyFromReg(SDOperand Chain, unsigned Reg, MVT::ValueType VT) { @@ -218,14 +210,17 @@ SDOperand N1, SDOperand N2, SDOperand N3, SDOperand N4, SDOperand N5); SDOperand getNode(unsigned Opcode, MVT::ValueType VT, - std::vector &Children); - SDOperand getNode(unsigned Opcode, std::vector &ResultTys, - std::vector &Ops); - - SDOperand getNode(unsigned Opcode, MVT::ValueType VT, const SDOperand *Ops, unsigned NumOps); + SDOperand getNode(unsigned Opcode, MVT::ValueType VT, + const std::vector &Ops) { + return getNode(Opcode, VT, &Ops[0], Ops.size()); + } SDOperand getNode(unsigned Opcode, std::vector &ResultTys, const SDOperand *Ops, unsigned NumOps); + SDOperand getNode(unsigned Opcode, std::vector &ResultTys, + const std::vector &Ops) { + return getNode(Opcode, ResultTys, &Ops[0], Ops.size()); + } /// getSetCC - Helper function to make it easier to build SetCC's if you just @@ -351,7 +346,7 @@ SDOperand Op4, SDOperand Op5, SDOperand Op6, SDOperand Op7, SDOperand Op8); SDNode *getTargetNode(unsigned Opcode, MVT::ValueType VT, - std::vector &Ops); + const SDOperand *Ops, unsigned NumOps); SDNode *getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, SDOperand Op1); SDNode *getTargetNode(unsigned Opcode, MVT::ValueType VT1, @@ -391,7 +386,8 @@ SDOperand Op3, SDOperand Op4, SDOperand Op5, SDOperand Op6, SDOperand Op7); SDNode *getTargetNode(unsigned Opcode, MVT::ValueType VT1, - MVT::ValueType VT2, std::vector &Ops); + MVT::ValueType VT2, + const SDOperand *Ops, unsigned NumOps); /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. /// This can cause recursive merging of nodes in the DAG. Use the first From lattner at cs.uiuc.edu Mon Aug 7 21:24:05 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 21:24:05 -0500 Subject: [llvm-commits] CVS: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp LegalizeDAG.cpp SelectionDAG.cpp SelectionDAGISel.cpp Message-ID: <200608080224.k782O5WO030218@zion.cs.uiuc.edu> Changes in directory llvm/lib/CodeGen/SelectionDAG: DAGCombiner.cpp updated: 1.179 -> 1.180 LegalizeDAG.cpp updated: 1.385 -> 1.386 SelectionDAG.cpp updated: 1.320 -> 1.321 SelectionDAGISel.cpp updated: 1.267 -> 1.268 --- Log message: Start eliminating temporary vectors used to create DAG nodes. Instead, pass in the start of an array and a count of operands where applicable. In many cases, the number of operands is known, so this static array can be allocated on the stack, avoiding the heap. In many other cases, a SmallVector can be used, which has the same benefit in the common cases. I updated a lot of code calling getNode that takes a vector, but ran out of time. The rest of the code should be updated, and these methods should be removed. We should also do the same thing to eliminate the methods that take a vector of MVT::ValueTypes. It would be extra nice to convert the dagiselemitter to avoid creating vectors for operands when calling getTargetNode. --- Diffs of the changes: (+177 -275) DAGCombiner.cpp | 76 +++++++++++++---------- LegalizeDAG.cpp | 87 ++++++++++++++------------- SelectionDAG.cpp | 163 ++++++++++----------------------------------------- SelectionDAGISel.cpp | 126 ++++++++++++++++----------------------- 4 files changed, 177 insertions(+), 275 deletions(-) Index: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp diff -u llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1.179 llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1.180 --- llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1.179 Tue Jul 25 15:44:41 2006 +++ llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp Mon Aug 7 21:23:41 2006 @@ -510,7 +510,7 @@ } SDOperand DAGCombiner::visitTokenFactor(SDNode *N) { - std::vector Ops; + SmallVector Ops; bool Changed = false; // If the token factor has two operands and one is the entry token, replace @@ -539,7 +539,7 @@ } } if (Changed) - return DAG.getNode(ISD::TokenFactor, MVT::Other, Ops); + return DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size()); return SDOperand(); } @@ -1284,7 +1284,7 @@ // Produce a vector of zeros. SDOperand El = DAG.getConstant(0, MVT::getVectorBaseType(VT)); std::vector Ops(MVT::getVectorNumElements(VT), El); - return DAG.getNode(ISD::BUILD_VECTOR, VT, Ops); + return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()); } } @@ -1953,14 +1953,14 @@ // If this is a conversion of N elements of one type to N elements of another // type, convert each element. This handles FP<->INT cases. if (SrcBitSize == DstBitSize) { - std::vector Ops; + SmallVector Ops; for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) { Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i))); AddToWorkList(Ops.back().Val); } Ops.push_back(*(BV->op_end()-2)); // Add num elements. Ops.push_back(DAG.getValueType(DstEltVT)); - return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops); + return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size()); } // Otherwise, we're growing or shrinking the elements. To avoid having to @@ -1992,7 +1992,7 @@ if (SrcBitSize < DstBitSize) { unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; - std::vector Ops; + SmallVector Ops; for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; i += NumInputsPerOutput) { bool isLE = TLI.isLittleEndian(); @@ -2016,13 +2016,13 @@ Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements. Ops.push_back(DAG.getValueType(DstEltVT)); // Add element size. - return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops); + return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size()); } // Finally, this must be the case where we are shrinking elements: each input // turns into multiple outputs. unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; - std::vector Ops; + SmallVector Ops; for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) { if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { for (unsigned j = 0; j != NumOutputsPerInput; ++j) @@ -2043,7 +2043,7 @@ } Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements. Ops.push_back(DAG.getValueType(DstEltVT)); // Add element size. - return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops); + return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size()); } @@ -2448,10 +2448,11 @@ // vector with the inserted element. if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa(EltNo)) { unsigned Elt = cast(EltNo)->getValue(); - std::vector Ops(InVec.Val->op_begin(), InVec.Val->op_end()); + SmallVector Ops(InVec.Val->op_begin(), InVec.Val->op_end()); if (Elt < Ops.size()) Ops[Elt] = InVal; - return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(), Ops); + return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(), + &Ops[0], Ops.size()); } return SDOperand(); @@ -2468,10 +2469,11 @@ // vector with the inserted element. if (InVec.getOpcode() == ISD::VBUILD_VECTOR && isa(EltNo)) { unsigned Elt = cast(EltNo)->getValue(); - std::vector Ops(InVec.Val->op_begin(), InVec.Val->op_end()); + SmallVector Ops(InVec.Val->op_begin(), InVec.Val->op_end()); if (Elt < Ops.size()-2) Ops[Elt] = InVal; - return DAG.getNode(ISD::VBUILD_VECTOR, InVec.getValueType(), Ops); + return DAG.getNode(ISD::VBUILD_VECTOR, InVec.getValueType(), + &Ops[0], Ops.size()); } return SDOperand(); @@ -2524,7 +2526,7 @@ // If everything is good, we can make a shuffle operation. if (VecIn1.Val) { - std::vector BuildVecIndices; + SmallVector BuildVecIndices; for (unsigned i = 0; i != NumInScalars; ++i) { if (N->getOperand(i).getOpcode() == ISD::UNDEF) { BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, MVT::i32)); @@ -2549,10 +2551,10 @@ BuildVecIndices.push_back(DAG.getValueType(MVT::i32)); // Return the new VVECTOR_SHUFFLE node. - std::vector Ops; - Ops.push_back(VecIn1); + SDOperand Ops[5]; + Ops[0] = VecIn1; if (VecIn2.Val) { - Ops.push_back(VecIn2); + Ops[1] = VecIn2; } else { // Use an undef vbuild_vector as input for the second operand. std::vector UnOps(NumInScalars, @@ -2560,13 +2562,15 @@ cast(EltType)->getVT())); UnOps.push_back(NumElts); UnOps.push_back(EltType); - Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, UnOps)); - AddToWorkList(Ops.back().Val); - } - Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector, BuildVecIndices)); - Ops.push_back(NumElts); - Ops.push_back(EltType); - return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, Ops); + Ops[1] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, + &UnOps[0], UnOps.size()); + AddToWorkList(Ops[1].Val); + } + Ops[2] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, + &BuildVecIndices[0], BuildVecIndices.size()); + Ops[3] = NumElts; + Ops[4] = EltType; + return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, Ops, 5); } return SDOperand(); @@ -2668,7 +2672,7 @@ return DAG.getNode(ISD::UNDEF, N->getValueType(0)); // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the // first operand. - std::vector MappedOps; + SmallVector MappedOps; for (unsigned i = 0, e = ShufMask.getNumOperands(); i != e; ++i) { if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF || cast(ShufMask.getOperand(i))->getValue() < NumElts) { @@ -2680,7 +2684,7 @@ } } ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(), - MappedOps); + &MappedOps[0], MappedOps.size()); AddToWorkList(ShufMask.Val); return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0), N0, @@ -2785,7 +2789,7 @@ if (isUnary || N0 == N1) { // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the // first operand. - std::vector MappedOps; + SmallVector MappedOps; for (unsigned i = 0; i != NumElts; ++i) { if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF || cast(ShufMask.getOperand(i))->getValue() < NumElts) { @@ -2801,7 +2805,7 @@ MappedOps.push_back(ShufMask.getOperand(NumElts+1)); ShufMask = DAG.getNode(ISD::VBUILD_VECTOR, ShufMask.getValueType(), - MappedOps); + &MappedOps[0], MappedOps.size()); AddToWorkList(ShufMask.Val); // Build the undef vector. @@ -2810,7 +2814,8 @@ MappedOps[i] = UDVal; MappedOps[NumElts ] = *(N0.Val->op_end()-2); MappedOps[NumElts+1] = *(N0.Val->op_end()-1); - UDVal = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, MappedOps); + UDVal = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, + &MappedOps[0], MappedOps.size()); return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, N0, UDVal, ShufMask, @@ -2863,13 +2868,16 @@ std::vector ZeroOps(NumElts, DAG.getConstant(0, EVT)); ZeroOps.push_back(NumEltsNode); ZeroOps.push_back(EVTNode); - Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, ZeroOps)); + Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, + &ZeroOps[0], ZeroOps.size())); IdxOps.push_back(NumEltsNode); IdxOps.push_back(EVTNode); - Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, IdxOps)); + Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, + &IdxOps[0], IdxOps.size())); Ops.push_back(NumEltsNode); Ops.push_back(EVTNode); - SDOperand Result = DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, Ops); + SDOperand Result = DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, + &Ops[0], Ops.size()); if (NumEltsNode != DstVecSize || EVTNode != DstVecEVT) { Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result, DstVecSize, DstVecEVT); @@ -2896,7 +2904,7 @@ // this operation. if (LHS.getOpcode() == ISD::VBUILD_VECTOR && RHS.getOpcode() == ISD::VBUILD_VECTOR) { - std::vector Ops; + SmallVector Ops; for (unsigned i = 0, e = LHS.getNumOperands()-2; i != e; ++i) { SDOperand LHSOp = LHS.getOperand(i); SDOperand RHSOp = RHS.getOperand(i); @@ -2927,7 +2935,7 @@ if (Ops.size() == LHS.getNumOperands()-2) { Ops.push_back(*(LHS.Val->op_end()-2)); Ops.push_back(*(LHS.Val->op_end()-1)); - return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops); + return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size()); } } Index: llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp diff -u llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:1.385 llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:1.386 --- llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:1.385 Mon Aug 7 20:09:31 2006 +++ llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp Mon Aug 7 21:23:41 2006 @@ -241,7 +241,7 @@ assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!"); if (NumEltsGrowth > 1) { // Renumber the elements. - std::vector Ops; + SmallVector Ops; for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) { SDOperand InOp = Mask.getOperand(i); for (unsigned j = 0; j != NumEltsGrowth; ++j) { @@ -253,7 +253,7 @@ } } } - Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, Ops); + Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, &Ops[0], Ops.size()); } VT = NVT; break; @@ -666,7 +666,7 @@ cast(Node->getOperand(4))->getValue(); unsigned SrcFile = DebugInfo->RecordSource(DirName, FName); - std::vector Ops; + SmallVector Ops; Ops.push_back(Tmp1); // chain SDOperand LineOp = Node->getOperand(1); SDOperand ColOp = Node->getOperand(2); @@ -675,13 +675,13 @@ Ops.push_back(LineOp); // line # Ops.push_back(ColOp); // col # Ops.push_back(DAG.getConstant(SrcFile, MVT::i32)); // source file id - Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops); + Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, &Ops[0], Ops.size()); } else { unsigned Line = cast(LineOp)->getValue(); unsigned Col = cast(ColOp)->getValue(); unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile); Ops.push_back(DAG.getConstant(ID, MVT::i32)); - Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops); + Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,&Ops[0],Ops.size()); } } else { Result = Tmp1; // chain @@ -889,14 +889,15 @@ // We generate a shuffle of InVec and ScVec, so the shuffle mask should // be 0,1,2,3,4,5... with the appropriate element replaced with elt 0 of // the RHS. - std::vector ShufOps; + SmallVector ShufOps; for (unsigned i = 0; i != NumElts; ++i) { if (i != InsertPos->getValue()) ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT)); else ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT)); } - SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,ShufOps); + SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT, + &ShufOps[0], ShufOps.size()); Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(), Tmp1, ScVec, ShufMask); @@ -985,7 +986,7 @@ MVT::ValueType PtrVT = TLI.getPointerTy(); SDOperand Mask = Node->getOperand(2); unsigned NumElems = Mask.getNumOperands(); - std::vector Ops; + SmallVector Ops; for (unsigned i = 0; i != NumElems; ++i) { SDOperand Arg = Mask.getOperand(i); if (Arg.getOpcode() == ISD::UNDEF) { @@ -1001,7 +1002,7 @@ DAG.getConstant(Idx - NumElems, PtrVT))); } } - Result = DAG.getNode(ISD::BUILD_VECTOR, VT, Ops); + Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()); break; } case TargetLowering::Promote: { @@ -2149,7 +2150,7 @@ assert(MVT::isVector(Node->getValueType(0)) && "Cannot expand this binary operator!"); // Expand the operation into a bunch of nasty scalar code. - std::vector Ops; + SmallVector Ops; MVT::ValueType EltVT = MVT::getVectorBaseType(Node->getValueType(0)); MVT::ValueType PtrVT = TLI.getPointerTy(); for (unsigned i = 0, e = MVT::getVectorNumElements(Node->getValueType(0)); @@ -2159,7 +2160,8 @@ SDOperand RHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2, Idx); Ops.push_back(DAG.getNode(Node->getOpcode(), EltVT, LHS, RHS)); } - Result = DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0), Ops); + Result = DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0), + &Ops[0], Ops.size()); break; } case TargetLowering::Promote: { @@ -3556,7 +3558,8 @@ MVT::getIntVectorWithNumElements(NumElems); SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT)); std::vector ZeroVec(NumElems, Zero); - SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec); + SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, + &ZeroVec[0], ZeroVec.size()); // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it. if (isShuffleLegal(Node->getValueType(0), SplatMask)) { @@ -3586,12 +3589,13 @@ MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT)); i += NumElems; } - SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec); + SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, + &MaskVec[0], MaskVec.size()); // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it. if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) && isShuffleLegal(Node->getValueType(0), ShuffleMask)) { - std::vector Ops; + SmallVector Ops; for(std::map >::iterator I=Values.begin(), E = Values.end(); I != E; ++I) { SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), @@ -3601,7 +3605,8 @@ Ops.push_back(ShuffleMask); // Return shuffle(LoValVec, HiValVec, <0,1,0,1>) - return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops); + return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), + &Ops[0], Ops.size()); } } @@ -3613,7 +3618,7 @@ SDOperand FIPtr = CreateStackTemporary(VT); // Emit a store of each element to the stack slot. - std::vector Stores; + SmallVector Stores; unsigned TypeByteSize = MVT::getSizeInBits(Node->getOperand(0).getValueType())/8; unsigned VectorSize = MVT::getSizeInBits(VT)/8; @@ -3634,7 +3639,8 @@ SDOperand StoreChain; if (!Stores.empty()) // Not all undef elements? - StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores); + StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, + &Stores[0], Stores.size()); else StoreChain = DAG.getEntryNode(); @@ -3658,12 +3664,9 @@ SDOperand LHSL, LHSH; ExpandOp(Op, LHSL, LHSH); - std::vector Ops; - Ops.push_back(LHSL); - Ops.push_back(LHSH); - Ops.push_back(Amt); + SDOperand Ops[] = { LHSL, LHSH, Amt }; std::vector VTs(2, LHSL.getValueType()); - Lo = DAG.getNode(NodeOp, VTs, Ops); + Lo = DAG.getNode(NodeOp, VTs, Ops, 3); Hi = Lo.getValue(1); } @@ -4634,21 +4637,21 @@ ExpandOp(Node->getOperand(0), LHSL, LHSH); ExpandOp(Node->getOperand(1), RHSL, RHSH); std::vector VTs; - std::vector LoOps, HiOps; + SDOperand LoOps[2], HiOps[2]; VTs.push_back(LHSL.getValueType()); VTs.push_back(MVT::Flag); - LoOps.push_back(LHSL); - LoOps.push_back(RHSL); - HiOps.push_back(LHSH); - HiOps.push_back(RHSH); + LoOps[0] = LHSL; + LoOps[1] = RHSL; + HiOps[0] = LHSH; + HiOps[1] = RHSH; if (Node->getOpcode() == ISD::ADD) { - Lo = DAG.getNode(ISD::ADDC, VTs, LoOps); - HiOps.push_back(Lo.getValue(1)); - Hi = DAG.getNode(ISD::ADDE, VTs, HiOps); + Lo = DAG.getNode(ISD::ADDC, VTs, LoOps, 2); + HiOps[2] = Lo.getValue(1); + Hi = DAG.getNode(ISD::ADDE, VTs, HiOps, 3); } else { - Lo = DAG.getNode(ISD::SUBC, VTs, LoOps); - HiOps.push_back(Lo.getValue(1)); - Hi = DAG.getNode(ISD::SUBE, VTs, HiOps); + Lo = DAG.getNode(ISD::SUBC, VTs, LoOps, 2); + HiOps[2] = Lo.getValue(1); + Hi = DAG.getNode(ISD::SUBE, VTs, HiOps, 3); } break; } @@ -4732,15 +4735,17 @@ #endif assert(0 && "Unhandled operation in SplitVectorOp!"); case ISD::VBUILD_VECTOR: { - std::vector LoOps(Node->op_begin(), Node->op_begin()+NewNumElts); + SmallVector LoOps(Node->op_begin(), + Node->op_begin()+NewNumElts); LoOps.push_back(NewNumEltsNode); LoOps.push_back(TypeNode); - Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, LoOps); + Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &LoOps[0], LoOps.size()); - std::vector HiOps(Node->op_begin()+NewNumElts, Node->op_end()-2); + SmallVector HiOps(Node->op_begin()+NewNumElts, + Node->op_end()-2); HiOps.push_back(NewNumEltsNode); HiOps.push_back(TypeNode); - Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, HiOps); + Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &HiOps[0], HiOps.size()); break; } case ISD::VADD: @@ -4891,8 +4896,8 @@ if (AllUndef) { Result = DAG.getNode(ISD::UNDEF, NewVT); } else { - std::vector Ops(Node->op_begin(), Node->op_end()-2); - Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Ops); + Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Node->op_begin(), + Node->getNumOperands()-2); } } break; @@ -4920,7 +4925,9 @@ std::vector BuildVecIdx(Node->getOperand(2).Val->op_begin(), Node->getOperand(2).Val->op_end()-2); MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size()); - SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT, BuildVecIdx); + SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT, + Node->getOperand(2).Val->op_begin(), + Node->getOperand(2).Val->getNumOperands()-2); Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, PackVectorOp(Node->getOperand(0), NewVT), Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp diff -u llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.320 llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.321 --- llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:1.320 Mon Aug 7 20:09:31 2006 +++ llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp Mon Aug 7 21:23:41 2006 @@ -1539,16 +1539,11 @@ SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT, SDOperand Chain, SDOperand Ptr, SDOperand SV, MVT::ValueType EVT) { - std::vector Ops; - Ops.reserve(4); - Ops.push_back(Chain); - Ops.push_back(Ptr); - Ops.push_back(SV); - Ops.push_back(getValueType(EVT)); + SDOperand Ops[] = { Chain, Ptr, SV, getValueType(EVT) }; std::vector VTs; VTs.reserve(2); VTs.push_back(VT); VTs.push_back(MVT::Other); // Add token chain. - return getNode(Opcode, VTs, Ops); + return getNode(Opcode, VTs, Ops, 4); } SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) { @@ -1565,15 +1560,11 @@ SDOperand SelectionDAG::getVAArg(MVT::ValueType VT, SDOperand Chain, SDOperand Ptr, SDOperand SV) { - std::vector Ops; - Ops.reserve(3); - Ops.push_back(Chain); - Ops.push_back(Ptr); - Ops.push_back(SV); + SDOperand Ops[] = { Chain, Ptr, SV }; std::vector VTs; VTs.reserve(2); VTs.push_back(VT); VTs.push_back(MVT::Other); // Add token chain. - return getNode(ISD::VAARG, VTs, Ops); + return getNode(ISD::VAARG, VTs, Ops, 3); } SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT, @@ -1719,17 +1710,6 @@ return SDOperand(N, 0); } -SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT, - std::vector &Ops) { - return getNode(Opcode, VT, &Ops[0], Ops.size()); -} - -SDOperand SelectionDAG::getNode(unsigned Opcode, - std::vector &ResultTys, - std::vector &Ops) { - return getNode(Opcode, ResultTys, &Ops[0], Ops.size()); -} - MVT::ValueType *SelectionDAG::getNodeValueTypes(MVT::ValueType VT) { return SDNode::getValueTypeList(VT); @@ -2233,59 +2213,33 @@ SDOperand Op1, SDOperand Op2, SDOperand Op3, SDOperand Op4, SDOperand Op5, SDOperand Op6) { - std::vector Ops; - Ops.reserve(6); - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - Ops.push_back(Op6); - return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5, Op6 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, 6).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT, SDOperand Op1, SDOperand Op2, SDOperand Op3, SDOperand Op4, SDOperand Op5, SDOperand Op6, SDOperand Op7) { - std::vector Ops; - Ops.reserve(7); - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - Ops.push_back(Op6); - Ops.push_back(Op7); - return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5, Op6, Op7 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, 7).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT, SDOperand Op1, SDOperand Op2, SDOperand Op3, SDOperand Op4, SDOperand Op5, SDOperand Op6, SDOperand Op7, SDOperand Op8) { - std::vector Ops; - Ops.reserve(8); - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - Ops.push_back(Op6); - Ops.push_back(Op7); - Ops.push_back(Op8); - return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5, Op6, Op7, Op8 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, 8).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT, - std::vector &Ops) { - return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val; + const SDOperand *Ops, unsigned NumOps) { + return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, SDOperand Op1) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); - std::vector Ops; - Ops.push_back(Op1); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, &Op1, 1).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, SDOperand Op1, @@ -2293,10 +2247,8 @@ std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 2).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, SDOperand Op1, @@ -2304,11 +2256,8 @@ std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 3).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, SDOperand Op1, @@ -2317,12 +2266,8 @@ std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 4).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, SDOperand Op1, @@ -2331,13 +2276,8 @@ std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 5).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, SDOperand Op1, @@ -2346,14 +2286,8 @@ std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - Ops.push_back(Op6); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5, Op6 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 6).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, SDOperand Op1, @@ -2363,15 +2297,8 @@ std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - Ops.push_back(Op6); - Ops.push_back(Op7); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5, Op6, Op7 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 7).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, MVT::ValueType VT3, @@ -2380,10 +2307,8 @@ ResultTys.push_back(VT1); ResultTys.push_back(VT2); ResultTys.push_back(VT3); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 2).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, MVT::ValueType VT3, @@ -2394,13 +2319,8 @@ ResultTys.push_back(VT1); ResultTys.push_back(VT2); ResultTys.push_back(VT3); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 5).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, MVT::ValueType VT3, @@ -2411,14 +2331,8 @@ ResultTys.push_back(VT1); ResultTys.push_back(VT2); ResultTys.push_back(VT3); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - Ops.push_back(Op6); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5, Op6 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 6).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, MVT::ValueType VT3, @@ -2429,23 +2343,16 @@ ResultTys.push_back(VT1); ResultTys.push_back(VT2); ResultTys.push_back(VT3); - std::vector Ops; - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - Ops.push_back(Op5); - Ops.push_back(Op6); - Ops.push_back(Op7); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5, Op6, Op7 }; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, 7).Val; } SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, MVT::ValueType VT2, - std::vector &Ops) { + const SDOperand *Ops, unsigned NumOps) { std::vector ResultTys; ResultTys.push_back(VT1); ResultTys.push_back(VT2); - return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val; + return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops, NumOps).Val; } /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp diff -u llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1.267 llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1.268 --- llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1.267 Wed Aug 2 19:18:59 2006 +++ llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp Mon Aug 7 21:23:41 2006 @@ -437,7 +437,8 @@ } // Otherwise, we have to make a token factor node. - SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads); + SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, + &PendingLoads[0], PendingLoads.size()); PendingLoads.clear(); DAG.setRoot(Root); return Root; @@ -598,13 +599,14 @@ unsigned NumElements = PTy->getNumElements(); MVT::ValueType PVT = TLI.getValueType(PTy->getElementType()); - std::vector Ops; + SmallVector Ops; Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT)); // Create a VConstant node with generic Vector type. Ops.push_back(DAG.getConstant(NumElements, MVT::i32)); Ops.push_back(DAG.getValueType(PVT)); - return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops); + return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, + &Ops[0], Ops.size()); } else if (ConstantFP *CFP = dyn_cast(C)) { return N = DAG.getConstantFP(CFP->getValue(), VT); } else if (const PackedType *PTy = dyn_cast(VTy)) { @@ -614,7 +616,7 @@ // Now that we know the number and type of the elements, push a // Constant or ConstantFP node onto the ops list for each element of // the packed constant. - std::vector Ops; + SmallVector Ops; if (ConstantPacked *CP = dyn_cast(C)) { for (unsigned i = 0; i != NumElements; ++i) Ops.push_back(getValue(CP->getOperand(i))); @@ -631,7 +633,7 @@ // Create a VBUILD_VECTOR node with generic Vector type. Ops.push_back(DAG.getConstant(NumElements, MVT::i32)); Ops.push_back(DAG.getValueType(PVT)); - return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops); + return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size()); } else { // Canonicalize all constant ints to be unsigned. return N = DAG.getConstant(cast(C)->getRawValue(),VT); @@ -676,7 +678,7 @@ PTyLegalElementVT); // Build a VBUILD_VECTOR with the input registers. - std::vector Ops; + SmallVector Ops; if (PTyElementVT == PTyLegalElementVT) { // If the value types are legal, just VBUILD the CopyFromReg nodes. for (unsigned i = 0; i != NE; ++i) @@ -707,7 +709,7 @@ Ops.push_back(DAG.getConstant(NE, MVT::i32)); Ops.push_back(DAG.getValueType(PTyLegalElementVT)); - N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops); + N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size()); // Finally, use a VBIT_CONVERT to make this available as the appropriate // vector type. @@ -726,7 +728,7 @@ DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot())); return; } - std::vector NewValues; + SmallVector NewValues; NewValues.push_back(getRoot()); for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { SDOperand RetOp = getValue(I.getOperand(i)); @@ -753,7 +755,8 @@ NewValues.push_back(RetOp); NewValues.push_back(DAG.getConstant(isSigned, MVT::i32)); } - DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues)); + DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, + &NewValues[0], NewValues.size())); } void SelectionDAGLowering::visitBr(BranchInst &I) { @@ -1346,11 +1349,8 @@ std::vector VTs; VTs.push_back(AllocSize.getValueType()); VTs.push_back(MVT::Other); - std::vector Ops; - Ops.push_back(getRoot()); - Ops.push_back(AllocSize); - Ops.push_back(getIntPtrConstant(Align)); - SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops); + SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) }; + SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops, 3); DAG.setRoot(setValue(&I, DSA).getValue(1)); // Inform the Frame Information that we have just allocated a variable-sized @@ -1427,7 +1427,7 @@ bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic); // Build the operand list. - std::vector Ops; + SmallVector Ops; if (HasChain) { // If this intrinsic has side-effects, chainify it. if (OnlyLoad) { // We don't need to serialize loads against other loads. @@ -1479,11 +1479,11 @@ // Create the node. SDOperand Result; if (!HasChain) - Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops); + Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, &Ops[0], Ops.size()); else if (I.getType() != Type::VoidTy) - Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops); + Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, &Ops[0], Ops.size()); else - Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops); + Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, &Ops[0], Ops.size()); if (HasChain) { SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1); @@ -1541,20 +1541,20 @@ MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo(); DbgStopPointInst &SPI = cast(I); if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) { - std::vector Ops; + SDOperand Ops[5]; - Ops.push_back(getRoot()); - Ops.push_back(getValue(SPI.getLineValue())); - Ops.push_back(getValue(SPI.getColumnValue())); + Ops[0] = getRoot(); + Ops[1] = getValue(SPI.getLineValue()); + Ops[2] = getValue(SPI.getColumnValue()); DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext()); assert(DD && "Not a debug information descriptor"); CompileUnitDesc *CompileUnit = cast(DD); - Ops.push_back(DAG.getString(CompileUnit->getFileName())); - Ops.push_back(DAG.getString(CompileUnit->getDirectory())); + Ops[3] = DAG.getString(CompileUnit->getFileName()); + Ops[4] = DAG.getString(CompileUnit->getDirectory()); - DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops)); + DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5)); } return 0; @@ -1563,14 +1563,9 @@ MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo(); DbgRegionStartInst &RSI = cast(I); if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) { - std::vector Ops; - unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext()); - - Ops.push_back(getRoot()); - Ops.push_back(DAG.getConstant(LabelID, MVT::i32)); - - DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops)); + DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(), + DAG.getConstant(LabelID, MVT::i32))); } return 0; @@ -1579,14 +1574,9 @@ MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo(); DbgRegionEndInst &REI = cast(I); if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) { - std::vector Ops; - unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext()); - - Ops.push_back(getRoot()); - Ops.push_back(DAG.getConstant(LabelID, MVT::i32)); - - DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops)); + DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, + getRoot(), DAG.getConstant(LabelID, MVT::i32))); } return 0; @@ -1596,14 +1586,9 @@ DbgFuncStartInst &FSI = cast(I); if (DebugInfo && FSI.getSubprogram() && DebugInfo->Verify(FSI.getSubprogram())) { - std::vector Ops; - unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram()); - - Ops.push_back(getRoot()); - Ops.push_back(DAG.getConstant(LabelID, MVT::i32)); - - DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops)); + DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, + getRoot(), DAG.getConstant(LabelID, MVT::i32))); } return 0; @@ -1612,12 +1597,9 @@ MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo(); DbgDeclareInst &DI = cast(I); if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) { - std::vector Ops; - SDOperand AddressOp = getValue(DI.getAddress()); - if (FrameIndexSDNode *FI = dyn_cast(AddressOp)) { + if (FrameIndexSDNode *FI = dyn_cast(AddressOp)) DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex()); - } } return 0; @@ -1644,9 +1626,8 @@ std::vector VTs; VTs.push_back(MVT::i64); VTs.push_back(MVT::Other); - std::vector Ops; - Ops.push_back(getRoot()); - SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops); + SDOperand Op = getRoot(); + SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, &Op, 1); setValue(&I, Tmp); DAG.setRoot(Tmp.getValue(1)); return 0; @@ -1686,9 +1667,8 @@ std::vector VTs; VTs.push_back(TLI.getPointerTy()); VTs.push_back(MVT::Other); - std::vector Ops; - Ops.push_back(getRoot()); - SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops); + SDOperand Op = getRoot(); + SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, &Op, 1); setValue(&I, Tmp); DAG.setRoot(Tmp.getValue(1)); return 0; @@ -2279,7 +2259,8 @@ std::vector VTs; VTs.push_back(MVT::Other); VTs.push_back(MVT::Flag); - Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands); + Chain = DAG.getNode(ISD::INLINEASM, VTs, + &AsmNodeOperands[0], AsmNodeOperands.size()); Flag = Chain.getValue(1); // If this asm returns a register value, copy the result from that register @@ -2299,14 +2280,15 @@ } // Emit the non-flagged stores from the physregs. - std::vector OutChains; + SmallVector OutChains; for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain, StoresToEmit[i].first, getValue(StoresToEmit[i].second), DAG.getSrcValue(StoresToEmit[i].second))); if (!OutChains.empty()) - Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains); + Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, + &OutChains[0], OutChains.size()); DAG.setRoot(Chain); } @@ -2446,7 +2428,8 @@ RetVals.push_back(MVT::Other); // Create the node. - SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, Ops).Val; + SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, + &Ops[0], Ops.size()).Val; DAG.setRoot(SDOperand(Result, Result->getNumValues()-1)); @@ -2653,7 +2636,7 @@ RetTys.push_back(MVT::Other); // Always has a chain. // Finally, create the CALL node. - SDOperand Res = DAG.getNode(ISD::CALL, RetTys, Ops); + SDOperand Res = DAG.getNode(ISD::CALL, RetTys, &Ops[0], Ops.size()); // This returns a pair of operands. The first element is the // return value for the function (if RetTy is not VoidTy). The second @@ -2862,7 +2845,7 @@ // Expand memset / memcpy to a series of load / store ops // if the size operand falls below a certain threshold. - std::vector OutChains; + SmallVector OutChains; switch (Op) { default: break; // Do nothing for now. case ISD::MEMSET: { @@ -2944,18 +2927,13 @@ } if (!OutChains.empty()) { - DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains)); + DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, + &OutChains[0], OutChains.size())); return; } } - std::vector Ops; - Ops.push_back(getRoot()); - Ops.push_back(Op1); - Ops.push_back(Op2); - Ops.push_back(Op3); - Ops.push_back(Op4); - DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops)); + DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4)); } //===----------------------------------------------------------------------===// @@ -3318,7 +3296,7 @@ // Loop over all of the elements of the resultant vector, // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then // copying them into output registers. - std::vector OutChains; + SmallVector OutChains; SDOperand Root = SDL.getRoot(); for (unsigned i = 0; i != NE; ++i) { SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT, @@ -3344,7 +3322,8 @@ OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi)); } } - return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains); + return DAG.getNode(ISD::TokenFactor, MVT::Other, + &OutChains[0], OutChains.size()); } else if (SrcVT < DestVT) { // The src value is promoted to the register. if (MVT::isFloatingPoint(SrcVT)) @@ -3500,7 +3479,8 @@ if (i == e) UnorderedChains.push_back(Root); } - DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains)); + DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, + &UnorderedChains[0], UnorderedChains.size())); } // Lower the terminator after the copies are emitted. From lattner at cs.uiuc.edu Mon Aug 7 21:24:04 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Mon, 7 Aug 2006 21:24:04 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/X86/X86ISelLowering.cpp Message-ID: <200608080224.k782O4cp030190@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/X86: X86ISelLowering.cpp updated: 1.241 -> 1.242 --- Log message: Start eliminating temporary vectors used to create DAG nodes. Instead, pass in the start of an array and a count of operands where applicable. In many cases, the number of operands is known, so this static array can be allocated on the stack, avoiding the heap. In many other cases, a SmallVector can be used, which has the same benefit in the common cases. I updated a lot of code calling getNode that takes a vector, but ran out of time. The rest of the code should be updated, and these methods should be removed. We should also do the same thing to eliminate the methods that take a vector of MVT::ValueTypes. It would be extra nice to convert the dagiselemitter to avoid creating vectors for operands when calling getTargetNode. --- Diffs of the changes: (+43 -34) X86ISelLowering.cpp | 77 +++++++++++++++++++++++++++++----------------------- 1 files changed, 43 insertions(+), 34 deletions(-) Index: llvm/lib/Target/X86/X86ISelLowering.cpp diff -u llvm/lib/Target/X86/X86ISelLowering.cpp:1.241 llvm/lib/Target/X86/X86ISelLowering.cpp:1.242 --- llvm/lib/Target/X86/X86ISelLowering.cpp:1.241 Mon Jul 31 18:26:50 2006 +++ llvm/lib/Target/X86/X86ISelLowering.cpp Mon Aug 7 21:23:41 2006 @@ -479,7 +479,7 @@ // Return the new list of results. std::vector RetVTs(Op.Val->value_begin(), Op.Val->value_end()); - return DAG.getNode(ISD::MERGE_VALUES, RetVTs, ArgValues); + return DAG.getNode(ISD::MERGE_VALUES, RetVTs, &ArgValues[0],ArgValues.size()); } @@ -596,7 +596,8 @@ } if (!MemOpChains.empty()) - Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOpChains); + Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, + &MemOpChains[0], MemOpChains.size()); // Build a sequence of copy-to-reg nodes chained together with token chain // and flag operands which copy the outgoing args into registers. @@ -631,7 +632,7 @@ Ops.push_back(InFlag); Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL, - NodeTys, Ops); + NodeTys, &Ops[0], Ops.size()); InFlag = Chain.getValue(1); // Create the CALLSEQ_END node. @@ -651,7 +652,7 @@ Ops.push_back(DAG.getConstant(NumBytes, getPointerTy())); Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy())); Ops.push_back(InFlag); - Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops); + Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size()); if (RetVT != MVT::Other) InFlag = Chain.getValue(1); @@ -703,7 +704,8 @@ std::vector Ops; Ops.push_back(Chain); Ops.push_back(InFlag); - SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops); + SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, + &Ops[0], Ops.size()); Chain = RetVal.getValue(1); InFlag = RetVal.getValue(2); if (X86ScalarSSE) { @@ -721,7 +723,7 @@ Ops.push_back(StackSlot); Ops.push_back(DAG.getValueType(RetVT)); Ops.push_back(InFlag); - Chain = DAG.getNode(X86ISD::FST, Tys, Ops); + Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size()); RetVal = DAG.getLoad(RetVT, Chain, StackSlot, DAG.getSrcValue(NULL)); Chain = RetVal.getValue(1); @@ -744,7 +746,8 @@ // Otherwise, merge everything together with a MERGE_VALUES node. NodeTys.push_back(MVT::Other); ResultVals.push_back(Chain); - SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, ResultVals); + SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, + &ResultVals[0], ResultVals.size()); return Res.getValue(Op.ResNo); } @@ -980,10 +983,10 @@ // Return the new list of results. std::vector RetVTs(Op.Val->value_begin(), Op.Val->value_end()); - return DAG.getNode(ISD::MERGE_VALUES, RetVTs, ArgValues); + return DAG.getNode(ISD::MERGE_VALUES, RetVTs, &ArgValues[0],ArgValues.size()); } -SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG) { +SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG){ SDOperand Chain = Op.getOperand(0); unsigned CallingConv= cast(Op.getOperand(1))->getValue(); bool isVarArg = cast(Op.getOperand(2))->getValue() != 0; @@ -1117,7 +1120,8 @@ } if (!MemOpChains.empty()) - Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOpChains); + Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, + &MemOpChains[0], MemOpChains.size()); // Build a sequence of copy-to-reg nodes chained together with token chain // and flag operands which copy the outgoing args into registers. @@ -1153,7 +1157,7 @@ // FIXME: Do not generate X86ISD::TAILCALL for now. Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL, - NodeTys, Ops); + NodeTys, &Ops[0], Ops.size()); InFlag = Chain.getValue(1); NodeTys.clear(); @@ -1165,7 +1169,7 @@ Ops.push_back(DAG.getConstant(NumBytes, getPointerTy())); Ops.push_back(DAG.getConstant(NumBytes, getPointerTy())); Ops.push_back(InFlag); - Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops); + Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size()); if (RetVT != MVT::Other) InFlag = Chain.getValue(1); @@ -1217,7 +1221,8 @@ std::vector Ops; Ops.push_back(Chain); Ops.push_back(InFlag); - SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops); + SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, + &Ops[0], Ops.size()); Chain = RetVal.getValue(1); InFlag = RetVal.getValue(2); if (X86ScalarSSE) { @@ -1235,7 +1240,7 @@ Ops.push_back(StackSlot); Ops.push_back(DAG.getValueType(RetVT)); Ops.push_back(InFlag); - Chain = DAG.getNode(X86ISD::FST, Tys, Ops); + Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size()); RetVal = DAG.getLoad(RetVT, Chain, StackSlot, DAG.getSrcValue(NULL)); Chain = RetVal.getValue(1); @@ -1259,7 +1264,8 @@ // Otherwise, merge everything together with a MERGE_VALUES node. NodeTys.push_back(MVT::Other); ResultVals.push_back(Chain); - SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, ResultVals); + SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, + &ResultVals[0], ResultVals.size()); return Res.getValue(Op.ResNo); } @@ -1963,7 +1969,7 @@ MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT)); } - Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec); + Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size()); return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1, Mask); } @@ -2049,7 +2055,8 @@ } if (Changed) - Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(), MaskVec); + Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(), + &MaskVec[0], MaskVec.size()); return Mask; } @@ -2063,7 +2070,7 @@ MaskVec.push_back(DAG.getConstant(NumElems, BaseVT)); for (unsigned i = 1; i != NumElems; ++i) MaskVec.push_back(DAG.getConstant(i, BaseVT)); - return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec); + return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size()); } /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation @@ -2076,7 +2083,7 @@ MaskVec.push_back(DAG.getConstant(i, BaseVT)); MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT)); } - return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec); + return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size()); } /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation @@ -2090,7 +2097,7 @@ MaskVec.push_back(DAG.getConstant(i + Half, BaseVT)); MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT)); } - return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec); + return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size()); } /// getZeroVector - Returns a vector of specified type with all zero elements. @@ -2102,7 +2109,7 @@ bool isFP = MVT::isFloatingPoint(EVT); SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT); std::vector ZeroVec(NumElems, Zero); - return DAG.getNode(ISD::BUILD_VECTOR, VT, ZeroVec); + return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size()); } /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32. @@ -2146,7 +2153,8 @@ SDOperand Zero = DAG.getConstant(0, EVT); std::vector MaskVec(NumElems, Zero); MaskVec[Idx] = DAG.getConstant(NumElems, EVT); - SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec); + SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, + &MaskVec[0], MaskVec.size()); return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask); } @@ -2281,7 +2289,8 @@ std::vector MaskVec; for (unsigned i = 0; i < NumElems; i++) MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT)); - SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec); + SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, + &MaskVec[0], MaskVec.size()); return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item, DAG.getNode(ISD::UNDEF, VT), Mask); } @@ -2832,7 +2841,7 @@ Ops.push_back(Tmp3); Ops.push_back(CC); Ops.push_back(InFlag); - Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops); + Hi = DAG.getNode(X86ISD::CMOV, Tys, &Ops[0], Ops.size()); InFlag = Hi.getValue(1); Ops.clear(); @@ -2840,13 +2849,13 @@ Ops.push_back(Tmp1); Ops.push_back(CC); Ops.push_back(InFlag); - Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops); + Lo = DAG.getNode(X86ISD::CMOV, Tys, &Ops[0], Ops.size()); } else { Ops.push_back(Tmp2); Ops.push_back(Tmp3); Ops.push_back(CC); Ops.push_back(InFlag); - Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops); + Lo = DAG.getNode(X86ISD::CMOV, Tys, &Ops[0], Ops.size()); InFlag = Lo.getValue(1); Ops.clear(); @@ -2854,7 +2863,7 @@ Ops.push_back(Tmp1); Ops.push_back(CC); Ops.push_back(InFlag); - Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops); + Hi = DAG.getNode(X86ISD::CMOV, Tys, &Ops[0], Ops.size()); } Tys.clear(); @@ -2863,7 +2872,7 @@ Ops.clear(); Ops.push_back(Lo); Ops.push_back(Hi); - return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops); + return DAG.getNode(ISD::MERGE_VALUES, Tys, &Ops[0], Ops.size()); } SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) { @@ -2891,7 +2900,7 @@ Ops.push_back(StackSlot); Ops.push_back(DAG.getValueType(SrcVT)); Result = DAG.getNode(X86ScalarSSE ? X86ISD::FILD_FLAG :X86ISD::FILD, - Tys, Ops); + Tys, &Ops[0], Ops.size()); if (X86ScalarSSE) { Chain = Result.getValue(1); @@ -2911,7 +2920,7 @@ Ops.push_back(StackSlot); Ops.push_back(DAG.getValueType(Op.getValueType())); Ops.push_back(InFlag); - Chain = DAG.getNode(X86ISD::FST, Tys, Ops); + Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size()); Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, DAG.getSrcValue(NULL)); } @@ -2950,7 +2959,7 @@ Ops.push_back(Chain); Ops.push_back(StackSlot); Ops.push_back(DAG.getValueType(Op.getOperand(0).getValueType())); - Value = DAG.getNode(X86ISD::FLD, Tys, Ops); + Value = DAG.getNode(X86ISD::FLD, Tys, &Ops[0], Ops.size()); Chain = Value.getValue(1); SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize); StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); @@ -3040,7 +3049,7 @@ Tys.push_back(MVT::Flag); Ops.push_back(DAG.getConstant(X86ISD::COND_NP, MVT::i8)); Ops.push_back(Cond); - SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops); + SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, &Ops[0], Ops.size()); SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8, DAG.getConstant(X86ISD::COND_E, MVT::i8), Tmp1.getValue(1)); @@ -3051,7 +3060,7 @@ Tys.push_back(MVT::Flag); Ops.push_back(DAG.getConstant(X86ISD::COND_P, MVT::i8)); Ops.push_back(Cond); - SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops); + SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, &Ops[0], Ops.size()); SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8, DAG.getConstant(X86ISD::COND_NE, MVT::i8), Tmp1.getValue(1)); @@ -3087,7 +3096,7 @@ std::vector Ops; for (unsigned i = 0; i < Op0.getNumOperands(); ++i) Ops.push_back(Op0.getOperand(i)); - Op0 = DAG.getNode(X86ISD::SETCC, Tys, Ops); + Op0 = DAG.getNode(X86ISD::SETCC, Tys, &Ops[0], Ops.size()); } CC = Op0.getOperand(0); From rafael.espindola at gmail.com Tue Aug 8 08:02:46 2006 From: rafael.espindola at gmail.com (Rafael Espindola) Date: Tue, 8 Aug 2006 08:02:46 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp ARMRegisterInfo.cpp Message-ID: <200608081302.k78D2klW009116@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/ARM: ARMISelDAGToDAG.cpp updated: 1.23 -> 1.24 ARMRegisterInfo.cpp updated: 1.9 -> 1.10 --- Log message: initial support for variable number of arguments --- Diffs of the changes: (+37 -12) ARMISelDAGToDAG.cpp | 24 ++++++++++++++++++++---- ARMRegisterInfo.cpp | 25 +++++++++++++++++-------- 2 files changed, 37 insertions(+), 12 deletions(-) Index: llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp diff -u llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp:1.23 llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp:1.24 --- llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp:1.23 Mon Aug 7 17:22:14 2006 +++ llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp Tue Aug 8 08:02:29 2006 @@ -79,7 +79,6 @@ unsigned CallConv = cast(Op.getOperand(1))->getValue(); assert(CallConv == CallingConv::C && "unknown calling convention"); bool isVarArg = cast(Op.getOperand(2))->getValue() != 0; - assert(isVarArg == false && "VarArg not supported"); bool isTailCall = cast(Op.getOperand(3))->getValue() != 0; assert(isTailCall == false && "tail call not supported"); SDOperand Callee = Op.getOperand(4); @@ -89,23 +88,40 @@ // only the link register. unsigned NumBytes = 4; - assert(NumOps <= 4); //no args on the stack + // Add up all the space actually used. + for (unsigned i = 4; i < NumOps; ++i) + NumBytes += MVT::getSizeInBits(Op.getOperand(5+2*i).getValueType())/8; // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes, MVT::i32)); - static const unsigned regs[] = { + SDOperand StackPtr = DAG.getRegister(ARM::R13, MVT::i32); + + static const unsigned int num_regs = 4; + static const unsigned regs[num_regs] = { ARM::R0, ARM::R1, ARM::R2, ARM::R3 }; std::vector > RegsToPass; + std::vector MemOpChains; for (unsigned i = 0; i != NumOps; ++i) { SDOperand Arg = Op.getOperand(5+2*i); - RegsToPass.push_back(std::make_pair(regs[i], Arg)); + assert(Arg.getValueType() == MVT::i32); + if (i < num_regs) + RegsToPass.push_back(std::make_pair(regs[i], Arg)); + else { + unsigned ArgOffset = (i - num_regs) * 4; + SDOperand PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType()); + PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff); + MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain, + Arg, PtrOff, DAG.getSrcValue(NULL))); + } } + if (!MemOpChains.empty()) + Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOpChains); // Build a sequence of copy-to-reg nodes chained together with token chain // and flag operands which copy the outgoing args into the appropriate regs. Index: llvm/lib/Target/ARM/ARMRegisterInfo.cpp diff -u llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.9 llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.10 --- llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.9 Fri Jul 21 07:26:16 2006 +++ llvm/lib/Target/ARM/ARMRegisterInfo.cpp Tue Aug 8 08:02:29 2006 @@ -124,10 +124,21 @@ //hack assert(NumBytes == 0); - //sub sp, sp, #4 - BuildMI(MBB, MBBI, ARM::subri, 2, ARM::R13).addReg(ARM::R13).addImm(4); - //str lr, [sp] - BuildMI(MBB, MBBI, ARM::str, 1, ARM::R14).addReg(ARM::R13); + if (MFI->hasCalls()) { + // We reserve argument space for call sites in the function immediately on + // entry to the current function. This eliminates the need for add/sub + // brackets around call sites. + NumBytes += MFI->getMaxCallFrameSize(); + } + + MFI->setStackSize(NumBytes); + + //sub sp, sp, #NumBytes + BuildMI(MBB, MBBI, ARM::subri, 2, ARM::R13).addReg(ARM::R13).addImm(NumBytes); + //add ip, sp, #NumBytes - 4 + BuildMI(MBB, MBBI, ARM::addri, 2, ARM::R12).addReg(ARM::R13).addImm(NumBytes - 4); + //str lr, [ip] + BuildMI(MBB, MBBI, ARM::str, 1, ARM::R14).addReg(ARM::R12); } void ARMRegisterInfo::emitEpilogue(MachineFunction &MF, @@ -138,13 +149,11 @@ MachineFrameInfo *MFI = MF.getFrameInfo(); int NumBytes = (int) MFI->getStackSize(); - //hack - assert(NumBytes == 0); //ldr lr, [sp] BuildMI(MBB, MBBI, ARM::ldr, 2, ARM::R14).addImm(0).addReg(ARM::R13); - //add sp, sp, #4 - BuildMI(MBB, MBBI, ARM::addri, 2, ARM::R13).addReg(ARM::R13).addImm(4); + //add sp, sp, #NumBytes + BuildMI(MBB, MBBI, ARM::addri, 2, ARM::R13).addReg(ARM::R13).addImm(NumBytes); } unsigned ARMRegisterInfo::getRARegister() const { From rafael.espindola at gmail.com Tue Aug 8 08:02:46 2006 From: rafael.espindola at gmail.com (Rafael Espindola) Date: Tue, 8 Aug 2006 08:02:46 -0500 Subject: [llvm-commits] CVS: llvm/test/Regression/CodeGen/ARM/vargs.ll Message-ID: <200608081302.k78D2kDm009115@zion.cs.uiuc.edu> Changes in directory llvm/test/Regression/CodeGen/ARM: vargs.ll added (r1.1) --- Log message: initial support for variable number of arguments --- Diffs of the changes: (+12 -0) vargs.ll | 12 ++++++++++++ 1 files changed, 12 insertions(+) Index: llvm/test/Regression/CodeGen/ARM/vargs.ll diff -c /dev/null llvm/test/Regression/CodeGen/ARM/vargs.ll:1.1 *** /dev/null Tue Aug 8 08:02:39 2006 --- llvm/test/Regression/CodeGen/ARM/vargs.ll Tue Aug 8 08:02:29 2006 *************** *** 0 **** --- 1,12 ---- + ; RUN: llvm-as < %s | llc -march=arm + %str = internal constant [43 x sbyte] c"Hello World %d %d %d %d %d %d %d %d %d %d\0A\00" ; <[43 x sbyte]*> [#uses=1] + + implementation ; Functions: + + int %main() { + entry: + %tmp = call int (sbyte*, ...)* %printf( sbyte* getelementptr ([43 x sbyte]* %str, int 0, uint 0), int 1, int 2, int 3, int 4, int 5, int 6, int 7, int 8, int 9, int 10 ) ; [#uses=0] + ret int 0 + } + + declare int %printf(sbyte*, ...) From criswell at cs.uiuc.edu Tue Aug 8 09:47:08 2006 From: criswell at cs.uiuc.edu (John Criswell) Date: Tue, 8 Aug 2006 09:47:08 -0500 Subject: [llvm-commits] CVS: llvm-gcc/README.llvm Message-ID: <200608081447.JAA15981@choi.cs.uiuc.edu> Changes in directory llvm-gcc: README.llvm updated: 1.1 -> 1.2 --- Log message: Added copyright, warranty, and source code download information for those components of glibc that we distribute. Serendipitiously updated the copyright years for LLVM. --- Diffs of the changes: (+17 -3) README.llvm | 20 +++++++++++++++++--- 1 files changed, 17 insertions(+), 3 deletions(-) Index: llvm-gcc/README.llvm diff -u llvm-gcc/README.llvm:1.1 llvm-gcc/README.llvm:1.2 --- llvm-gcc/README.llvm:1.1 Fri Mar 12 11:28:42 2004 +++ llvm-gcc/README.llvm Tue Aug 8 09:46:43 2006 @@ -4,9 +4,23 @@ General Public License and the GNU Lesser General Public License. Please see the file COPYING and COPYING.LIB for more details. -The software also has the following additional copyrights: +The software also has the following additional copyrights and warranty +information: -Copyright (c) 2003, 2004 University of Illinois at Urbana-Champaign. +Portions of the GNU C library are shipped with this software. The source is +contained in the LLVM distribution which can be downloaded from +http://llvm.org/releases/. It is licensed to you under the GNU Lesser General +Public License (see COPYING.LIB) and has the following copyrights and warranty: + +Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc. +Copyright (C) 1995,96,97,2002 Free Software Foundation, Inc. + +The GNU C Library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +Copyright (c) 2003, 2004, 2005, 2006 University of Illinois at Urbana-Champaign. All rights reserved. Developed by: @@ -15,7 +29,7 @@ University of Illinois at Urbana-Champaign - http://llvm.cs.uiuc.edu + http://llvm.org THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS From criswell at cs.uiuc.edu Tue Aug 8 09:48:19 2006 From: criswell at cs.uiuc.edu (John Criswell) Date: Tue, 8 Aug 2006 09:48:19 -0500 Subject: [llvm-commits] CVS: llvm/runtime/GCCLibraries/libc/remove.c qsort.c Message-ID: <200608081448.JAA16004@choi.cs.uiuc.edu> Changes in directory llvm/runtime/GCCLibraries/libc: remove.c updated: 1.1 -> 1.2 qsort.c updated: 1.4 -> 1.5 --- Log message: Describe and date modifications we made per LGPL requirements. --- Diffs of the changes: (+16 -1) qsort.c | 10 ++++++++++ remove.c | 7 ++++++- 2 files changed, 16 insertions(+), 1 deletion(-) Index: llvm/runtime/GCCLibraries/libc/remove.c diff -u llvm/runtime/GCCLibraries/libc/remove.c:1.1 llvm/runtime/GCCLibraries/libc/remove.c:1.2 --- llvm/runtime/GCCLibraries/libc/remove.c:1.1 Mon Nov 28 09:49:15 2005 +++ llvm/runtime/GCCLibraries/libc/remove.c Tue Aug 8 09:47:54 2006 @@ -1,6 +1,11 @@ //===-- remove.c - The remove function for the LLVM libc Library --*- C -*-===// // -// A lot of this code is ripped gratuitously from glibc and libiberty. +// This code is a modified form of the remove() function from the GNU C +// library. +// +// Modifications: +// 2005/11/28 - Added to LLVM tree. Functions renamed to allow compilation. +// Code to control symbol linkage types removed. // //===----------------------------------------------------------------------===// Index: llvm/runtime/GCCLibraries/libc/qsort.c diff -u llvm/runtime/GCCLibraries/libc/qsort.c:1.4 llvm/runtime/GCCLibraries/libc/qsort.c:1.5 --- llvm/runtime/GCCLibraries/libc/qsort.c:1.4 Fri Jul 28 13:30:52 2006 +++ llvm/runtime/GCCLibraries/libc/qsort.c Tue Aug 8 09:47:54 2006 @@ -1,3 +1,13 @@ +//===-- qsort.c - The qsort function for the LLVM libc Library ----*- C -*-===// +// +// This code is a modified form of the qsort() function from the GNU C +// library. +// +// Modifications: +// 2003/05/29 - Code disabled for compilation. Line wrapping changed. +// +//===----------------------------------------------------------------------===// + /* Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc. This file is part of the GNU C Library. Written by Douglas C. Schmidt (schmidt at ics.uci.edu). From criswell at cs.uiuc.edu Tue Aug 8 09:48:22 2006 From: criswell at cs.uiuc.edu (John Criswell) Date: Tue, 8 Aug 2006 09:48:22 -0500 Subject: [llvm-commits] CVS: llvm/runtime/GCCLibraries/libc/LICENSE.TXT Message-ID: <200608081448.JAA16008@choi.cs.uiuc.edu> Changes in directory llvm/runtime/GCCLibraries/libc: LICENSE.TXT updated: 1.3 -> 1.4 --- Log message: Make information more complete. --- Diffs of the changes: (+9 -0) LICENSE.TXT | 9 +++++++++ 1 files changed, 9 insertions(+) Index: llvm/runtime/GCCLibraries/libc/LICENSE.TXT diff -u llvm/runtime/GCCLibraries/libc/LICENSE.TXT:1.3 llvm/runtime/GCCLibraries/libc/LICENSE.TXT:1.4 --- llvm/runtime/GCCLibraries/libc/LICENSE.TXT:1.3 Fri Jul 28 13:16:00 2006 +++ llvm/runtime/GCCLibraries/libc/LICENSE.TXT Tue Aug 8 09:47:33 2006 @@ -6,3 +6,12 @@ Portions of glibc also contain copyrights and licenses from third parties. Those are listed in LICENSES. + +FSF copyright and warranty disclaimer: +Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc. +Copyright (C) 1995,96,97,2002 Free Software Foundation, Inc. + +The GNU C Library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. From lattner at cs.uiuc.edu Tue Aug 8 12:27:42 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 8 Aug 2006 12:27:42 -0500 Subject: [llvm-commits] CVS: llvm/docs/ReleaseNotes.html Message-ID: <200608081727.k78HRgNp013400@zion.cs.uiuc.edu> Changes in directory llvm/docs: ReleaseNotes.html updated: 1.358 -> 1.359 --- Log message: First draft of the llvm 1.8 release notes. --- Diffs of the changes: (+77 -162) ReleaseNotes.html | 239 +++++++++++++++++------------------------------------- 1 files changed, 77 insertions(+), 162 deletions(-) Index: llvm/docs/ReleaseNotes.html diff -u llvm/docs/ReleaseNotes.html:1.358 llvm/docs/ReleaseNotes.html:1.359 --- llvm/docs/ReleaseNotes.html:1.358 Wed Apr 19 23:24:28 2006 +++ llvm/docs/ReleaseNotes.html Tue Aug 8 12:27:28 2006 @@ -4,11 +4,11 @@ - LLVM 1.7 Release Notes + LLVM 1.8 Release Notes -
    LLVM 1.7 Release Notes
    +
    LLVM 1.8 Release Notes
    1. Introduction
    2. @@ -32,9 +32,10 @@

      This document contains the release notes for the LLVM compiler -infrastructure, release 1.7. Here we describe the status of LLVM, including any +infrastructure, release 1.8. Here we describe the status of LLVM, including any known problems and major improvements from the previous release. The most -up-to-date version of this document can be found on the LLVM releases web site. If you are not reading this on the LLVM web pages, you should probably go there because this document may be updated after the release.

      @@ -62,38 +63,30 @@

      This is the eighth public release of the LLVM Compiler Infrastructure. This release incorporates a large number of enhancements and new features, -including vector support (Intel SSE and Altivec), a new GCC4.0-based -C/C++ front-end, Objective C/C++ support, inline assembly support, and many -other big features. +including DWARF debugging support (C and C++ on Darwin/PPC), improved inline +assembly support, a new nightly +tester, llvm-config enhancments, many bugs +fixed, and performance and compile time improvements.

      - +
      -

      LLVM 1.7 includes a brand new llvm-gcc, based on GCC 4.0.1. This version -of llvm-gcc solves many serious long-standing problems with llvm-gcc, including -all of those blocked by the llvm-gcc 4 meta -bug. In addition, llvm-gcc4 implements support for many new features, -including GCC inline assembly, generic vector support, SSE and Altivec -intrinsics, and several new GCC attributes. Finally, llvm-gcc4 is -significantly faster than llvm-gcc3, respects -O options, its -c/-S options -correspond to GCC's (they emit native code), supports Objective C/C++, and -it has debugging support well underway.

      - -

      If you can use it, llvm-gcc4 offers significant new functionality, and we -hope that it will replace llvm-gcc3 completely in a future release. -Unfortunately, it does not currently support C++ exception handling at all, and -it only works on Apple Mac OS/X machines with X86 or PowerPC processors. +

      The llvm-gcc4 C front-end now generates debugging info for C and C++. This +information is propagated through the compiler and the code generator can +currently produce DWARF debugging information from it. DWARF is a standard +debugging format used on many platforms, but currently LLVM only includes +target support for Mac OS X targets for the 1.8 release.

      @@ -104,174 +97,96 @@
      -

      The LLVM IR and llvm-gcc4 front-end now fully support arbitrary GCC inline assembly. The LLVM X86 and PowerPC -code generators have initial support for it, -being able to compile basic statements, but are missing some features. Please -report any inline asm statements that crash the compiler or that are miscompiled -as bugs.

      +

      Inline assembly support is substantially improved in LLVM 1.8 over LLVM 1.7. +Many unsupported features are now supported, and inline asm support in the X86 +backend is far better. llvm-gcc4 now supports global register variables as +well.

      - +
      -

      LLVM 1.7 includes a new, fully functional, SPARC backend built in the -target-independent code generator. This SPARC backend includes support for -SPARC V8 and SPARC V9 subtargets (controlling whether V9 features can be used), -and targets the 32-bit SPARC ABI.

      - -

      The LLVM 1.7 release is the last release that will include the LLVM "SparcV9" -backend, which was the very first LLVM native code generator. It will -be removed in LLVM 1.8, being replaced with the new SPARC backend.

      +

      The Loop Optimizer pass now used "Loop-Closed SSA Form", which makes it +easier to update SSA form as loop transformations change the code. An +immediate benefit of this is that the loop unswitching pass can now unswitch +loops in more cases. +

      -
      Generic Vector Support +
      -

      LLVM now includes significantly extended support for SIMD vectors in its -core instruction set. It now includes three new instructions for manipulating -vectors: extractelement, -insertelement, and -shufflevector. Further, -many bugs in vector handling have been fixed, and vectors are now supported by -the target-independent code generator. For example, if a vector operation is -not supported by a particular target, it will be correctly broken down and -executed as scalar operations.

      +

      The code generator now lowers switch statements to jump tables, providing +significant performance boosts for applications (e.g. interpreters) whose +performance is highly correlated to switch statement performance.

      -

      Because llvm-gcc3 does not support GCC generic vectors or vector intrinsics, -llvm-gcc4 must be used.

      - -
      Intel SSE and PowerPC -Altivec support +
      -

      The LLVM X86 backend now supports Intel SSE 1, 2, and 3, and now uses scalar -SSE operations to implement scalar floating point math when the target supports -SSE1 (for floats) or SSE2 (for doubles). Vector SSE instructions are generated -by llvm-gcc4 when the generic vector mechanism or specific SSE intrinsics are -used. -

      - -

      The LLVM PowerPC backend now supports the Altivec instruction set, including -both GCC -maltivec and -faltivec modes. Altivec instructions are generated -by llvm-gcc4 when the generic vector mechanism or specific Altivec intrinsics -are used. +

      The LLVM JIT now allows clients to deallocate machine code JIT'd to its code +buffer. This is important for long living applications that depend on the JIT.

      - +
      -
        -
      • The Loop Unswitching pass (-loop-unswitch) has had several bugs - fixed, has several new features, and is enabled by default in llvmgcc3 - now.
      • -
      • The Loop Strength Reduction pass (-loop-reduce) is now enabled for - the X86 and Alpha backends.
      • -
      • The Instruction Combining pass (-instcombine) now includes a - framework and implementation for simplifying code based on whether computed - bits are demanded or not.
      • -
      • The Scalar Replacement of Aggregates pass (-scalarrepl) can now - promote simple unions to registers.
      • -
      • The Reassociation pass (-reassociate) can now - factor expressions, e.g. turning "A*A+A*B" into "A*(A+B)".
      • -
      • Several LLVM passes are significantly -faster.
      • -
      -
      - - +

      This release includes many other improvements, including improvements to + the optimizers and code generators (improving the generated code) changes to + speed up the compiler in many ways (improving algorithms and fine tuning + code), and changes to reduce the code size of the compiler itself.

      + +

      More specific changes include:

      + +
        +
      • LLVM 1.8 includes an initial ARM backend. This backend is in early + development stages.
      • +
      • LLVM 1.8 now includes significantly better support for mingw and + cygwin.
      • +
      • The llvm-config tool is + now built by default and has several new features.
      • +
      • The X86 and PPC backends now use the correct platform ABI for passing + vectors as arguments to functions.
      • +
      • The X86 backend now includes support for the Microsoft ML assembler + ("MASM").
      • +
      • The PowerPC backend now pattern matches the 'rlwimi' instruction more + aggressively.
      • +
      • Most of LLVM is now built with "-pedantic", ensuring better portability + to more C++ Compilers.
      • +
      • The PowerPC backend now includes initial 64-bit support. The JIT is not + complete, and the static compiler has a couple of known bugs, but support + is mostly in place. LLVM 1.9 will include completed PPC-64 support.
      • -
        -
          -
        • LLVM has a new prepass (before register allocation) list scheduler, which - supports bottom-up and top-down scheduling, pluggable priority functions and - pluggable hazard recognizers. The X86 backend uses this to reduce register - pressure and RISC targets schedule based on operation latency.
        • -
        • The tblgen-based target description framework introduced in LLVM 1.6 has - several new features, useful for targets that can fold loads and stores into - operations, and features that make the .td files more expressive.
        • -
        • The instruction selector is significantly faster in 1.7 than in 1.6.
        • -
        • The X86, Alpha and Itanium backends use new DAG-DAG instruction selectors, - making them easier to maintain and generate slightly better code.
        • -
        • The X86 backend now supports generation of Scalar SSE code for scalar FP - expressions. LLVM provides significantly better performance with Scalar SSE - instructions than it does with the Intel floating point stack - instructions.
        • -
        • The Itanium backend now has a bundling pass, which improves performance - by ~10% and reduces code size (previously it unconditionally inserted a stop - bit after every instruction).
        - - - -
        -
          -
        • The Mac OS/X PowerPC and X86 backends now have initial support for - Darwin DWARF - debugging information, however, debug info generation has been disabled for - the 1.7 release in llvmgcc4.
        • -
        • LLVM includes the new - llvm-config utility, which makes it easier to build and link programs - against the LLVM libraries when not using the LLVM makefiles.
        • -
        • LLVM now supports first class global ctor/dtor initialization lists, no - longer forcing targets to use "__main".
        • -
        • LLVM supports assigning globals and functions to a particular section - in the result executable using the GCC section attribute.
        • -
        • Adding intrinsics to LLVM is now - significantly easier.
        • -
        • llvmgcc4 now fully supports C99 Variable Length Arrays, including dynamic - stack deallocation.
        • - -
        -
        - -
          -
        • The official LLVM URL is now - http://llvm.org/.
        • -
        • The LLVM intrinsics used to be overloaded based on type: for example, - llvm.ctpop could work with any - integer datatype. They are now separated into different intrinsics with - suffixes to denote their argument type (e.g. llvm.ctpop.i32)). Old - LLVM .ll and .bc files that use these intrinsics will continue to work with - new LLVM versions (they are transparently upgraded by the parsers), but will - cause a warning to be emitted.
        • -
        • The llvm.readport, llvm.writeport, llvm.readio, - and llvm.writeio intrinsics have been removed. The first two - were ever only supported by the X86 backend, the last two were never - correctly supported by any target, and none were accessible through the - C front-end. Inline assembly support can now be used to - implement these operations.
        • -
        • The llvm-db tool had basic support for stepping through code, which - used the JIT. This code has been removed, and DWARF emission support added - instead. llvm-db still exists in CVS if someone wanted to write a - ptrace backend for it.
        • +
        • The LLVM "SparcV9" backend (deprecated in LLVM 1.7) has been removed in +LLVM 1.8. The LLVM "Sparc" backend replaces it.
        • +
        • The --version option now prints more useful information, including the + build configuration for the tool.
        @@ -382,8 +297,7 @@

        -llvm-gcc3 has many significant problems that are fixed by llvm-gcc4. See - those blocked on the llvm-gcc4 meta bug. +llvm-gcc3 has many significant problems that are fixed by llvm-gcc4. Two major ones include:

          @@ -401,6 +315,11 @@ href="http://llvm.org/PR162">with the largest union member.
        + +

        llvm-gcc4 is far more stable and produces better code than llvm-gcc3, but +does not currently support Link-Time-Optimization or C++ Exception Handling, +which llvm-gcc3 does.

        +
        @@ -638,8 +557,7 @@ @@ -718,19 +636,16 @@
      -
      @@ -768,7 +683,7 @@ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /> The LLVM Compiler Infrastructure
      - Last modified: $Date: 2006/04/20 04:24:28 $ + Last modified: $Date: 2006/08/08 17:27:28 $ From rafael.espindola at gmail.com Tue Aug 8 15:35:17 2006 From: rafael.espindola at gmail.com (Rafael Espindola) Date: Tue, 8 Aug 2006 15:35:17 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/ARM/ARMInstrInfo.cpp ARMInstrInfo.h ARMInstrInfo.td ARMRegisterInfo.cpp Message-ID: <200608082035.k78KZHB3016251@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/ARM: ARMInstrInfo.cpp updated: 1.4 -> 1.5 ARMInstrInfo.h updated: 1.2 -> 1.3 ARMInstrInfo.td updated: 1.12 -> 1.13 ARMRegisterInfo.cpp updated: 1.10 -> 1.11 --- Log message: change the addressing mode of the str instruction to reg+imm --- Diffs of the changes: (+13 -7) ARMInstrInfo.cpp | 4 ++++ ARMInstrInfo.h | 4 ++++ ARMInstrInfo.td | 6 +++--- ARMRegisterInfo.cpp | 6 ++---- 4 files changed, 13 insertions(+), 7 deletions(-) Index: llvm/lib/Target/ARM/ARMInstrInfo.cpp diff -u llvm/lib/Target/ARM/ARMInstrInfo.cpp:1.4 llvm/lib/Target/ARM/ARMInstrInfo.cpp:1.5 --- llvm/lib/Target/ARM/ARMInstrInfo.cpp:1.4 Sun Jul 9 20:41:35 2006 +++ llvm/lib/Target/ARM/ARMInstrInfo.cpp Tue Aug 8 15:35:03 2006 @@ -22,6 +22,10 @@ : TargetInstrInfo(ARMInsts, sizeof(ARMInsts)/sizeof(ARMInsts[0])) { } +const TargetRegisterClass *ARMInstrInfo::getPointerRegClass() const { + return &ARM::IntRegsRegClass; +} + /// Return true if the instruction is a register to register move and /// leave the source and dest operands in the passed parameters. /// Index: llvm/lib/Target/ARM/ARMInstrInfo.h diff -u llvm/lib/Target/ARM/ARMInstrInfo.h:1.2 llvm/lib/Target/ARM/ARMInstrInfo.h:1.3 --- llvm/lib/Target/ARM/ARMInstrInfo.h:1.2 Sun Jul 9 20:41:35 2006 +++ llvm/lib/Target/ARM/ARMInstrInfo.h Tue Aug 8 15:35:03 2006 @@ -31,6 +31,10 @@ /// virtual const MRegisterInfo &getRegisterInfo() const { return RI; } + /// getPointerRegClass - Return the register class to use to hold pointers. + /// This is used for addressing modes. + virtual const TargetRegisterClass *getPointerRegClass() const; + /// Return true if the instruction is a register to register move and /// leave the source and dest operands in the passed parameters. /// Index: llvm/lib/Target/ARM/ARMInstrInfo.td diff -u llvm/lib/Target/ARM/ARMInstrInfo.td:1.12 llvm/lib/Target/ARM/ARMInstrInfo.td:1.13 --- llvm/lib/Target/ARM/ARMInstrInfo.td:1.12 Thu Aug 3 12:02:20 2006 +++ llvm/lib/Target/ARM/ARMInstrInfo.td Tue Aug 8 15:35:03 2006 @@ -67,9 +67,9 @@ "ldr $dst, $addr", [(set IntRegs:$dst, (load iaddr:$addr))]>; -def str : InstARM<(ops IntRegs:$src, IntRegs:$addr), - "str $src, [$addr]", - [(store IntRegs:$src, IntRegs:$addr)]>; +def str : InstARM<(ops IntRegs:$src, memri:$addr), + "str $src, $addr", + [(store IntRegs:$src, iaddr:$addr)]>; def movrr : InstARM<(ops IntRegs:$dst, IntRegs:$src), "mov $dst, $src", []>; Index: llvm/lib/Target/ARM/ARMRegisterInfo.cpp diff -u llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.10 llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.11 --- llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.10 Tue Aug 8 08:02:29 2006 +++ llvm/lib/Target/ARM/ARMRegisterInfo.cpp Tue Aug 8 15:35:03 2006 @@ -135,10 +135,8 @@ //sub sp, sp, #NumBytes BuildMI(MBB, MBBI, ARM::subri, 2, ARM::R13).addReg(ARM::R13).addImm(NumBytes); - //add ip, sp, #NumBytes - 4 - BuildMI(MBB, MBBI, ARM::addri, 2, ARM::R12).addReg(ARM::R13).addImm(NumBytes - 4); - //str lr, [ip] - BuildMI(MBB, MBBI, ARM::str, 1, ARM::R14).addReg(ARM::R12); + //str lr, [sp, #NumBytes - 4] + BuildMI(MBB, MBBI, ARM::str, 2, ARM::R14).addImm(NumBytes - 4).addReg(ARM::R13); } void ARMRegisterInfo::emitEpilogue(MachineFunction &MF, From lattner at cs.uiuc.edu Tue Aug 8 23:09:06 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 8 Aug 2006 23:09:06 -0500 Subject: [llvm-commits] CVS: llvm/docs/ReleaseNotes.html Message-ID: <200608090409.k79496fk023951@zion.cs.uiuc.edu> Changes in directory llvm/docs: ReleaseNotes.html updated: 1.359 -> 1.360 --- Log message: Fixes from Anton Vayvod and Gabor Greif! --- Diffs of the changes: (+5 -5) ReleaseNotes.html | 10 +++++----- 1 files changed, 5 insertions(+), 5 deletions(-) Index: llvm/docs/ReleaseNotes.html diff -u llvm/docs/ReleaseNotes.html:1.359 llvm/docs/ReleaseNotes.html:1.360 --- llvm/docs/ReleaseNotes.html:1.359 Tue Aug 8 12:27:28 2006 +++ llvm/docs/ReleaseNotes.html Tue Aug 8 23:08:52 2006 @@ -61,11 +61,11 @@
      -

      This is the eighth public release of the LLVM Compiler Infrastructure. This +

      This is the nineth public release of the LLVM Compiler Infrastructure. This release incorporates a large number of enhancements and new features, including DWARF debugging support (C and C++ on Darwin/PPC), improved inline assembly support, a new nightly -tester, llvm-config enhancments, many bugs +tester, llvm-config enhancements, many bugs fixed, and performance and compile time improvements.

      @@ -109,7 +109,7 @@
      -

      The Loop Optimizer pass now used "Loop-Closed SSA Form", which makes it +

      The loop optimizer passes now uses "Loop-Closed SSA Form", which makes it easier to update SSA form as loop transformations change the code. An immediate benefit of this is that the loop unswitching pass can now unswitch loops in more cases. @@ -247,7 +247,7 @@ be broken or unreliable, or are in early development. These components should not be relied on, and bugs should not be filed against them, but they may be useful to some people. In particular, if you would like to work on one of these -components, please contact us on the llvmdev list.

      +components, please contact us on the LLVMdev list.

      • The -cee pass is known to be buggy, and may be removed in in a @@ -683,7 +683,7 @@ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /> The LLVM Compiler Infrastructure
        - Last modified: $Date: 2006/08/08 17:27:28 $ + Last modified: $Date: 2006/08/09 04:08:52 $ From lattner at cs.uiuc.edu Tue Aug 8 23:10:46 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Tue, 8 Aug 2006 23:10:46 -0500 Subject: [llvm-commits] CVS: llvm/docs/ReleaseNotes.html Message-ID: <200608090410.k794AkZP024048@zion.cs.uiuc.edu> Changes in directory llvm/docs: ReleaseNotes.html updated: 1.360 -> 1.361 --- Log message: Update from Anton Korobeynikov --- Diffs of the changes: (+2 -1) ReleaseNotes.html | 3 ++- 1 files changed, 2 insertions(+), 1 deletion(-) Index: llvm/docs/ReleaseNotes.html diff -u llvm/docs/ReleaseNotes.html:1.360 llvm/docs/ReleaseNotes.html:1.361 --- llvm/docs/ReleaseNotes.html:1.360 Tue Aug 8 23:08:52 2006 +++ llvm/docs/ReleaseNotes.html Tue Aug 8 23:10:32 2006 @@ -204,6 +204,7 @@
        • Intel and AMD machines running Red Hat Linux, Fedora Core and FreeBSD (and probably other unix-like systems).
        • +
        • Intel and AMD machines running on Win32 using MinGW libraries (native)
        • Sun UltraSPARC workstations running Solaris 8.
        • Intel and AMD machines running on Win32 with the Cygwin libraries (limited support is available for native builds with Visual C++).
        • @@ -683,7 +684,7 @@ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /> The LLVM Compiler Infrastructure
          - Last modified: $Date: 2006/08/09 04:08:52 $ + Last modified: $Date: 2006/08/09 04:10:32 $ From tbrethou at cs.uiuc.edu Tue Aug 8 23:11:12 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Tue, 8 Aug 2006 23:11:12 -0500 Subject: [llvm-commits] [release_18] CVS: llvm-gcc/README.llvm Message-ID: <200608090411.k794BCP7024068@zion.cs.uiuc.edu> Changes in directory llvm-gcc: README.llvm updated: 1.1 -> 1.1.14.1 --- Log message: Updating README with year and correct link to website --- Diffs of the changes: (+17 -3) README.llvm | 20 +++++++++++++++++--- 1 files changed, 17 insertions(+), 3 deletions(-) Index: llvm-gcc/README.llvm diff -u llvm-gcc/README.llvm:1.1 llvm-gcc/README.llvm:1.1.14.1 --- llvm-gcc/README.llvm:1.1 Fri Mar 12 11:28:42 2004 +++ llvm-gcc/README.llvm Tue Aug 8 23:10:59 2006 @@ -4,9 +4,23 @@ General Public License and the GNU Lesser General Public License. Please see the file COPYING and COPYING.LIB for more details. -The software also has the following additional copyrights: +The software also has the following additional copyrights and warranty +information: -Copyright (c) 2003, 2004 University of Illinois at Urbana-Champaign. +Portions of the GNU C library are shipped with this software. The source is +contained in the LLVM distribution which can be downloaded from +http://llvm.org/releases/. It is licensed to you under the GNU Lesser General +Public License (see COPYING.LIB) and has the following copyrights and warranty: + +Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc. +Copyright (C) 1995,96,97,2002 Free Software Foundation, Inc. + +The GNU C Library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +Copyright (c) 2003, 2004, 2005, 2006 University of Illinois at Urbana-Champaign. All rights reserved. Developed by: @@ -15,7 +29,7 @@ University of Illinois at Urbana-Champaign - http://llvm.cs.uiuc.edu + http://llvm.org THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS From tbrethou at cs.uiuc.edu Tue Aug 8 23:18:22 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Tue, 8 Aug 2006 23:18:22 -0500 Subject: [llvm-commits] CVS: llvm/CREDITS.TXT Message-ID: <200608090418.k794IMoP024223@zion.cs.uiuc.edu> Changes in directory llvm: CREDITS.TXT updated: 1.61 -> 1.62 --- Log message: Update credits and fix sorting issue. --- Diffs of the changes: (+5 -4) CREDITS.TXT | 9 +++++---- 1 files changed, 5 insertions(+), 4 deletions(-) Index: llvm/CREDITS.TXT diff -u llvm/CREDITS.TXT:1.61 llvm/CREDITS.TXT:1.62 --- llvm/CREDITS.TXT:1.61 Tue Aug 1 11:52:07 2006 +++ llvm/CREDITS.TXT Tue Aug 8 23:18:09 2006 @@ -85,6 +85,10 @@ E: arathorn at fastwebnet.it D: Visual C++ compatibility fixes +N: Patrick Jenkins +E: patjenk at wam.umd.edu +D: Nightly Tester + N: Brad Jones E: kungfoomaster at nondot.org D: Support for packed types @@ -118,6 +122,7 @@ W: http://nondot.org/~tonic/ D: The initial llvm-ar tool, converted regression testsuite to dejagnu D: Modulo scheduling in the SparcV9 backend +D: Release manager (1.7+) N: Andrew Lenharth E: alenhar2 at cs.uiuc.edu @@ -170,7 +175,3 @@ E: isanbard at gmail.com D: The `Lower Setjmp/Longjmp' pass, improvements to the -lowerswitch pass. D: Bug hunter extraordinaire. - -N: Patrick Jenkins -E: patjenk at wam.umd.edu -D: Nightly Tester From tbrethou at cs.uiuc.edu Tue Aug 8 23:19:15 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Tue, 8 Aug 2006 23:19:15 -0500 Subject: [llvm-commits] [release_18] CVS: llvm/CREDITS.TXT Message-ID: <200608090419.k794JF1S024251@zion.cs.uiuc.edu> Changes in directory llvm: CREDITS.TXT updated: 1.57 -> 1.57.2.1 --- Log message: Updating credits from mainline --- Diffs of the changes: (+17 -9) CREDITS.TXT | 26 +++++++++++++++++--------- 1 files changed, 17 insertions(+), 9 deletions(-) Index: llvm/CREDITS.TXT diff -u llvm/CREDITS.TXT:1.57 llvm/CREDITS.TXT:1.57.2.1 --- llvm/CREDITS.TXT:1.57 Wed Jul 5 15:17:26 2006 +++ llvm/CREDITS.TXT Tue Aug 8 23:19:03 2006 @@ -85,6 +85,10 @@ E: arathorn at fastwebnet.it D: Visual C++ compatibility fixes +N: Patrick Jenkins +E: patjenk at wam.umd.edu +D: Nightly Tester + N: Brad Jones E: kungfoomaster at nondot.org D: Support for packed types @@ -93,6 +97,10 @@ W: http://randomhacks.net/ D: llvm-config script +N: Anton Korobeynikov +E: asl at math.spbu.ru +D: Mingw32 fixes, cross-compiling support, minor changes here and there + N: Sumant Kowshik E: kowshik at uiuc.edu D: Author of the original C backend @@ -100,7 +108,9 @@ N: Jim Laskey E: jlaskey at apple.com D: Improvements to the PPC backend, instruction scheduling -D: Debug implementation, Dwarf implementation +D: Debug and Dwarf implementation +D: Auto upgrade mangler +D: llvm-gcc4 svn wrangler N: Chris Lattner E: sabre at nondot.org @@ -112,6 +122,7 @@ W: http://nondot.org/~tonic/ D: The initial llvm-ar tool, converted regression testsuite to dejagnu D: Modulo scheduling in the SparcV9 backend +D: Release manager (1.7+) N: Andrew Lenharth E: alenhar2 at cs.uiuc.edu @@ -150,20 +161,17 @@ D: The `paths' pass N: Reid Spencer -E: rspencer at x10sys.com -W: http://llvm.x10sys.com/rspencer +E: rspencer at reidspencer.com +W: http://reidspencer.com/ D: Stacker, llvmc, llvm-ld, llvm-ar, lib/Archive, lib/Linker, lib/System, D: bytecode enhancements, symtab hacking, unoverloading of intrinsics, makefile -D: and configuration system, documentation. +D: and configuration system, documentation, various bug fixing. N: Adam Treat E: manyoso at yahoo.com D: C++ bugs filed, and C++ front-end bug fixes. N: Bill Wendling -E: wendling at isanbard.org +E: isanbard at gmail.com D: The `Lower Setjmp/Longjmp' pass, improvements to the -lowerswitch pass. - -N: Patrick Jenkins -E: patjenk at wam.umd.edu -D: Nightly Tester +D: Bug hunter extraordinaire. From tbrethou at cs.uiuc.edu Tue Aug 8 23:31:52 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Tue, 8 Aug 2006 23:31:52 -0500 Subject: [llvm-commits] [release_18] CVS: llvm/docs/ReleaseNotes.html Message-ID: <200608090431.k794VqGY024479@zion.cs.uiuc.edu> Changes in directory llvm/docs: ReleaseNotes.html updated: 1.358 -> 1.358.2.1 --- Log message: Merge from mainline --- Diffs of the changes: (+80 -164) ReleaseNotes.html | 244 +++++++++++++++++------------------------------------- 1 files changed, 80 insertions(+), 164 deletions(-) Index: llvm/docs/ReleaseNotes.html diff -u llvm/docs/ReleaseNotes.html:1.358 llvm/docs/ReleaseNotes.html:1.358.2.1 --- llvm/docs/ReleaseNotes.html:1.358 Wed Apr 19 23:24:28 2006 +++ llvm/docs/ReleaseNotes.html Tue Aug 8 23:31:39 2006 @@ -4,11 +4,11 @@ - LLVM 1.7 Release Notes + LLVM 1.8 Release Notes -
          LLVM 1.7 Release Notes
          +
          LLVM 1.8 Release Notes
          1. Introduction
          2. @@ -32,9 +32,10 @@

            This document contains the release notes for the LLVM compiler -infrastructure, release 1.7. Here we describe the status of LLVM, including any +infrastructure, release 1.8. Here we describe the status of LLVM, including any known problems and major improvements from the previous release. The most -up-to-date version of this document can be found on the LLVM releases web site. If you are not reading this on the LLVM web pages, you should probably go there because this document may be updated after the release.

            @@ -60,40 +61,32 @@
            -

            This is the eighth public release of the LLVM Compiler Infrastructure. This +

            This is the nineth public release of the LLVM Compiler Infrastructure. This release incorporates a large number of enhancements and new features, -including vector support (Intel SSE and Altivec), a new GCC4.0-based -C/C++ front-end, Objective C/C++ support, inline assembly support, and many -other big features. +including DWARF debugging support (C and C++ on Darwin/PPC), improved inline +assembly support, a new nightly +tester, llvm-config enhancements, many bugs +fixed, and performance and compile time improvements.

            - +
            -

            LLVM 1.7 includes a brand new llvm-gcc, based on GCC 4.0.1. This version -of llvm-gcc solves many serious long-standing problems with llvm-gcc, including -all of those blocked by the llvm-gcc 4 meta -bug. In addition, llvm-gcc4 implements support for many new features, -including GCC inline assembly, generic vector support, SSE and Altivec -intrinsics, and several new GCC attributes. Finally, llvm-gcc4 is -significantly faster than llvm-gcc3, respects -O options, its -c/-S options -correspond to GCC's (they emit native code), supports Objective C/C++, and -it has debugging support well underway.

            - -

            If you can use it, llvm-gcc4 offers significant new functionality, and we -hope that it will replace llvm-gcc3 completely in a future release. -Unfortunately, it does not currently support C++ exception handling at all, and -it only works on Apple Mac OS/X machines with X86 or PowerPC processors. +

            The llvm-gcc4 C front-end now generates debugging info for C and C++. This +information is propagated through the compiler and the code generator can +currently produce DWARF debugging information from it. DWARF is a standard +debugging format used on many platforms, but currently LLVM only includes +target support for Mac OS X targets for the 1.8 release.

            @@ -104,174 +97,96 @@
            -

            The LLVM IR and llvm-gcc4 front-end now fully support arbitrary GCC inline assembly. The LLVM X86 and PowerPC -code generators have initial support for it, -being able to compile basic statements, but are missing some features. Please -report any inline asm statements that crash the compiler or that are miscompiled -as bugs.

            +

            Inline assembly support is substantially improved in LLVM 1.8 over LLVM 1.7. +Many unsupported features are now supported, and inline asm support in the X86 +backend is far better. llvm-gcc4 now supports global register variables as +well.

            - +
            -

            LLVM 1.7 includes a new, fully functional, SPARC backend built in the -target-independent code generator. This SPARC backend includes support for -SPARC V8 and SPARC V9 subtargets (controlling whether V9 features can be used), -and targets the 32-bit SPARC ABI.

            - -

            The LLVM 1.7 release is the last release that will include the LLVM "SparcV9" -backend, which was the very first LLVM native code generator. It will -be removed in LLVM 1.8, being replaced with the new SPARC backend.

            +

            The loop optimizer passes now uses "Loop-Closed SSA Form", which makes it +easier to update SSA form as loop transformations change the code. An +immediate benefit of this is that the loop unswitching pass can now unswitch +loops in more cases. +

            -
            Generic Vector Support +
            -

            LLVM now includes significantly extended support for SIMD vectors in its -core instruction set. It now includes three new instructions for manipulating -vectors: extractelement, -insertelement, and -shufflevector. Further, -many bugs in vector handling have been fixed, and vectors are now supported by -the target-independent code generator. For example, if a vector operation is -not supported by a particular target, it will be correctly broken down and -executed as scalar operations.

            +

            The code generator now lowers switch statements to jump tables, providing +significant performance boosts for applications (e.g. interpreters) whose +performance is highly correlated to switch statement performance.

            -

            Because llvm-gcc3 does not support GCC generic vectors or vector intrinsics, -llvm-gcc4 must be used.

            - -
            Intel SSE and PowerPC -Altivec support +
            -

            The LLVM X86 backend now supports Intel SSE 1, 2, and 3, and now uses scalar -SSE operations to implement scalar floating point math when the target supports -SSE1 (for floats) or SSE2 (for doubles). Vector SSE instructions are generated -by llvm-gcc4 when the generic vector mechanism or specific SSE intrinsics are -used. -

            - -

            The LLVM PowerPC backend now supports the Altivec instruction set, including -both GCC -maltivec and -faltivec modes. Altivec instructions are generated -by llvm-gcc4 when the generic vector mechanism or specific Altivec intrinsics -are used. +

            The LLVM JIT now allows clients to deallocate machine code JIT'd to its code +buffer. This is important for long living applications that depend on the JIT.

            - +
            -
              -
            • The Loop Unswitching pass (-loop-unswitch) has had several bugs - fixed, has several new features, and is enabled by default in llvmgcc3 - now.
            • -
            • The Loop Strength Reduction pass (-loop-reduce) is now enabled for - the X86 and Alpha backends.
            • -
            • The Instruction Combining pass (-instcombine) now includes a - framework and implementation for simplifying code based on whether computed - bits are demanded or not.
            • -
            • The Scalar Replacement of Aggregates pass (-scalarrepl) can now - promote simple unions to registers.
            • -
            • The Reassociation pass (-reassociate) can now - factor expressions, e.g. turning "A*A+A*B" into "A*(A+B)".
            • -
            • Several LLVM passes are significantly -faster.
            • -
            -
            - - +

            This release includes many other improvements, including improvements to + the optimizers and code generators (improving the generated code) changes to + speed up the compiler in many ways (improving algorithms and fine tuning + code), and changes to reduce the code size of the compiler itself.

            + +

            More specific changes include:

            + +
              +
            • LLVM 1.8 includes an initial ARM backend. This backend is in early + development stages.
            • +
            • LLVM 1.8 now includes significantly better support for mingw and + cygwin.
            • +
            • The llvm-config tool is + now built by default and has several new features.
            • +
            • The X86 and PPC backends now use the correct platform ABI for passing + vectors as arguments to functions.
            • +
            • The X86 backend now includes support for the Microsoft ML assembler + ("MASM").
            • +
            • The PowerPC backend now pattern matches the 'rlwimi' instruction more + aggressively.
            • +
            • Most of LLVM is now built with "-pedantic", ensuring better portability + to more C++ Compilers.
            • +
            • The PowerPC backend now includes initial 64-bit support. The JIT is not + complete, and the static compiler has a couple of known bugs, but support + is mostly in place. LLVM 1.9 will include completed PPC-64 support.
            • -
              -
                -
              • LLVM has a new prepass (before register allocation) list scheduler, which - supports bottom-up and top-down scheduling, pluggable priority functions and - pluggable hazard recognizers. The X86 backend uses this to reduce register - pressure and RISC targets schedule based on operation latency.
              • -
              • The tblgen-based target description framework introduced in LLVM 1.6 has - several new features, useful for targets that can fold loads and stores into - operations, and features that make the .td files more expressive.
              • -
              • The instruction selector is significantly faster in 1.7 than in 1.6.
              • -
              • The X86, Alpha and Itanium backends use new DAG-DAG instruction selectors, - making them easier to maintain and generate slightly better code.
              • -
              • The X86 backend now supports generation of Scalar SSE code for scalar FP - expressions. LLVM provides significantly better performance with Scalar SSE - instructions than it does with the Intel floating point stack - instructions.
              • -
              • The Itanium backend now has a bundling pass, which improves performance - by ~10% and reduces code size (previously it unconditionally inserted a stop - bit after every instruction).
              - - - -
              -
                -
              • The Mac OS/X PowerPC and X86 backends now have initial support for - Darwin DWARF - debugging information, however, debug info generation has been disabled for - the 1.7 release in llvmgcc4.
              • -
              • LLVM includes the new - llvm-config utility, which makes it easier to build and link programs - against the LLVM libraries when not using the LLVM makefiles.
              • -
              • LLVM now supports first class global ctor/dtor initialization lists, no - longer forcing targets to use "__main".
              • -
              • LLVM supports assigning globals and functions to a particular section - in the result executable using the GCC section attribute.
              • -
              • Adding intrinsics to LLVM is now - significantly easier.
              • -
              • llvmgcc4 now fully supports C99 Variable Length Arrays, including dynamic - stack deallocation.
              • - -
              -
              - -
                -
              • The official LLVM URL is now - http://llvm.org/.
              • -
              • The LLVM intrinsics used to be overloaded based on type: for example, - llvm.ctpop could work with any - integer datatype. They are now separated into different intrinsics with - suffixes to denote their argument type (e.g. llvm.ctpop.i32)). Old - LLVM .ll and .bc files that use these intrinsics will continue to work with - new LLVM versions (they are transparently upgraded by the parsers), but will - cause a warning to be emitted.
              • -
              • The llvm.readport, llvm.writeport, llvm.readio, - and llvm.writeio intrinsics have been removed. The first two - were ever only supported by the X86 backend, the last two were never - correctly supported by any target, and none were accessible through the - C front-end. Inline assembly support can now be used to - implement these operations.
              • -
              • The llvm-db tool had basic support for stepping through code, which - used the JIT. This code has been removed, and DWARF emission support added - instead. llvm-db still exists in CVS if someone wanted to write a - ptrace backend for it.
              • +
              • The LLVM "SparcV9" backend (deprecated in LLVM 1.7) has been removed in +LLVM 1.8. The LLVM "Sparc" backend replaces it.
              • +
              • The --version option now prints more useful information, including the + build configuration for the tool.
              @@ -289,6 +204,7 @@
              • Intel and AMD machines running Red Hat Linux, Fedora Core and FreeBSD (and probably other unix-like systems).
              • +
              • Intel and AMD machines running on Win32 using MinGW libraries (native)
              • Sun UltraSPARC workstations running Solaris 8.
              • Intel and AMD machines running on Win32 with the Cygwin libraries (limited support is available for native builds with Visual C++).
              • @@ -332,7 +248,7 @@ be broken or unreliable, or are in early development. These components should not be relied on, and bugs should not be filed against them, but they may be useful to some people. In particular, if you would like to work on one of these -components, please contact us on the llvmdev list.

                +components, please contact us on the LLVMdev list.

                • The -cee pass is known to be buggy, and may be removed in in a @@ -382,8 +298,7 @@

                  -llvm-gcc3 has many significant problems that are fixed by llvm-gcc4. See - those blocked on the llvm-gcc4 meta bug. +llvm-gcc3 has many significant problems that are fixed by llvm-gcc4. Two major ones include:

                    @@ -401,6 +316,11 @@ href="http://llvm.org/PR162">with the largest union member.
                  + +

                  llvm-gcc4 is far more stable and produces better code than llvm-gcc3, but +does not currently support Link-Time-Optimization or C++ Exception Handling, +which llvm-gcc3 does.

                  +
                  @@ -638,8 +558,7 @@ @@ -718,19 +637,16 @@
            -
            @@ -768,7 +684,7 @@ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /> The LLVM Compiler Infrastructure
            - Last modified: $Date: 2006/04/20 04:24:28 $ + Last modified: $Date: 2006/08/09 04:31:39 $ From tbrethou at cs.uiuc.edu Tue Aug 8 23:32:22 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Tue, 8 Aug 2006 23:32:22 -0500 Subject: [llvm-commits] [release_18] CVS: llvm/runtime/GCCLibraries/libc/LICENSE.TXT qsort.c remove.c Message-ID: <200608090432.k794WMH3024504@zion.cs.uiuc.edu> Changes in directory llvm/runtime/GCCLibraries/libc: LICENSE.TXT updated: 1.2.22.1 -> 1.2.22.2 qsort.c updated: 1.2 -> 1.2.32.1 remove.c updated: 1.1 -> 1.1.4.1 --- Log message: Merge from mainline --- Diffs of the changes: (+25 -1) LICENSE.TXT | 9 +++++++++ qsort.c | 10 ++++++++++ remove.c | 7 ++++++- 3 files changed, 25 insertions(+), 1 deletion(-) Index: llvm/runtime/GCCLibraries/libc/LICENSE.TXT diff -u llvm/runtime/GCCLibraries/libc/LICENSE.TXT:1.2.22.1 llvm/runtime/GCCLibraries/libc/LICENSE.TXT:1.2.22.2 --- llvm/runtime/GCCLibraries/libc/LICENSE.TXT:1.2.22.1 Fri Jul 28 13:40:05 2006 +++ llvm/runtime/GCCLibraries/libc/LICENSE.TXT Tue Aug 8 23:32:10 2006 @@ -6,3 +6,12 @@ Portions of glibc also contain copyrights and licenses from third parties. Those are listed in LICENSES. + +FSF copyright and warranty disclaimer: +Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc. +Copyright (C) 1995,96,97,2002 Free Software Foundation, Inc. + +The GNU C Library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. Index: llvm/runtime/GCCLibraries/libc/qsort.c diff -u llvm/runtime/GCCLibraries/libc/qsort.c:1.2 llvm/runtime/GCCLibraries/libc/qsort.c:1.2.32.1 --- llvm/runtime/GCCLibraries/libc/qsort.c:1.2 Thu May 29 17:12:35 2003 +++ llvm/runtime/GCCLibraries/libc/qsort.c Tue Aug 8 23:32:10 2006 @@ -1,3 +1,13 @@ +//===-- qsort.c - The qsort function for the LLVM libc Library ----*- C -*-===// +// +// This code is a modified form of the qsort() function from the GNU C +// library. +// +// Modifications: +// 2003/05/29 - Code disabled for compilation. Line wrapping changed. +// +//===----------------------------------------------------------------------===// + /* Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc. This file is part of the GNU C Library. Written by Douglas C. Schmidt (schmidt at ics.uci.edu). Index: llvm/runtime/GCCLibraries/libc/remove.c diff -u llvm/runtime/GCCLibraries/libc/remove.c:1.1 llvm/runtime/GCCLibraries/libc/remove.c:1.1.4.1 --- llvm/runtime/GCCLibraries/libc/remove.c:1.1 Mon Nov 28 09:49:15 2005 +++ llvm/runtime/GCCLibraries/libc/remove.c Tue Aug 8 23:32:10 2006 @@ -1,6 +1,11 @@ //===-- remove.c - The remove function for the LLVM libc Library --*- C -*-===// // -// A lot of this code is ripped gratuitously from glibc and libiberty. +// This code is a modified form of the remove() function from the GNU C +// library. +// +// Modifications: +// 2005/11/28 - Added to LLVM tree. Functions renamed to allow compilation. +// Code to control symbol linkage types removed. // //===----------------------------------------------------------------------===// From tbrethou at cs.uiuc.edu Wed Aug 9 00:18:24 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:18:24 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/ Message-ID: <200608090518.k795IO9V025225@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8: --- Log message: Directory /var/cvs/llvm/llvm-www/releases/1.8 added to the repository --- Diffs of the changes: (+0 -0) 0 files changed From evan.cheng at apple.com Wed Aug 9 00:39:08 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Wed, 9 Aug 2006 00:39:08 -0500 Subject: [llvm-commits] CVS: llvm/autoconf/m4/libtool.m4 Message-ID: <200608090539.k795d8ND025661@zion.cs.uiuc.edu> Changes in directory llvm/autoconf/m4: libtool.m4 updated: 1.7 -> 1.8 --- Log message: Recover the lost diff between 1.5 and 1.6. --- Diffs of the changes: (+1 -1) libtool.m4 | 2 +- 1 files changed, 1 insertion(+), 1 deletion(-) Index: llvm/autoconf/m4/libtool.m4 diff -u llvm/autoconf/m4/libtool.m4:1.7 llvm/autoconf/m4/libtool.m4:1.8 --- llvm/autoconf/m4/libtool.m4:1.7 Fri Aug 4 13:18:08 2006 +++ llvm/autoconf/m4/libtool.m4 Wed Aug 9 00:38:51 2006 @@ -2234,7 +2234,7 @@ case $host_os in darwin*) if test "$GCC" = yes; then - reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' + reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r $compiler_flags -o $output$reload_objs' else reload_cmds='$LD$reload_flag -o $output$reload_objs' fi From evan.cheng at apple.com Wed Aug 9 00:40:29 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Wed, 9 Aug 2006 00:40:29 -0500 Subject: [llvm-commits] CVS: llvm/configure Message-ID: <200608090540.k795eTnP025705@zion.cs.uiuc.edu> Changes in directory llvm: configure updated: 1.245 -> 1.246 --- Log message: Recover the lost diff between 1.221 and 1.222. --- Diffs of the changes: (+1 -1) configure | 2 +- 1 files changed, 1 insertion(+), 1 deletion(-) Index: llvm/configure diff -u llvm/configure:1.245 llvm/configure:1.246 --- llvm/configure:1.245 Fri Aug 4 13:18:07 2006 +++ llvm/configure Wed Aug 9 00:40:14 2006 @@ -12218,7 +12218,7 @@ case $host_os in darwin*) if test "$GCC" = yes; then - reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' + reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r $compiler_flags -o $output$reload_objs' else reload_cmds='$LD$reload_flag -o $output$reload_objs' fi From evan.cheng at apple.com Wed Aug 9 00:45:26 2006 From: evan.cheng at apple.com (Evan Cheng) Date: Wed, 9 Aug 2006 00:45:26 -0500 Subject: [llvm-commits] CVS: llvm/utils/NewNightlyTest.pl Message-ID: <200608090545.k795jQri025795@zion.cs.uiuc.edu> Changes in directory llvm/utils: NewNightlyTest.pl updated: 1.46 -> 1.47 --- Log message: Merge some NightlyTest.pl changes. --- Diffs of the changes: (+5 -1) NewNightlyTest.pl | 6 +++++- 1 files changed, 5 insertions(+), 1 deletion(-) Index: llvm/utils/NewNightlyTest.pl diff -u llvm/utils/NewNightlyTest.pl:1.46 llvm/utils/NewNightlyTest.pl:1.47 --- llvm/utils/NewNightlyTest.pl:1.46 Mon Aug 7 21:03:53 2006 +++ llvm/utils/NewNightlyTest.pl Wed Aug 9 00:45:12 2006 @@ -132,6 +132,7 @@ $CONFIGUREARGS .= " --disable-llc_diffs"; next; } if (/^-disable-jit$/) { $PROGTESTOPTS .= " DISABLE_JIT=1"; $CONFIGUREARGS .= " --disable-jit"; next; } + if (/^-disable-cbe$/) { $PROGTESTOPTS .= " DISABLE_CBE=1"; next; } if (/^-verbose$/) { $VERBOSE = 1; next; } if (/^-debug$/) { $DEBUG = 1; next; } if (/^-nice$/) { $NICE = "nice "; next; } @@ -168,8 +169,11 @@ if (/^-use-gmake/) { $MAKECMD = "gmake"; shift; next; } + if (/^-compileflags/) { + $MAKEOPTS = "$MAKEOPTS $ARGV[0]"; shift; next; + } if (/^-extraflags/) { - $PROGTESTOPTS .= " EXTRA_FLAGS=\'$ARGV[0]\'"; shift; next; + $CONFIGUREARGS .= " --with-extra-options=\'$ARGV[0]\'"; shift; next; } if (/^-noexternals$/) { $NOEXTERNALS = 1; next; } if (/^-nodejagnu$/) { $NODEJAGNU = 1; next; } From tbrethou at cs.uiuc.edu Wed Aug 9 00:50:20 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:50:20 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/download.html Message-ID: <200608090550.k795oKus025893@zion.cs.uiuc.edu> Changes in directory llvm-www/releases: download.html updated: 1.31 -> 1.32 --- Log message: Adding 1.8 release --- Diffs of the changes: (+67 -0) download.html | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 67 insertions(+) Index: llvm-www/releases/download.html diff -u llvm-www/releases/download.html:1.31 llvm-www/releases/download.html:1.32 --- llvm-www/releases/download.html:1.31 Fri Jun 30 10:15:42 2006 +++ llvm-www/releases/download.html Wed Aug 9 00:50:08 2006 @@ -30,6 +30,73 @@
            + +
            Download LLVM 1.8
            + + + + + + +
            Download LLVM 1.8
            + + + +
            Download LLVM 1.7
            + + + + +
            Download LLVM 1.7
            From tbrethou at cs.uiuc.edu Wed Aug 9 00:51:33 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:51:33 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/download.html Message-ID: <200608090551.k795pXVd025931@zion.cs.uiuc.edu> Changes in directory llvm-www/releases: download.html updated: 1.32 -> 1.33 --- Log message: Fixing copy error. --- Diffs of the changes: (+0 -41) download.html | 41 ----------------------------------------- 1 files changed, 41 deletions(-) Index: llvm-www/releases/download.html diff -u llvm-www/releases/download.html:1.32 llvm-www/releases/download.html:1.33 --- llvm-www/releases/download.html:1.32 Wed Aug 9 00:50:08 2006 +++ llvm-www/releases/download.html Wed Aug 9 00:51:20 2006 @@ -55,47 +55,6 @@
      - - - -
      Download LLVM 1.8
      - - - -
      Download LLVM 1.7
      - - - -
      Download LLVM 1.7
      From tbrethou at cs.uiuc.edu Wed Aug 9 00:52:12 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:52:12 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/ Message-ID: <200608090552.k795qCfl025964@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs: --- Log message: Directory /var/cvs/llvm/llvm-www/releases/1.8/docs added to the repository --- Diffs of the changes: (+0 -0) 0 files changed From tbrethou at cs.uiuc.edu Wed Aug 9 00:52:50 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:52:50 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/LICENSE.TXT cfrontend-1.8.i686-redhat-linux-gnu.tar.gz cfrontend-1.8.powerpc-apple-darwin8.5.0.tar.gz cfrontend-1.8.source.tar.gz llvm-1.8.tar.gz llvm-gcc4-1.8-ppc-darwin.tar.gz llvm-gcc4-1.8-source.tar.gz llvm-gcc4-1.8-x86-darwin.tar.gz llvm-gcc4-1.8-x86-linux.tar.gz llvm-gcc4-1.8-x86-mingw32.tar.bz2 llvm-gcc4-freebsd6.tar.bz2 llvm-test-1.8.tar.gz Message-ID: <200608090552.k795qohv026016@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8: LICENSE.TXT added (r1.1) cfrontend-1.8.i686-redhat-linux-gnu.tar.gz added (r1.1) cfrontend-1.8.powerpc-apple-darwin8.5.0.tar.gz added (r1.1) cfrontend-1.8.source.tar.gz added (r1.1) llvm-1.8.tar.gz added (r1.1) llvm-gcc4-1.8-ppc-darwin.tar.gz added (r1.1) llvm-gcc4-1.8-source.tar.gz added (r1.1) llvm-gcc4-1.8-x86-darwin.tar.gz added (r1.1) llvm-gcc4-1.8-x86-linux.tar.gz added (r1.1) llvm-gcc4-1.8-x86-mingw32.tar.bz2 added (r1.1) llvm-gcc4-freebsd6.tar.bz2 added (r1.1) llvm-test-1.8.tar.gz added (r1.1) --- Log message: 1.8 release --- Diffs of the changes: (+72 -0) LICENSE.TXT | 72 +++++++++++++++++++++++++ cfrontend-1.8.i686-redhat-linux-gnu.tar.gz | 0 cfrontend-1.8.powerpc-apple-darwin8.5.0.tar.gz | 0 cfrontend-1.8.source.tar.gz | 0 llvm-1.8.tar.gz | 0 llvm-gcc4-1.8-ppc-darwin.tar.gz | 0 llvm-gcc4-1.8-source.tar.gz | 0 llvm-gcc4-1.8-x86-darwin.tar.gz | 0 llvm-gcc4-1.8-x86-linux.tar.gz | 0 llvm-gcc4-1.8-x86-mingw32.tar.bz2 | 0 llvm-gcc4-freebsd6.tar.bz2 | 0 llvm-test-1.8.tar.gz | 0 12 files changed, 72 insertions(+) Index: llvm-www/releases/1.8/LICENSE.TXT diff -c /dev/null llvm-www/releases/1.8/LICENSE.TXT:1.1 *** /dev/null Wed Aug 9 00:52:45 2006 --- llvm-www/releases/1.8/LICENSE.TXT Wed Aug 9 00:52:22 2006 *************** *** 0 **** --- 1,72 ---- + ============================================================================== + LLVM Release License + ============================================================================== + University of Illinois/NCSA + Open Source License + + Copyright (c) 2003, 2004, 2005, 2006 University of Illinois at Urbana-Champaign. + All rights reserved. + + Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal with + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE + SOFTWARE. + + ============================================================================== + Copyrights and Licenses for Third Party Software Distributed with LLVM: + ============================================================================== + The LLVM software contains code written by third parties. Such software will + have its own individual LICENSE.TXT file in the directory in which it appears. + This file will describe the copyrights, license, and restrictions which apply + to that code. + + The disclaimer of warranty in the University of Illinois Open Source License + applies to all code in the LLVM Distribution, and nothing in any of the + other licenses gives permission to use the names of the LLVM Team or the + University of Illinois to endorse or promote products derived from this + Software. + + The following pieces of software have additional or alternate copyrights, + licenses, and/or restrictions: + + Program Directory + ------- --------- + System Library llvm/lib/System + Compiler Driver llvm/tools/llvmc + PowerPC Backend llvm/lib/Target/PowerPC + bzip2 llvm/lib/Support/bzip2/LICENSE + Autoconf llvm/autoconf + llvm/projects/ModuleMaker/autoconf + llvm/projects/sample/autoconf + Burg llvm/utils/Burg + GNU Libc llvm/runtime/GCCLibraries/libc Index: llvm-www/releases/1.8/cfrontend-1.8.i686-redhat-linux-gnu.tar.gz Index: llvm-www/releases/1.8/cfrontend-1.8.powerpc-apple-darwin8.5.0.tar.gz Index: llvm-www/releases/1.8/cfrontend-1.8.source.tar.gz Index: llvm-www/releases/1.8/llvm-1.8.tar.gz Index: llvm-www/releases/1.8/llvm-gcc4-1.8-ppc-darwin.tar.gz Index: llvm-www/releases/1.8/llvm-gcc4-1.8-source.tar.gz Index: llvm-www/releases/1.8/llvm-gcc4-1.8-x86-darwin.tar.gz Index: llvm-www/releases/1.8/llvm-gcc4-1.8-x86-linux.tar.gz Index: llvm-www/releases/1.8/llvm-gcc4-1.8-x86-mingw32.tar.bz2 Index: llvm-www/releases/1.8/llvm-gcc4-freebsd6.tar.bz2 Index: llvm-www/releases/1.8/llvm-test-1.8.tar.gz From tbrethou at cs.uiuc.edu Wed Aug 9 00:55:10 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:55:10 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/download.html Message-ID: <200608090555.k795tAfk026079@zion.cs.uiuc.edu> Changes in directory llvm-www/releases: download.html updated: 1.33 -> 1.34 --- Log message: Fixing broken link --- Diffs of the changes: (+1 -1) download.html | 2 +- 1 files changed, 1 insertion(+), 1 deletion(-) Index: llvm-www/releases/download.html diff -u llvm-www/releases/download.html:1.33 llvm-www/releases/download.html:1.34 --- llvm-www/releases/download.html:1.33 Wed Aug 9 00:51:20 2006 +++ llvm-www/releases/download.html Wed Aug 9 00:54:57 2006 @@ -49,7 +49,7 @@
    3. GCC 4 Front End Binaries for Linux/x86 (28.0M)
    4. GCC 4 Front End Binaries for Mingw32/x86 (15.1M)
    5. GCC 4 Front End Binaries for FreeBSD6/x86 (23.4M)
    6. -
    7. GCC 4 Front End Source Code (43.7M)
    8. +
    9. GCC 4 Front End Source Code (43.7M)
    10. From tbrethou at cs.uiuc.edu Wed Aug 9 00:56:06 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:56:06 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/CommandGuide/ Message-ID: <200608090556.k795u64l026143@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs/CommandGuide: --- Log message: Directory /var/cvs/llvm/llvm-www/releases/1.8/docs/CommandGuide added to the repository --- Diffs of the changes: (+0 -0) 0 files changed From tbrethou at cs.uiuc.edu Wed Aug 9 00:56:06 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:56:06 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/HistoricalNotes/ Message-ID: <200608090556.k795u6IO026146@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs/HistoricalNotes: --- Log message: Directory /var/cvs/llvm/llvm-www/releases/1.8/docs/HistoricalNotes added to the repository --- Diffs of the changes: (+0 -0) 0 files changed From tbrethou at cs.uiuc.edu Wed Aug 9 00:56:06 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:56:06 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/img/ Message-ID: <200608090556.k795u60p026149@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs/img: --- Log message: Directory /var/cvs/llvm/llvm-www/releases/1.8/docs/img added to the repository --- Diffs of the changes: (+0 -0) 0 files changed From tbrethou at cs.uiuc.edu Wed Aug 9 00:56:53 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:56:53 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/AliasAnalysis.html Bugpoint.html BytecodeFormat.html CFEBuildInstrs.html CodeGenerator.html CodingStandards.html CommandLine.html CompilerDriver.html CompilerWriterInfo.html ExtendingLLVM.html FAQ.html GarbageCollection.html GettingStarted.html GettingStartedVS.html HowToReleaseLLVM.html HowToSubmitABug.html LangRef.html Lexicon.html Makefile MakefileGuide.html ProgrammersManual.html Projects.html ReleaseNotes.html SourceLevelDebugging.html Stacker.html SystemLibrary.html TableGenFundamentals.html TestingGuide.html UsingLibraries.html WritingAnLLVMBackend.html WritingAnLLVMPass.html doxygen.cfg.in doxygen.css doxygen.footer doxygen.header doxygen.intro index.html llvm.css Message-ID: <200608090556.k795ur1c026258@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs: AliasAnalysis.html added (r1.1) Bugpoint.html added (r1.1) BytecodeFormat.html added (r1.1) CFEBuildInstrs.html added (r1.1) CodeGenerator.html added (r1.1) CodingStandards.html added (r1.1) CommandLine.html added (r1.1) CompilerDriver.html added (r1.1) CompilerWriterInfo.html added (r1.1) ExtendingLLVM.html added (r1.1) FAQ.html added (r1.1) GarbageCollection.html added (r1.1) GettingStarted.html added (r1.1) GettingStartedVS.html added (r1.1) HowToReleaseLLVM.html added (r1.1) HowToSubmitABug.html added (r1.1) LangRef.html added (r1.1) Lexicon.html added (r1.1) Makefile added (r1.1) MakefileGuide.html added (r1.1) ProgrammersManual.html added (r1.1) Projects.html added (r1.1) ReleaseNotes.html added (r1.1) SourceLevelDebugging.html added (r1.1) Stacker.html added (r1.1) SystemLibrary.html added (r1.1) TableGenFundamentals.html added (r1.1) TestingGuide.html added (r1.1) UsingLibraries.html added (r1.1) WritingAnLLVMBackend.html added (r1.1) WritingAnLLVMPass.html added (r1.1) doxygen.cfg.in added (r1.1) doxygen.css added (r1.1) doxygen.footer added (r1.1) doxygen.header added (r1.1) doxygen.intro added (r1.1) index.html added (r1.1) llvm.css added (r1.1) --- Log message: Adding 1.8 docs --- Diffs of the changes: (+30599 -0) AliasAnalysis.html | 959 +++++++++++ Bugpoint.html | 238 ++ BytecodeFormat.html | 2154 +++++++++++++++++++++++++ CFEBuildInstrs.html | 364 ++++ CodeGenerator.html | 1293 +++++++++++++++ CodingStandards.html | 679 ++++++++ CommandLine.html | 1930 +++++++++++++++++++++++ CompilerDriver.html | 823 +++++++++ CompilerWriterInfo.html | 260 +++ ExtendingLLVM.html | 389 ++++ FAQ.html | 678 ++++++++ GarbageCollection.html | 533 ++++++ GettingStarted.html | 1601 +++++++++++++++++++ GettingStartedVS.html | 353 ++++ HowToReleaseLLVM.html | 474 +++++ HowToSubmitABug.html | 359 ++++ LangRef.html | 3846 ++++++++++++++++++++++++++++++++++++++++++++++ Lexicon.html | 178 ++ Makefile | 83 MakefileGuide.html | 1010 ++++++++++++ ProgrammersManual.html | 2288 +++++++++++++++++++++++++++ Projects.html | 460 +++++ ReleaseNotes.html | 691 ++++++++ SourceLevelDebugging.html | 1762 +++++++++++++++++++++ Stacker.html | 1412 ++++++++++++++++ SystemLibrary.html | 344 ++++ TableGenFundamentals.html | 567 ++++++ TestingGuide.html | 620 +++++++ UsingLibraries.html | 398 ++++ WritingAnLLVMBackend.html | 260 +++ WritingAnLLVMPass.html | 1600 +++++++++++++++++++ doxygen.cfg.in | 1230 ++++++++++++++ doxygen.css | 378 ++++ doxygen.footer | 9 doxygen.header | 9 doxygen.intro | 18 index.html | 265 +++ llvm.css | 84 + 38 files changed, 30599 insertions(+) Index: llvm-www/releases/1.8/docs/AliasAnalysis.html diff -c /dev/null llvm-www/releases/1.8/docs/AliasAnalysis.html:1.1 *** /dev/null Wed Aug 9 00:56:50 2006 --- llvm-www/releases/1.8/docs/AliasAnalysis.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,959 ---- + + + + LLVM Alias Analysis Infrastructure + + + + +
      + LLVM Alias Analysis Infrastructure +
      + +
        +
      1. Introduction
      2. + +
      3. AliasAnalysis Class Overview + +
      4. + +
      5. Writing a new AliasAnalysis Implementation + +
      6. + +
      7. Using alias analysis results + +
      8. + +
      9. Existing alias analysis implementations and clients + +
      10. +
      + +
      +

      Written by Chris Lattner

      +
      + + + + + +
      + +

      Alias Analysis (aka Pointer Analysis) is a class of techniques which attempt + to determine whether or not two pointers ever can point to the same object in + memory. There are many different algorithms for alias analysis and many + different ways of classifying them: flow-sensitive vs flow-insensitive, + context-sensitive vs context-insensitive, field-sensitive vs field-insensitive, + unification-based vs subset-based, etc. Traditionally, alias analyses respond + to a query with a Must, May, or No alias response, + indicating that two pointers always point to the same object, might point to the + same object, or are known to never point to the same object.

      + +

      The LLVM AliasAnalysis + class is the primary interface used by clients and implementations of alias + analyses in the LLVM system. This class is the common interface between clients + of alias analysis information and the implementations providing it, and is + designed to support a wide range of implementations and clients (but currently + all clients are assumed to be flow-insensitive). In addition to simple alias + analysis information, this class exposes Mod/Ref information from those + implementations which can provide it, allowing for powerful analyses and + transformations to work well together.

      + +

      This document contains information necessary to successfully implement this + interface, use it, and to test both sides. It also explains some of the finer + points about what exactly results mean. If you feel that something is unclear + or should be added, please let me + know.

      + +
      + + + + + +
      + +

      The AliasAnalysis + class defines the interface that the various alias analysis implementations + should support. This class exports two important enums: AliasResult + and ModRefResult which represent the result of an alias query or a + mod/ref query, respectively.

      + +

      The AliasAnalysis interface exposes information about memory, + represented in several different ways. In particular, memory objects are + represented as a starting address and size, and function calls are represented + as the actual call or invoke instructions that performs the + call. The AliasAnalysis interface also exposes some helper methods + which allow you to get mod/ref information for arbitrary instructions.

      + +
      + + + + +
      + +

      Most importantly, the AliasAnalysis class provides several methods + which are used to query whether or not two memory objects alias, whether + function calls can modify or read a memory object, etc. For all of these + queries, memory objects are represented as a pair of their starting address (a + symbolic LLVM Value*) and a static size.

      + +

      Representing memory objects as a starting address and a size is critically + important for correct Alias Analyses. For example, consider this (silly, but + possible) C code:

      + +
      +
      + int i;
      + char C[2];
      + char A[10]; 
      + /* ... */
      + for (i = 0; i != 10; ++i) {
      +   C[0] = A[i];          /* One byte store */
      +   C[1] = A[9-i];        /* One byte store */
      + }
      + 
      +
      + +

      In this case, the basicaa pass will disambiguate the stores to + C[0] and C[1] because they are accesses to two distinct + locations one byte apart, and the accesses are each one byte. In this case, the + LICM pass can use store motion to remove the stores from the loop. In + constrast, the following code:

      + +
      +
      + int i;
      + char C[2];
      + char A[10]; 
      + /* ... */
      + for (i = 0; i != 10; ++i) {
      +   ((short*)C)[0] = A[i];  /* Two byte store! */
      +   C[1] = A[9-i];          /* One byte store */
      + }
      + 
      +
      + +

      In this case, the two stores to C do alias each other, because the access to + the &C[0] element is a two byte access. If size information wasn't + available in the query, even the first case would have to conservatively assume + that the accesses alias.

      + +
      + + + + +
      + The alias method is the primary interface used to determine whether or + not two memory objects alias each other. It takes two memory objects as input + and returns MustAlias, MayAlias, or NoAlias as appropriate. +
      + + + + +
      + +

      An Alias Analysis implementation can return one of three responses: + MustAlias, MayAlias, and NoAlias. The No and May alias results are obvious: if + the two pointers can never equal each other, return NoAlias, if they might, + return MayAlias.

      + +

      The MustAlias response is trickier though. In LLVM, the Must Alias response + may only be returned if the two memory objects are guaranteed to always start at + exactly the same location. If two memory objects overlap, but do not start at + the same location, return MayAlias.

      + +
      + + + + +
      + +

      The getModRefInfo methods return information about whether the + execution of an instruction can read or modify a memory location. Mod/Ref + information is always conservative: if an instruction might read or write + a location, ModRef is returned.

      + +

      The AliasAnalysis class also provides a getModRefInfo + method for testing dependencies between function calls. This method takes two + call sites (CS1 & CS2), returns NoModRef if the two calls refer to disjoint + memory locations, Ref if CS1 reads memory written by CS2, Mod if CS1 writes to + memory read or written by CS2, or ModRef if CS1 might read or write memory + accessed by CS2. Note that this relation is not commutative. Clients that use + this method should be predicated on the hasNoModRefInfoForCalls() + method, which indicates whether or not an analysis can provide mod/ref + information for function call pairs (most can not). If this predicate is false, + the client shouldn't waste analysis time querying the getModRefInfo + method many times.

      + +
      + + + + + +
      + +

      + Several other tidbits of information are often collected by various alias + analysis implementations and can be put to good use by various clients. +

      + +
      + + +
      + The getMustAliases method +
      + +
      + +

      The getMustAliases method returns all values that are known to + always must alias a pointer. This information can be provided in some cases for + important objects like the null pointer and global values. Knowing that a + pointer always points to a particular function allows indirect calls to be + turned into direct calls, for example.

      + +
      + + +
      + The pointsToConstantMemory method +
      + +
      + +

      The pointsToConstantMemory method returns true if and only if the + analysis can prove that the pointer only points to unchanging memory locations + (functions, constant global variables, and the null pointer). This information + can be used to refine mod/ref information: it is impossible for an unchanging + memory location to be modified.

      + +
      + + + + +
      + +

      These methods are used to provide very simple mod/ref information for + function calls. The doesNotAccessMemory method returns true for a + function if the analysis can prove that the function never reads or writes to + memory, or if the function only reads from constant memory. Functions with this + property are side-effect free and only depend on their input arguments, allowing + them to be eliminated if they form common subexpressions or be hoisted out of + loops. Many common functions behave this way (e.g., sin and + cos) but many others do not (e.g., acos, which modifies the + errno variable).

      + +

      The onlyReadsMemory method returns true for a function if analysis + can prove that (at most) the function only reads from non-volatile memory. + Functions with this property are side-effect free, only depending on their input + arguments and the state of memory when they are called. This property allows + calls to these functions to be eliminated and moved around, as long as there is + no store instruction that changes the contents of memory. Note that all + functions that satisfy the doesNotAccessMemory method also satisfies + onlyReadsMemory.

      + +
      + + + + + +
      + +

      Writing a new alias analysis implementation for LLVM is quite + straight-forward. There are already several implementations that you can use + for examples, and the following information should help fill in any details. + For a examples, take a look at the various alias analysis + implementations included with LLVM.

      + +
      + + + + +
      + +

      The first step to determining what type of LLVM pass you need to use for your Alias + Analysis. As is the case with most other analyses and transformations, the + answer should be fairly obvious from what type of problem you are trying to + solve:

      + +
        +
      1. If you require interprocedural analysis, it should be a + Pass.
      2. +
      3. If you are a function-local analysis, subclass FunctionPass.
      4. +
      5. If you don't need to look at the program at all, subclass + ImmutablePass.
      6. +
      + +

      In addition to the pass that you subclass, you should also inherit from the + AliasAnalysis interface, of course, and use the + RegisterAnalysisGroup template to register as an implementation of + AliasAnalysis.

      + +
      + + + + +
      + +

      Your subclass of AliasAnalysis is required to invoke two methods on + the AliasAnalysis base class: getAnalysisUsage and + InitializeAliasAnalysis. In particular, your implementation of + getAnalysisUsage should explicitly call into the + AliasAnalysis::getAnalysisUsage method in addition to doing any + declaring any pass dependencies your pass has. Thus you should have something + like this:

      + +
      +
      + void getAnalysisUsage(AnalysisUsage &AU) const {
      +   AliasAnalysis::getAnalysisUsage(AU);
      +   // declare your dependencies here.
      + }
      + 
      +
      + +

      Additionally, your must invoke the InitializeAliasAnalysis method + from your analysis run method (run for a Pass, + runOnFunction for a FunctionPass, or InitializePass + for an ImmutablePass). For example (as part of a Pass):

      + +
      +
      + bool run(Module &M) {
      +   InitializeAliasAnalysis(this);
      +   // Perform analysis here...
      +   return false;
      + }
      + 
      +
      + +
      + + + + +
      + +

      All of the AliasAnalysis + virtual methods default to providing chaining to another + alias analysis implementation, which ends up returning conservatively correct + information (returning "May" Alias and "Mod/Ref" for alias and mod/ref queries + respectively). Depending on the capabilities of the analysis you are + implementing, you just override the interfaces you can improve.

      + +
      + + + + + + +
      + +

      With only two special exceptions (the basicaa and no-aa + passes) every alias analysis pass chains to another alias analysis + implementation (for example, the user can specify "-basicaa -ds-aa + -anders-aa -licm" to get the maximum benefit from the three alias + analyses). The alias analysis class automatically takes care of most of this + for methods that you don't override. For methods that you do override, in code + paths that return a conservative MayAlias or Mod/Ref result, simply return + whatever the superclass computes. For example:

      + +
      +
      + AliasAnalysis::AliasResult alias(const Value *V1, unsigned V1Size,
      +                                  const Value *V2, unsigned V2Size) {
      +   if (...)
      +     return NoAlias;
      +   ...
      + 
      +   // Couldn't determine a must or no-alias result.
      +   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
      + }
      + 
      +
      + +

      In addition to analysis queries, you must make sure to unconditionally pass + LLVM update notification methods to the superclass as + well if you override them, which allows all alias analyses in a change to be + updated.

      + +
      + + + + + +
      +

      + Alias analysis information is initially computed for a static snapshot of the + program, but clients will use this information to make transformations to the + code. All but the most trivial forms of alias analysis will need to have their + analysis results updated to reflect the changes made by these transformations. +

      + +

      + The AliasAnalysis interface exposes two methods which are used to + communicate program changes from the clients to the analysis implementations. + Various alias analysis implementations should use these methods to ensure that + their internal data structures are kept up-to-date as the program changes (for + example, when an instruction is deleted), and clients of alias analysis must be + sure to call these interfaces appropriately. +

      +
      + + +
      The deleteValue method
      + +
      + The deleteValue method is called by transformations when they remove an + instruction or any other value from the program (including values that do not + use pointers). Typically alias analyses keep data structures that have entries + for each value in the program. When this method is called, they should remove + any entries for the specified value, if they exist. +
      + + +
      The copyValue method
      + +
      + The copyValue method is used when a new value is introduced into the + program. There is no way to introduce a value into the program that did not + exist before (this doesn't make sense for a safe compiler transformation), so + this is the only way to introduce a new value. This method indicates that the + new value has exactly the same properties as the value being copied. +
      + + +
      The replaceWithNewValue method
      + +
      + This method is a simple helper method that is provided to make clients easier to + use. It is implemented by copying the old analysis information to the new + value, then deleting the old value. This method cannot be overridden by alias + analysis implementations. +
      + + + + +
      + +

      From the LLVM perspective, the only thing you need to do to provide an + efficient alias analysis is to make sure that alias analysis queries are + serviced quickly. The actual calculation of the alias analysis results (the + "run" method) is only performed once, but many (perhaps duplicate) queries may + be performed. Because of this, try to move as much computation to the run + method as possible (within reason).

      + +
      + + + + + +
      + +

      There are several different ways to use alias analysis results. In order of + preference, these are...

      + +
      + + + + +
      + +

      The load-vn pass uses alias analysis to provide value numbering + information for load instructions and pointer values. If your analysis + or transformation can be modeled in a form that uses value numbering + information, you don't have to do anything special to handle load instructions: + just use the load-vn pass, which uses alias analysis.

      + +
      + + + + +
      + +

      Many transformations need information about alias sets that are active + in some scope, rather than information about pairwise aliasing. The AliasSetTracker class + is used to efficiently build these Alias Sets from the pairwise alias analysis + information provided by the AliasAnalysis interface.

      + +

      First you initialize the AliasSetTracker by using the "add" methods + to add information about various potentially aliasing instructions in the scope + you are interested in. Once all of the alias sets are completed, your pass + should simply iterate through the constructed alias sets, using the + AliasSetTracker begin()/end() methods.

      + +

      The AliasSets formed by the AliasSetTracker are guaranteed + to be disjoint, calculate mod/ref information and volatility for the set, and + keep track of whether or not all of the pointers in the set are Must aliases. + The AliasSetTracker also makes sure that sets are properly folded due to call + instructions, and can provide a list of pointers in each set.

      + +

      As an example user of this, the Loop + Invariant Code Motion pass uses AliasSetTrackers to calculate alias + sets for each loop nest. If an AliasSet in a loop is not modified, + then all load instructions from that set may be hoisted out of the loop. If any + alias sets are stored to and are must alias sets, then the stores may be + sunk to outside of the loop, promoting the memory location to a register for the + duration of the loop nest. Both of these transformations only apply if the + pointer argument is loop-invariant.

      + +
      + + +
      + The AliasSetTracker implementation +
      + +
      + +

      The AliasSetTracker class is implemented to be as efficient as possible. It + uses the union-find algorithm to efficiently merge AliasSets when a pointer is + inserted into the AliasSetTracker that aliases multiple sets. The primary data + structure is a hash table mapping pointers to the AliasSet they are in.

      + +

      The AliasSetTracker class must maintain a list of all of the LLVM Value*'s + that are in each AliasSet. Since the hash table already has entries for each + LLVM Value* of interest, the AliasesSets thread the linked list through these + hash-table nodes to avoid having to allocate memory unnecessarily, and to make + merging alias sets extremely efficient (the linked list merge is constant time). +

      + +

      You shouldn't need to understand these details if you are just a client of + the AliasSetTracker, but if you look at the code, hopefully this brief + description will help make sense of why things are designed the way they + are.

      + +
      + + + + +
      + +

      If neither of these utility class are what your pass needs, you should use + the interfaces exposed by the AliasAnalysis class directly. Try to use + the higher-level methods when possible (e.g., use mod/ref information instead of + the alias method directly if possible) to get the + best precision and efficiency.

      + +
      + + + + + +
      + +

      If you're going to be working with the LLVM alias analysis infrastructure, + you should know what clients and implementations of alias analysis are + available. In particular, if you are implementing an alias analysis, you should + be aware of the the clients that are useful + for monitoring and evaluating different implementations.

      + +
      + + + + +
      + +

      This section lists the various implementations of the AliasAnalysis + interface. With the exception of the -no-aa and + -basicaa implementations, all of these chain to other alias analysis implementations.

      + +
      + + + + +
      + +

      The -no-aa pass is just like what it sounds: an alias analysis that + never returns any useful information. This pass can be useful if you think that + alias analysis is doing something wrong and are trying to narrow down a + problem.

      + +
      + + + + +
      + +

      The -basicaa pass is the default LLVM alias analysis. It is an + aggressive local analysis that "knows" many important facts:

      + +
        +
      • Distinct globals, stack allocations, and heap allocations can never + alias.
      • +
      • Globals, stack allocations, and heap allocations never alias the null + pointer.
      • +
      • Different fields of a structure do not alias.
      • +
      • Indexes into arrays with statically differing subscripts cannot alias.
      • +
      • Many common standard C library functions never access memory or only read memory.
      • +
      • Pointers that obviously point to constant globals + "pointToConstantMemory".
      • +
      • Function calls can not modify or references stack allocations if they never + escape from the function that allocates them (a common case for automatic + arrays).
      • +
      + +
      + + + + +
      + +

      This pass implements a simple context-sensitive mod/ref and alias analysis + for internal global variables that don't "have their address taken". If a + global does not have its address taken, the pass knows that no pointers alias + the global. This pass also keeps track of functions that it knows never access + memory or never read memory. This allows certain optimizations (e.g. GCSE) to + eliminate call instructions entirely. +

      + +

      The real power of this pass is that it provides context-sensitive mod/ref + information for call instructions. This allows the optimizer to know that + calls to a function do not clobber or read the value of the global, allowing + loads and stores to be eliminated.

      + +

      Note that this pass is somewhat limited in its scope (only support + non-address taken globals), but is very quick analysis.

      +
      + + + + +
      + +

      The -anders-aa pass implements the well-known "Andersen's algorithm" + for interprocedural alias analysis. This algorithm is a subset-based, + flow-insensitive, context-insensitive, and field-insensitive alias analysis that + is widely believed to be fairly precise. Unfortunately, this algorithm is also + O(N3). The LLVM implementation currently does not implement any of + the refinements (such as "online cycle elimination" or "offline variable + substitution") to improve its efficiency, so it can be quite slow in common + cases. +

      + +
      + + + + +
      + +

      The -steens-aa pass implements a variation on the well-known + "Steensgaard's algorithm" for interprocedural alias analysis. Steensgaard's + algorithm is a unification-based, flow-insensitive, context-insensitive, and + field-insensitive alias analysis that is also very scalable (effectively linear + time).

      + +

      The LLVM -steens-aa pass implements a "speculatively + field-sensitive" version of Steensgaard's algorithm using the Data + Structure Analysis framework. This gives it substantially more precision than + the standard algorithm while maintaining excellent analysis scalability.

      + +
      + + + + +
      + +

      The -ds-aa pass implements the full Data Structure Analysis + algorithm. Data Structure Analysis is a modular unification-based, + flow-insensitive, context-sensitive, and speculatively + field-sensitive alias analysis that is also quite scalable, usually at + O(n*log(n)).

      + +

      This algorithm is capable of responding to a full variety of alias analysis + queries, and can provide context-sensitive mod/ref information as well. The + only major facility not implemented so far is support for must-alias + information.

      + +
      + + + + + +
      + LLVM includes several alias-analysis driven transformations which can be used + with any of the implementations above. +
      + + + + +
      + +

      The -adce pass, which implements Aggressive Dead Code Elimination + uses the AliasAnalysis interface to delete calls to functions that do + not have side-effects and are not used.

      + +
      + + + + + +
      + +

      The -licm pass implements various Loop Invariant Code Motion related + transformations. It uses the AliasAnalysis interface for several + different transformations:

      + +
        +
      • It uses mod/ref information to hoist or sink load instructions out of loops + if there are no instructions in the loop that modifies the memory loaded.
      • + +
      • It uses mod/ref information to hoist function calls out of loops that do not + write to memory and are loop-invariant.
      • + +
      • If uses alias information to promote memory objects that are loaded and + stored to in loops to live in a register instead. It can do this if there are + no may aliases to the loaded/stored memory location.
      • +
      + +
      + + + + +
      +

      + The -argpromotion pass promotes by-reference arguments to be passed in + by-value instead. In particular, if pointer arguments are only loaded from it + passes in the value loaded instead of the address to the function. This pass + uses alias information to make sure that the value loaded from the argument + pointer is not modified between the entry of the function and any load of the + pointer.

      +
      + + + + +
      + +

      The -load-vn pass uses alias analysis to "value + number" loads and pointers values, which is used by the GCSE pass to + eliminate instructions. The -load-vn pass relies on alias information + and must-alias information. This combination of passes can make the following + transformations:

      + +
        +
      • Redundant load instructions are eliminated.
      • +
      • Load instructions that follow a store to the same location are replaced with + the stored value ("store forwarding").
      • +
      • Pointers values (e.g. formal arguments) that must-alias simpler expressions + (e.g. global variables or the null pointer) are replaced. Note that this + implements transformations like "virtual method resolution", turning indirect + calls into direct calls.
      • +
      + +
      + + + + +
      + +

      These passes are useful for evaluating the various alias analysis + implementations. You can use them with commands like 'opt -anders-aa -ds-aa + -aa-eval foo.bc -disable-output -stats'.

      + +
      + + + + +
      + +

      The -print-alias-sets pass is exposed as part of the + opt tool to print out the Alias Sets formed by the AliasSetTracker class. This is useful if you're using + the AliasSetTracker class. To use it, use something like:

      + +
      +
      + % opt -ds-aa -print-alias-sets -disable-output
      + 
      +
      + +
      + + + + + +
      + +

      The -count-aa pass is useful to see how many queries a particular + pass is making and what responses are returned by the alias analysis. As an + example,

      + +
      +
      + % opt -basicaa -count-aa -ds-aa -count-aa -licm
      + 
      +
      + +

      will print out how many queries (and what responses are returned) by the + -licm pass (of the -ds-aa pass) and how many queries are made + of the -basicaa pass by the -ds-aa pass. This can be useful + when debugging a transformation or an alias analysis implementation.

      + +
      + + + + +
      + +

      The -aa-eval pass simply iterates through all pairs of pointers in a + function and asks an alias analysis whether or not the pointers alias. This + gives an indication of the precision of the alias analysis. Statistics are + printed indicating the percent of no/may/must aliases found (a more precise + algorithm will have a lower number of may aliases).

      + +
      + + + +
      +
      + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
      + LLVM Compiler Infrastructure
      + Last modified: $Date: 2006/08/09 05:56:40 $ +
      + + + Index: llvm-www/releases/1.8/docs/Bugpoint.html diff -c /dev/null llvm-www/releases/1.8/docs/Bugpoint.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/Bugpoint.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,238 ---- + + + + LLVM bugpoint tool: design and usage + + + +
      + LLVM bugpoint tool: design and usage +
      + + + +
      +

      Written by Chris Lattner

      +
      + + + + + +
      + +

      bugpoint narrows down the source of problems in LLVM tools and + passes. It can be used to debug three types of failures: optimizer crashes, + miscompilations by optimizers, or bad native code generation (including problems + in the static and JIT compilers). It aims to reduce large test cases to small, + useful ones. For example, if gccas crashes while optimizing a + file, it will identify the optimization (or combination of optimizations) that + causes the crash, and reduce the file down to a small example which triggers the + crash.

      + +

      For detailed case scenarios, such as debugging gccas, + gccld, or one of the LLVM code generators, see How To Submit a Bug Report document.

      + +
      + + + + + +
      + +

      bugpoint is designed to be a useful tool without requiring any + hooks into the LLVM infrastructure at all. It works with any and all LLVM + passes and code generators, and does not need to "know" how they work. Because + of this, it may appear to do stupid things or miss obvious + simplifications. bugpoint is also designed to trade off programmer + time for computer time in the compiler-debugging process; consequently, it may + take a long period of (unattended) time to reduce a test case, but we feel it + is still worth it. Note that bugpoint is generally very quick unless + debugging a miscompilation where each test of the program (which requires + executing it) takes a long time.

      + +
      + + + + +
      + +

      bugpoint reads each .bc or .ll file specified on + the command line and links them together into a single module, called the test + program. If any LLVM passes are specified on the command line, it runs these + passes on the test program. If any of the passes crash, or if they produce + malformed output (which causes the verifier to abort), bugpoint starts + the crash debugger.

      + +

      Otherwise, if the -output option was not specified, + bugpoint runs the test program with the C backend (which is assumed to + generate good code) to generate a reference output. Once bugpoint has + a reference output for the test program, it tries executing it with the + selected code generator. If the selected code generator crashes, + bugpoint starts the crash debugger on the + code generator. Otherwise, if the resulting output differs from the reference + output, it assumes the difference resulted from a code generator failure, and + starts the code generator debugger.

      + +

      Finally, if the output of the selected code generator matches the reference + output, bugpoint runs the test program after all of the LLVM passes + have been applied to it. If its output differs from the reference output, it + assumes the difference resulted from a failure in one of the LLVM passes, and + enters the miscompilation debugger. + Otherwise, there is no problem bugpoint can debug.

      + +
      + + + + +
      + +

      If an optimizer or code generator crashes, bugpoint will try as hard + as it can to reduce the list of passes (for optimizer crashes) and the size of + the test program. First, bugpoint figures out which combination of + optimizer passes triggers the bug. This is useful when debugging a problem + exposed by gccas, for example, because it runs over 38 passes.

      + +

      Next, bugpoint tries removing functions from the test program, to + reduce its size. Usually it is able to reduce a test program to a single + function, when debugging intraprocedural optimizations. Once the number of + functions has been reduced, it attempts to delete various edges in the control + flow graph, to reduce the size of the function as much as possible. Finally, + bugpoint deletes any individual LLVM instructions whose absence does + not eliminate the failure. At the end, bugpoint should tell you what + passes crash, give you a bytecode file, and give you instructions on how to + reproduce the failure with opt, analyze, or llc.

      + +
      + + + + +
      + +

      The code generator debugger attempts to narrow down the amount of code that + is being miscompiled by the selected code generator. To do this, it takes the + test program and partitions it into two pieces: one piece which it compiles + with the C backend (into a shared object), and one piece which it runs with + either the JIT or the static LLC compiler. It uses several techniques to + reduce the amount of code pushed through the LLVM code generator, to reduce the + potential scope of the problem. After it is finished, it emits two bytecode + files (called "test" [to be compiled with the code generator] and "safe" [to be + compiled with the C backend], respectively), and instructions for reproducing + the problem. The code generator debugger assumes that the C backend produces + good code.

      + +
      + + + + +
      + +

      The miscompilation debugger works similarly to the code generator debugger. + It works by splitting the test program into two pieces, running the + optimizations specified on one piece, linking the two pieces back together, and + then executing the result. It attempts to narrow down the list of passes to + the one (or few) which are causing the miscompilation, then reduce the portion + of the test program which is being miscompiled. The miscompilation debugger + assumes that the selected code generator is working properly.

      + +
      + + + + + +
      + + bugpoint can be a remarkably useful tool, but it sometimes works in + non-obvious ways. Here are some hints and tips:

      + +

        +
      1. In the code generator and miscompilation debuggers, bugpoint only + works with programs that have deterministic output. Thus, if the program + outputs argv[0], the date, time, or any other "random" data, + bugpoint may misinterpret differences in these data, when output, + as the result of a miscompilation. Programs should be temporarily modified + to disable outputs that are likely to vary from run to run. + +
      2. In the code generator and miscompilation debuggers, debugging will go + faster if you manually modify the program or its inputs to reduce the + runtime, but still exhibit the problem. + +
      3. bugpoint is extremely useful when working on a new optimization: + it helps track down regressions quickly. To avoid having to relink + bugpoint every time you change your optimization however, have + bugpoint dynamically load your optimization with the + -load option. + +
      4. bugpoint can generate a lot of output and run for a long period + of time. It is often useful to capture the output of the program to file. + For example, in the C shell, you can run:

        + +
        +

        bugpoint ... |& tee bugpoint.log

        +
        + +

        to get a copy of bugpoint's output in the file + bugpoint.log, as well as on your terminal.

        + +
      5. bugpoint cannot debug problems with the LLVM linker. If + bugpoint crashes before you see its "All input ok" message, + you might try llvm-link -v on the same set of input files. If + that also crashes, you may be experiencing a linker bug. + +
      6. If your program is supposed to crash, bugpoint will be + confused. One way to deal with this is to cause bugpoint to ignore the exit + code from your program, by giving it the -check-exit-code=false + option. + +
      + +
      + + + +
      +
      + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
      + LLVM Compiler Infrastructure
      + Last modified: $Date: 2006/08/09 05:56:40 $ +
      + + + Index: llvm-www/releases/1.8/docs/BytecodeFormat.html diff -c /dev/null llvm-www/releases/1.8/docs/BytecodeFormat.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/BytecodeFormat.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,2154 ---- + + + + + LLVM Bytecode File Format + + + + +
      LLVM Bytecode File Format
      +
        +
      1. Abstract
      2. +
      3. Concepts +
          +
        1. Blocks
        2. +
        3. Lists
        4. +
        5. Fields
        6. +
        7. Alignment
        8. +
        9. Variable Bit-Rate Encoding
        10. +
        11. Encoding Primitives
        12. +
        13. Slots
        14. +
        +
      4. +
      5. General Structure
      6. +
      7. Block Definitions +
          +
        1. Signature Block
        2. +
        3. Module Block
        4. +
        5. Global Type Pool
        6. +
        7. Module Info Block
        8. +
        9. Global Constant Pool
        10. +
        11. Function Definition
        12. +
        13. Compaction Table
        14. +
        15. Instructions List
        16. +
        17. Instructions
        18. +
        19. Symbol Table
        20. +
        +
      8. +
      9. Version Differences +
          +
        1. Version 1.3 Differences From 1.4
        2. +
        3. Version 1.2 Differences From 1.3
        4. +
        5. Version 1.1 Differences From 1.2
        6. +
        7. Version 1.0 Differences From 1.1
        8. +
        +
      10. +
      +
      +

      Written by Reid Spencer +

      +
      + + + +
      +

      This document describes the LLVM bytecode file format. It specifies + the binary encoding rules of the bytecode file format so that + equivalent systems can encode bytecode files correctly. The LLVM + bytecode representation is used to store the intermediate + representation on disk in compacted form.

      +

      The LLVM bytecode format may change in the future, but LLVM will + always be backwards compatible with older formats. This document will + only describe the most current version of the bytecode format. See Version Differences for the details on how + the current version is different from previous versions.

      +
      + + + +
      +

      This section describes the general concepts of the bytecode file + format without getting into specific layout details. It is recommended + that you read this section thoroughly before interpreting the detailed + descriptions.

      +
      + + +
      +

      LLVM bytecode files consist simply of a sequence of blocks of bytes + using a binary encoding Each block begins with an header of two + unsigned integers. The first value identifies the type of block and the + second value provides the size of the block in bytes. The block + identifier is used because it is possible for entire blocks to be + omitted from the file if they are empty. The block identifier helps the + reader determine which kind of block is next in the file. Note that + blocks can be nested within other blocks.

      +

      All blocks are variable length, and the block header specifies the + size of the block. All blocks begin on a byte index that is aligned to + an even 32-bit boundary. That is, the first block is 32-bit aligned + because it starts at offset 0. Each block is padded with zero fill + bytes to ensure that the next block also starts on a 32-bit boundary.

      +
      + + +
      +

      LLVM Bytecode blocks often contain lists of things of a similar + type. For example, a function contains a list of instructions and a + function type contains a list of argument types. There are two basic + types of lists: length lists (llist), and null + terminated lists (zlist), as described below in + the Encoding Primitives.

      +
      + + +
      +

      Fields are units of information that LLVM knows how to write atomically. Most + fields have a uniform length or some kind of length indication built into their + encoding. For example, a constant string (array of bytes) is written simply as + the length followed by the characters. Although this is similar to a list, + constant strings are treated atomically and are thus fields.

      +

      Fields use a condensed bit format specific to the type of information + they must contain. As few bits as possible are written for each field. The + sections that follow will provide the details on how these fields are + written and how the bits are to be interpreted.

      +
      + + +
      +

      To support cross-platform differences, the bytecode file is aligned on + certain boundaries. This means that a small amount of padding (at most 3 + bytes) will be added to ensure that the next entry is aligned to a 32-bit + boundary.

      +
      + + +
      +

      Most of the values written to LLVM bytecode files are small integers. To + minimize the number of bytes written for these quantities, an encoding scheme + similar to UTF-8 is used to write integer data. The scheme is known as + variable bit rate (vbr) encoding. In this encoding, the high bit of + each byte is used to indicate if more bytes follow. If (byte & + 0x80) is non-zero in any given byte, it means there is another byte + immediately following that also contributes to the value. For the final + byte (byte & 0x80) is false (the high bit is not set). In each byte + only the low seven bits contribute to the value. Consequently 32-bit + quantities can take from one to five bytes to encode. In + general, smaller quantities will encode in fewer bytes, as follows:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Byte #Significant BitsMaximum Value
      10-6127
      27-1316,383
      314-202,097,151
      421-27268,435,455
      528-3434,359,738,367
      635-414,398,046,511,103
      742-48562,949,953,421,311
      849-5572,057,594,037,927,935
      956-629,223,372,036,854,775,807
      1063-691,180,591,620,717,411,303,423
      +

      Note that in practice, the tenth byte could only encode bit 63 since + the maximum quantity to use this encoding is a 64-bit integer.

      +

      Signed VBR values are encoded with the standard vbr + encoding, but with the sign bit as the low order bit instead of the + high order bit. This allows small negative quantities to be encoded + efficiently. For example, -3 + is encoded as "((3 << 1) | 1)" and 3 is encoded as "(3 << + 1) | 0)", emitted with the standard vbr encoding above.

      +
      + + +
      +

      Each field in the bytecode format is encoded into the file using a + small set of primitive formats. The table below defines the encoding + rules for the various primitives used and gives them each a type name. + The type names used in the descriptions of blocks and fields in the Detailed Layoutnext section. Any type name with + the suffix _vbr indicates a quantity that is encoded using + variable bit rate encoding as described above.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeRule
      unsignedA 32-bit unsigned integer that always occupies four + consecutive bytes. The unsigned integer is encoded using LSB first + ordering. That is bits 20 through 27 are in the + byte with the lowest file offset (little endian).
      + uint24_vbrA 24-bit unsigned + integer that occupies from one to four bytes using variable bit rate + encoding.
      uint32_vbrA 32-bit unsigned integer that occupies from one to + five bytes using variable bit rate encoding.
      uint64_vbrA 64-bit unsigned integer that occupies from one to ten + bytes using variable bit rate encoding.
      int64_vbrA 64-bit signed integer that occupies from one to ten + bytes using the signed variable bit rate encoding.
      charA single unsigned character encoded into one byte
      bit(n-m)A set of bit within some larger integer field. The values + of n and m specify the inclusive range of bits + that define the subfield. The value for m may be omitted if + its the same as n.
      floatA floating point value encoded + as a 32-bit IEEE value written in little-endian form.
      +
      doubleA floating point value encoded + as a64-bit IEEE value written in little-endian form
      stringA uint32_vbr indicating the type of the + constant string which also includes its length, immediately followed by + the characters of the string. There is no terminating null byte in the + string.
      dataAn arbitrarily long segment of data to which + no interpretation is implied. This is used for constant initializers.
      +
      llist(x)A length list of x. This means the list is + encoded as an uint32_vbr providing the + length of the list, followed by a sequence of that many "x" items. This + implies that the reader should iterate the number of times provided by + the length.
      zlist(x)A zero-terminated list of x. This means the + list is encoded as a sequence of an indeterminate number of "x" items, + followed by an uint32_vbr terminating value. + This implies that none of the "x" items can have a zero value (or else + the list terminates).
      blockA block of data that is logically related. A + block is an unsigned 32-bit integer that encodes the type of the block + in the low 5 bits and the size of the block in the high 27 bits. The + length does not include the block header or any alignment bytes at the + end of the block. Blocks may compose other blocks.
      +
      + + +
      +

      In the detailed block and field descriptions that follow, a regex + like notation is used to describe optional and repeated fields. A very + limited subset of regex is used to describe these, as given in the + following table:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      CharacterMeaning
      ?The question mark indicates 0 or 1 + occurrences of the thing preceding it.
      *The asterisk indicates 0 or more occurrences + of the thing preceding it.
      +The plus sign indicates 1 or more occurrences + of the thing preceding it.
      ()Parentheses are used for grouping.
      ,The comma separates sequential fields.
      +

      So, for example, consider the following specifications:

      +
      +
        +
      1. string?
      2. +
      3. (uint32_vbr,uin32_vbr)+
      4. +
      5. (unsigned?,uint32_vbr)*
      6. +
      7. (llist(unsigned))?
      8. +
      +
      +

      with the following interpretations:

      +
        +
      1. An optional string. Matches either nothing or a single string
      2. +
      3. One or more pairs of uint32_vbr.
      4. +
      5. Zero or more occurrences of either an unsigned followed by a + uint32_vbr or just a uint32_vbr.
      6. +
      7. An optional length list of unsigned values.
      8. +
      +
      + + +
      +

      The bytecode format uses the notion of a "slot" to reference Types + and Values. Since the bytecode file is a direct representation of + LLVM's intermediate representation, there is a need to represent pointers in + the file. Slots are used for this purpose. For example, if one has the following + assembly: +

      +
      %MyType = type { int, sbyte }
      + %MyVar = external global %MyType +
      +

      there are two definitions. The definition of %MyVar uses %MyType. + In the C++ IR this linkage between %MyVar and %MyType + is explicit through the use of C++ pointers. In bytecode, however, there's no + ability to store memory addresses. Instead, we compute and write out + slot numbers for every Type and Value written to the file.

      +

      A slot number is simply an unsigned 32-bit integer encoded in the variable + bit rate scheme (see encoding). This ensures that + low slot numbers are encoded in one byte. Through various bits of magic LLVM + attempts to always keep the slot numbers low. The first attempt is to associate + slot numbers with their "type plane". That is, Values of the same type + are written to the bytecode file in a list (sequentially). Their order in + that list determines their slot number. This means that slot #1 doesn't mean + anything unless you also specify for which type you want slot #1. Types are + always written to the file first (in the Global Type + Pool) and in such a way that both forward and backward references of the + types can often be resolved with a single pass through the type pool.

      +

      Slot numbers are also kept small by rearranging their order. Because + of the structure of LLVM, certain values are much more likely to be used + frequently in the body of a function. For this reason, a compaction table is + provided in the body of a function if its use would make the function body + smaller. Suppose you have a function body that uses just the types "int*" and + "{double}" but uses them thousands of time. Its worthwhile to ensure that the + slot number for these types are low so they can be encoded in a single byte + (via vbr). This is exactly what the compaction table does.

      +

      In summary then, a slot number can be though of as just a vbr encoded index + into a list of Type* or Value*. To keep slot numbers low, Value* are indexed by + two slot numbers: the "type plane index" (type slot) and the "value index" + (value slot).

      +
      + + + +
      +

      This section provides the general structure of the LLVM bytecode + file format. The bytecode file format requires blocks to be in a + certain order and nested in a particular way so that an LLVM module can + be constructed efficiently from the contents of the file. This ordering + defines a general structure for bytecode files as shown below. The + table below shows the order in which all block types may appear. Please + note that some of the blocks are optional and some may be repeated. The + structure is fairly loose because optional blocks, if empty, are + completely omitted from the file.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      IDParentOptional?Repeated?LevelBlock TypeDescription
      N/AFileNoNo0SignatureThis contains the file signature (magic + number) that identifies the file as LLVM bytecode.
      0x01FileNoNo0ModuleThis is the top level block in a bytecode + file. It contains all the other blocks.
      0x06ModuleNoNo1   Global Type PoolThis block contains all the global (module) + level types.
      0x05ModuleNoNo1   Module Globals InfoThis block contains the type, constness, and + linkage for each of the global variables in the module. It also + contains the type of the functions and the constant initializers.
      0x03ModuleYesNo1   Module Constant PoolThis block contains all the global constants + except function arguments, global values and constant strings.
      0x02ModuleYesYes1   Function Definitions*One function block is written for each + function in the module. The function block contains the instructions, + compaction table, type constant pool, and symbol table for the function.
      0x03FunctionYesNo2      Function Constant PoolAny constants (including types) used solely + within the function are emitted here in the function constant pool.
      0x08FunctionYesNo2      Compaction TableThis table reduces bytecode size by providing + a funtion-local mapping of type and value slot numbers to their global + slot numbers
      0x07FunctionNoNo2      Instruction ListThis block contains all the instructions of + the function. The basic blocks are inferred by terminating + instructions.
      0x04FunctionYesNo2      Function Symbol TableThis symbol table provides the names for the + function specific values used (basic block labels mostly).
      0x04ModuleYesNo1   Module Symbol TableThis symbol table provides the names for the + various entries in the file that are not function specific (global + vars, and functions mostly).
      +

      Use the links in the table for details about the contents of each of + the block types.

      +
      + + + +
      +

      This section provides the detailed layout of the individual block + types in the LLVM bytecode file format.

      +
      + + +
      +

      The signature occurs in every LLVM bytecode file and is always first. + It simply provides a few bytes of data to identify the file as being an LLVM + bytecode file. This block is always four bytes in length and differs from the + other blocks because there is no identifier and no block length at the start + of the block. Essentially, this block is just the "magic number" for the file. +

      +

      There are two types of signatures for LLVM bytecode: uncompressed and + compressed as shown in the table below.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeUncompressedCompressed
      charConstant "l" (0x6C)Constant "l" (0x6C)
      charConstant "l" (0x6C)Constant "l" (0x6C)
      charConstant "v" (0x76)Constant "v" (0x76)
      charConstant "m" (0x6D)Constant "c" (0x63)
      charN/A'0'=null,'1'=gzip,'2'=bzip2
      +

      In other words, the uncompressed signature is just the characters 'llvm' + while the compressed signature is the characters 'llvc' followed by an ascii + digit ('0', '1', or '2') that indicates the kind of compression used. A value of + '0' indicates that null compression was used. This can happen when compression + was requested on a platform that wasn't configured for gzip or bzip2. A value of + '1' means that the rest of the file is compressed using the gzip algorithm and + should be uncompressed before interpretation. A value of '2' means that the rest + of the file is compressed using the bzip2 algorithm and should be uncompressed + before interpretation. In all cases, the data resulting from uncompression + should be interpreted as if it occurred immediately after the 'llvm' + signature (i.e. the uncompressed data begins with the + Module Block

      +

      NOTE: As of LLVM 1.4, all bytecode files produced by the LLVM tools + are compressed by default. To disable compression, pass the + --disable-compression option to the tool, if it supports it. +

      + + +
      +

      The module block contains a small pre-amble and all the other blocks in + the file. The table below shows the structure of the module block. Note that it + only provides the module identifier, size of the module block, and the format + information. Everything else is contained in other blocks, described in other + sections.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      unsigned
      Module Block Identifier + (0x01)
      unsignedModule Block Size
      uint32_vbrFormat Information
      blockGlobal Type Pool
      blockModule Globals Info
      blockModule Constant Pool
      block*Function Definitions
      blockModule Symbol Table
      +
      + + + +
      +

      The block header for the module block uses a longer format than the other + blocks in a bytecode file. Specifically, instead of encoding the type and size + of the block into a 32-bit integer with 5-bits for type and 27-bits for size, + the module block header uses two 32-bit unsigned values, one for type, and one + for size. While the 227 byte limit on block size is sufficient for the blocks + contained in the module, it isn't sufficient for the module block itself + because we want to ensure that bytecode files as large as 232 bytes + are possible. For this reason, the module block (and only the module block) + uses a long format header.

      +
      + + + +
      +

      The format information field is encoded into a uint32_vbr + as shown in the following table.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeDescription
      bit(0)Target is big endian?
      bit(1)On target pointers are 64-bit?
      bit(2)Target has no endianess?
      bit(3)Target has no pointer size?
      bit(4-31)Bytecode format version
      +

      + Of particular note, the bytecode format number is simply a 28-bit + monotonically increasing integer that identifies the version of the bytecode + format (which is not directly related to the LLVM release number). The + bytecode versions defined so far are (note that this document only + describes the latest version, 1.3):

      +
        +
      • #0: LLVM 1.0 & 1.1
      • +
      • #1: LLVM 1.2
      • +
      • #2: LLVM 1.2.5 (not released)
      • +
      • #3: LLVM 1.3
      • +
      • #4: LLVM 1.3.x (not released)
      • +
      • #5: LLVM 1.4 and newer
      • + +
      +

      Note that we plan to eventually expand the target description + capabilities + of bytecode files to target + triples. +

      +
      + + +
      +

      The global type pool consists of type definitions. Their order of appearance + in the file determines their type slot number (0 based). Slot numbers are + used to replace pointers in the intermediate representation. Each slot number + uniquely identifies one entry in a type plane (a collection of values of the + same type). Since all values have types and are associated with the order in + which the type pool is written, the global type pool must be written + as the first block of a module. If it is not, attempts to read the file will + fail because both forward and backward type resolution will not be possible.

      +

      The type pool is simply a list of type definitions, as shown in the + table below.

      + + + + + + + + + + + + + + + +
      TypeField Description
      blockType Pool Identifier (0x06) + Size
      +
      llist(type)A length list of type definitions.
      +
      + + +
      +

      Types in the type pool are defined using a different format for each kind + of type, as given in the following sections.

      +

      Primitive Types

      +

      The primitive types encompass the basic integer and floating point + types. They are encoded simply as their TypeID.

      + + + + + + + + + + + +
      TypeDescription
      uint24_vbrType ID for the primitive types (values 1 to + 11) 1
      + Notes: +
        +
      1. The values for the Type IDs for the primitive types are provided + by the definition of the llvm::Type::TypeID enumeration + in include/llvm/Type.h. The enumeration gives the + following mapping: +
          +
        1. bool
        2. +
        3. ubyte
        4. +
        5. sbyte
        6. +
        7. ushort
        8. +
        9. short
        10. +
        11. uint
        12. +
        13. int
        14. +
        15. ulong
        16. +
        17. long
        18. +
        19. float
        20. +
        21. double
        22. +
        +
      2. +
      +

      Function Types

      + + + + + + + + + + + + + + + + + + + + + + + +
      TypeDescription
      uint24_vbrType ID for function types (13)
      uint24_vbrType slot number of function's return type.
      llist(uint24_vbr)Type slot number of each argument's type.
      uint32_vbr?Value 0 if this is a varargs function, + missing otherwise.
      +

      Structure Types

      + + + + + + + + + + + + + + + +
      TypeDescription
      uint24_vbrType ID for structure types (14)
      zlist(uint24_vbr)Slot number of each of the element's fields.
      +

      Array Types

      + + + + + + + + + + + + + + + + + + + +
      TypeDescription
      uint24_vbrType ID for Array Types (15)
      uint24_vbrType slot number of array's element type.
      uint32_vbrThe number of elements in the array.
      +

      Pointer Types

      + + + + + + + + + + + + + + + +
      TypeDescription
      uint24_vbrType ID For Pointer Types (16)
      uint24_vbrType slot number of pointer's element type.
      +

      Opaque Types

      + + + + + + + + + + + +
      TypeDescription
      uint24_vbrType ID For Opaque Types (17)
      +

      Packed Types

      + + + + + + + + + + + + + + + + + + + +
      TypeDescription
      uint24_vbrType ID for Packed Types (18)
      uint24_vbrSlot number of packed vector's element type.
      uint32_vbrThe number of elements in the packed vector.
      +
      + + +
      +

      The module global info block contains the definitions of all global + variables including their initializers and the declaration of + all functions. The format is shown in the table below:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      blockModule global info identifier (0x05) + size
      zlist(globalvar)A zero terminated list of global var + definitions occurring in the module.
      zlist(funcfield)A zero terminated list of function definitions + occurring in the module.
      llist(string)A length list + of strings that specify the names of the libraries that this module + depends upon.
      stringThe target + triple for the module (blank means no target triple specified, i.e. a + platform independent module).
      llist(string)A length list + of strings that defines a table of section strings for globals. A global's + SectionID is an index into this table.
      stringThe inline asm block for this module.
      +
      + + + + +
      + +

      Global variables are written using an uint32_vbr + that encodes information about the global variable, an optional extension vbr, + and a an optional initializers for the global var.

      + +

      The table below provides the bit layout of the first uint32_vbr that describes the global variable.

      + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeDescription
      bit(0)Is constant?
      bit(1)Has initializer? Note that this bit + determines whether the constant initializer field (described below) + follows.
      bit(2-4)Linkage type: 0=External, 1=Weak, + 2=Appending, 3=Internal, 4=LinkOnce
      bit(5-31)Type slot number of type for the global variable.
      + +

      When the Linkage type is set to 3 (internal) and the initializer field is set + to 0 (an invalid combination), an extension word follows the first uint32_vbr which encodes the real linkage and init flag, + and can includes more information:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeDescription
      bit(0)Has initializer? Indicates the real value of the "Has + initializer" field for the global.
      bit(2-4)Linkage type: Indicates the real value of the "linkage + type" field for the global.
      bit(4-8)The log-base-2 of the alignment for the global.
      bit(9)If this bit is set, a SectionID follows this vbr.
      bit(10-31)Currently unassigned.
      + +

      If the SectionID bit is set above, the following field is included:

      + + + + + + + + + + + + +
      TypeDescription
      uint32_vbr + An optional section ID number, specifying the string + to use for the section of the global. This an index (+1) of an entry + into the SectionID llist in the Module Global + Info block. If this value is 0 or not present, the global has an + empty section string.
      + +

      If the "Has initializer" field is set, the following field is included:

      + + + + + + + + + + + + +
      TypeDescription
      uint32_vbr + An optional value slot number for the global + variable's constant initializer.
      +
      + + + +
      +

      Functions are written using an uint32_vbr + that encodes information about the function and a set of flags. If needed, + an extension word may follow this first field.

      + +

      The table below provides the bit layout of the uint32_vbr that describes the function.

      + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeDescription
      bit(0-3) + Encodes the calling convention number of the function. The + CC number of the function is the value of this field minus one. +
      bit(4)If this bit is set to 1, the indicated function is + external, and there is no Function Definiton + Block in the bytecode file for the function.
      bit(5-30)Type slot number of type for the function.
      bit(31)Indicates whether an extension word follows.
      + +

      If bit(31) is set, an additional uint32_vbr word + follows with the following fields:

      + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeDescription
      bit(0-4)The log-base-2 of the alignment for the function.
      bit(5-9)The top nibble of the calling convention.
      bit(10)If this bit is set, a SectionID follows this vbr.
      bit(11-31)Currently unassigned.
      + +

      If the SectionID bit is set above, the following field is included:

      + + + + + + + + + + + + +
      TypeDescription
      uint32_vbr + An optional section ID number, specifying the string + to use for the section of the function. This an index (+1) of an entry + into the SectionID llist in the Module Global + Info block. If this value is 0 or not present, the function has an + empty section string.
      + +
      + + + +
      +

      A constant pool defines as set of constant values. There are + actually two types of constant pool blocks: one for modules and one for + functions. For modules, the block begins with the constant strings + encountered anywhere in the module. For functions, the block begins + with types only encountered in the function. In both cases the header + is identical. The tables that follow, show the header, module constant + pool preamble, function constant pool preamble, and the part common to + both function and module constant pools.

      +

      Common Block Header

      + + + + + + + + + + + +
      TypeField Description
      blockConstant pool identifier (0x03) + size
      +
      +

      Module Constant Pool Preamble (constant strings)

      + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      uint32_vbrThe number of constant strings that follow.
      uint32_vbrZero. This identifies the following "plane" + as containing the constant strings. This is needed to identify it + uniquely from other constant planes that follow.
      uint24_vbr+Type slot number of the constant string's type. + Note that the constant string's type implicitly defines the length of + the string.
      +

      Function Constant Pool Preamble (function types)

      +

      The structure of the types for functions is identical to the Global Type Pool. Please refer to that section + for the details.

      +

      Common Part (other constants)

      + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      uint32_vbrNumber of entries in this type plane.
      uint24_vbrType slot number of this plane.
      constant+The definition of a constant (see below).
      +
      + + + + +
      + +

      Constant pool entries come in many shapes and flavors. The sections that + follow define the format for each of them. All constants start with a uint32_vbr encoded integer that provides the + number of operands for the constant. For primitive, structure, and + array constants, this will always be zero to indicate that the form of the + constant is solely determined by its type. In this case, we have the following + field definitions, based on type:

      + +
        +
      • Bool. This is written as an uint32_vbr + of value 1U or 0U.
      • +
      • Signed Integers (sbyte,short,int,long). These are written + as an int64_vbr with the corresponding value.
      • +
      • Unsigned Integers (ubyte,ushort,uint,ulong). These are + written as an uint64_vbr with the + corresponding value.
      • +
      • Floating Point. Both the float and double types are + written literally in binary format.
      • +
      • Arrays. Arrays are written simply as a list of uint32_vbr encoded value slot numbers to the constant + element values.
      • +
      • Structures. Structures are written simply as a list of uint32_vbr encoded value slot numbers to the constant + field values of the structure.
      • +
      + +
      + + +
      Undef Entries
      + +
      +

      When the number of operands to the constant is one, we have an 'undef' value + of the specified type.

      +
      + + +
      Inline Assembler Entries
      + +
      +

      Inline Assembler entries are stored in the constant pool, though they are not + officially LLVM constants. These entries are marked with a value of + "4294967295" (all ones) for the number of operands. They are encoded as + follows:

      + + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      stringThe asm string.
      stringThe constraints string.
      uint32_vbrFlags
      + +

      Currently, the only defined flag, the low bit, indicates whether or not the + inline assembler has side effects.

      + +
      + + +
      Constant Expression Entries
      + +
      + +

      Otherwise, we have a constant expression. The format of the constant + expression is specified in the table below, and the number is equal to the + number of operands+1.

      + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      uint32_vbrOp code of the instruction for the constant + expression.
      uint32_vbrThe value slot number of the constant value for an + operand.1
      uint24_vbrThe type slot number for the type of the constant + value for an operand.1
      + Notes: +
        +
      1. Both these fields are repeatable but only in pairs.
      2. +
      +
      + + +
      +

      Function definitions contain the linkage, constant pool or + compaction table, instruction list, and symbol table for a function. + The following table shows the structure of a function definition.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      block
      +
      Function definition block identifier (0x02) + + size
      +
      uint32_vbrThe linkage type of the function: 0=External, + 1=Weak, 2=Appending, 3=Internal, 4=LinkOnce1
      blockThe constant pool + block for this function.2
      blockThe compaction + table block for the function.2
      blockThe instruction + list for the function.
      blockThe function's symbol + table containing only those symbols pertinent to the function + (mostly block labels).
      + Notes: +
        +
      1. Note that if the linkage type is "External" then none of the + other fields will be present as the function is defined elsewhere.
      2. +
      3. Note that only one of the constant pool or compaction table will + be written. Compaction tables are only written if they will actually + save bytecode space. If not, then a regular constant pool is written.
      4. +
      +
      + + +
      +

      Compaction tables are part of a function definition. They are merely + a device for reducing the size of bytecode files. The size of a + bytecode file is dependent on the values of the slot numbers + used because larger values use more bytes in the variable bit rate + encoding scheme. Furthermore, the compressed instruction format + reserves only six bits for the type of the instruction. In large + modules, declaring hundreds or thousands of types, the values of the + slot numbers can be quite large. However, functions may use only a + small fraction of the global types. In such cases a compaction table is + created that maps the global type and value slot numbers to smaller + values used by a function. Functions will contain either a + function-specific constant pool or a compaction table but not + both. Compaction tables have the format shown in the table below.

      + + + + + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      uint32_vbrThe number of types that follow
      uint24_vbr+The type slot number in the global types of + the type that will be referenced in the function with the index of this + entry in the compaction table.
      type_lenAn encoding of the type and number of values + that follow. This field's encoding varies depending on the size of the + type plane. See Type and Length for further + details.
      uint32_vbr+The value slot number in the global values + that will be referenced in the function with the index of this entry in + the compaction table.
      +
      + + +
      +

      The type and length of a compaction table type plane is encoded + differently depending on the length of the plane. For planes of length + 1 or 2, the length is encoded into bits 0 and 1 of a uint32_vbr and the type is encoded into bits + 2-31. Because type numbers are often small, this often saves an extra + byte per plane. If the length of the plane is greater than 2 then the + encoding uses a uint32_vbr for each of the + length and type, in that order.

      +
      + + +
      +

      The instructions in a function are written as a simple list. Basic + blocks are inferred by the terminating instruction types. The format of + the block is given in the following table.

      + + + + + + + + + + + + + + + +
      TypeField Description
      block
      +
      Instruction list identifier (0x07) + size
      +
      instruction+An instruction. Instructions have a variety + of formats. See Instructions for details.
      +
      + + + + +
      +

      Instructions are written out one at a time as distinct units. Each + instruction + record contains at least an opcode and a type field, + and may contain a list of operands (whose + interpretation depends on the opcode). Based on the number of operands, the + instruction is encoded in a + dense format that tries to encoded each instruction into 32-bits if + possible.

      +
      + + + +
      +

      Instructions encode an opcode that identifies the kind of instruction. + Opcodes are an enumerated integer value. The specific values used depend on + the version of LLVM you're using. The opcode values are defined in the + + include/llvm/Instruction.def file. You should check there for the + most recent definitions. The table below provides the opcodes defined as of + the writing of this document. The table associates each opcode mnemonic with + its enumeration value and the bytecode and LLVM version numbers in which the + opcode was introduced.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      OpcodeNumberBytecode VersionLLVM Version
      Terminator Instructions
      Ret111.0
      Br211.0
      Switch311.0
      Invoke411.0
      Unwind511.0
      Unreachable611.4
      Binary Operators
      Add711.0
      Sub811.0
      Mul911.0
      Div1011.0
      Rem1111.0
      Logical Operators
      And1211.0
      Or1311.0
      Xor1411.0
      Binary Comparison Operators
      SetEQ1511.0
      SetNE1611.0
      SetLE1711.0
      SetGE1811.0
      SetLT1911.0
      SetGT2011.0
      Memory Operators
      Malloc2111.0
      Free2211.0
      Alloca2311.0
      Load2411.0
      Store2511.0
      GetElementPtr2611.0
      Other Operators
      PHI2711.0
      Cast2811.0
      Call2911.0
      Shl3011.0
      Shr3111.0
      VANext3211.0
      VAArg3311.0
      Select3421.2
      + Pseudo Instructions* +
      Invoke+CC 5651.5
      Invoke+FastCC5751.5
      Call+CC5851.5
      Call+FastCC+TailCall5951.5
      Call+FastCC6051.5
      Call+CCC+TailCall6151.5
      Load+Volatile6231.3
      Store+Volatile6331.3
      + +

      * Note: + These aren't really opcodes from an LLVM language perspective. They encode + information into other opcodes without reserving space for that information. + For example, opcode=63 is a Volatile Store. The opcode for this + instruction is 25 (Store) but we encode it as 63 to indicate that is a Volatile + Store. The same is done for the calling conventions and tail calls. + In each of these entries in range 56-63, the opcode is documented as the base + opcode (Invoke, Call, Store) plus some set of modifiers, as follows:

      +
      +
      CC
      +
      This means an arbitrary calling convention is specified + in a VBR that follows the opcode. This is used when the instruction cannot + be encoded with one of the more compact forms. +
      +
      FastCC
      +
      This indicates that the Call or Invoke is using the FastCC calling + convention.
      +
      CCC
      +
      This indicates that the Call or Invoke is using the native "C" calling + convention.
      +
      TailCall
      +
      This indicates that the Call has the 'tail' modifier.
      +
      +
      + + + + +
      +

      + Based on the instruction opcode and type, the bytecode format implicitly (to + save space) specifies the interpretation of the operand list. For most + instructions, the type of each operand is implicit from the type of the + instruction itself (e.g. the type of operands of a binary operator must match + the type of the instruction). As such, the bytecode format generally only + encodes the value number of the operand, not the type.

      + +

      In some cases, however, this is not sufficient. This section enumerates + those cases:

      + +
        +
      • getelementptr: the slot numbers for sequential type indexes are shifted up + two bits. This allows the low order bits will encode the type of index used, + as follows: 0=uint, 1=int, 2=ulong, 3=long.
      • +
      • cast: the result type number is encoded as the second operand.
      • +
      • alloca/malloc: If the allocation has an explicit alignment, the log2 of the + alignment is encoded as the second operand.
      • +
      • call: If the tail marker and calling convention cannot be encoded into the opcode of the call, it is passed as an + additional operand. The low bit of the operand is a flag indicating whether + the call is a tail call. The rest of the bits contain the calling + convention number (shifted left by one bit).
      • +
      +
      + + + + +
      +

      For brevity, instructions are written in one of four formats, + depending on the number of operands to the instruction. Each + instruction begins with a uint32_vbr that + encodes the type of the instruction as well as other things. The tables + that follow describe the format of this first part of each instruction.

      +

      Instruction Format 0

      +

      This format is used for a few instructions that can't easily be + shortened because they have large numbers of operands (e.g. PHI Node or + getelementptr). Each of the opcode, type, and operand fields is found in + successive fields.

      + + + + + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      uint32_vbrSpecifies the opcode of the instruction. Note + that for compatibility with the other instruction formats, the opcode + is shifted left by 2 bits. Bits 0 and 1 must have value zero for this + format.
      uint24_vbrProvides the type slot number of the result type of + the instruction.
      uint32_vbrThe number of operands that follow.
      uint32_vbr+The slot number of the value(s) for the operand(s). +
      + +

      Instruction Format 1

      +

      This format encodes the opcode, type and a single operand into a + single uint32_vbr as follows:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      BitsTypeField Description
      0-1constant "1"These two bits must be the value 1 which identifies + this as an instruction of format 1.
      2-7opcodeSpecifies the opcode of the instruction. Note that + the maximum opcode value is 63.
      8-19unsignedSpecifies the slot number of the type for this + instruction. Maximum slot number is 212-1=4095.
      20-31unsignedSpecifies the slot number of the value for the + first operand. Maximum slot number is 212-1=4095. Note that + the value 212-1 denotes zero operands.
      +

      Instruction Format 2

      +

      This format encodes the opcode, type and two operands into a single uint32_vbr as follows:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      BitsTypeField Description
      0-1constant "2"These two bits must be the value 2 which identifies + this as an instruction of format 2.
      2-7opcodeSpecifies the opcode of the instruction. Note that + the maximum opcode value is 63.
      8-15unsignedSpecifies the slot number of the type for this + instruction. Maximum slot number is 28-1=255.
      16-23unsignedSpecifies the slot number of the value for the first + operand. Maximum slot number is 28-1=255.
      24-31unsignedSpecifies the slot number of the value for the second + operand. Maximum slot number is 28-1=255.
      +

      Instruction Format 3

      +

      This format encodes the opcode, type and three operands into a + single uint32_vbr as follows:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      BitsTypeField Description
      0-1constant "3"These two bits must be the value 3 which identifies + this as an instruction of format 3.
      2-7opcodeSpecifies the opcode of the instruction. Note that + the maximum opcode value is 63.
      8-13unsignedSpecifies the slot number of the type for this + instruction. Maximum slot number is 26-1=63.
      14-19unsignedSpecifies the slot number of the value for the first + operand. Maximum slot number is 26-1=63.
      20-25unsignedSpecifies the slot number of the value for the second + operand. Maximum slot number is 26-1=63.
      26-31unsignedSpecifies the slot number of the value for the third + operand. Maximum slot number is 26-1=63.
      +
      + + + +
      +

      A symbol table can be put out in conjunction with a module or a function. A + symbol table has a list of name/type associations followed by a list of + name/value associations. The name/value associations are organized into "type + planes" so that all values of a common type are listed together. Each type + plane starts with the number of entries in the plane and the type slot number + for all the values in that plane (so the type can be looked up in the global + type pool). For each entry in a type plane, the slot number of the value and + the name associated with that value are written. The format is given in the + table below.

      + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      block
      +
      Symbol Table Identifier (0x04)
      llist(type_entry)A length list of symbol table entries for + Types +
      llist(symtab_plane)A length list of "type planes" of symbol table + entries for Values
      +
      + + + +
      +

      A symbol table type entry associates a name with a type. The name is provided + simply as an array of chars. The type is provided as a type slot number (index) + into the global type pool. The format is given in the following table:

      + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      uint24_vbrType slot number of the type being given a + name relative to the global type pool. +
      uint32_vbrLength of the character array that follows.
      char+The characters of the name.
      +
      + + +
      +

      A symbol table plane provides the symbol table entries for all + values of a common type. The encoding is given in the following table:

      + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      uint32_vbrNumber of entries in this plane.
      uint32_vbrType slot number of type for all values in this plane..
      value_entry+The symbol table entries for to associate values with + names.
      +
      + + +
      +

      A symbol table value entry provides the assocation between a value and the + name given to the value. The value is referenced by its slot number. The + format is given in the following table:

      + + + + + + + + + + + + + + + + + + + +
      TypeField Description
      uint24_vbrValue slot number of the value being given a name. +
      uint32_vbrLength of the character array that follows.
      char+The characters of the name.
      +
      + + + + +
      +

      This section describes the differences in the Bytecode Format across + LLVM + versions. The versions are listed in reverse order because it assumes + the current version is as documented in the previous sections. Each + section here + describes the differences between that version and the one that follows. +

      +
      + + + + + +
      Unreachable Instruction
      +
      +

      The LLVM Unreachable instruction + was added in version 1.4 of LLVM. This caused all instruction numbers after + it to shift down by one.

      +
      + +
      Function Flags
      +
      +

      LLVM bytecode versions prior to 1.4 did not include the 5 bit offset + in the function list in the Module Global Info block.

      +
      + +
      Function Flags
      +
      +

      LLVM bytecode versions prior to 1.4 did not include the 'undef' constant + value, which affects the encoding of Constant + Fields.

      +
      + + + + + + + +
      Type Derives From Value
      +
      +

      In version 1.2, the Type class in the LLVM IR derives from the Value + class. This is not the case in version 1.3. Consequently, in version + 1.2 the notion of a "Type Type" was used to write out values that were + Types. The types always occuped plane 12 (corresponding to the + TypeTyID) of any type planed set of values. In 1.3 this representation + is not convenient because the TypeTyID (12) is not present and its + value is now used for LabelTyID. Consequently, the data structures + written that involve types do so by writing all the types first and + then each of the value planes according to those types. In version 1.2, + the types would have been written intermingled with the values.

      +
      + +
      Restricted getelementptr Types
      +
      +

      In version 1.2, the getelementptr instruction required a ubyte type + index for accessing a structure field and a long type index for + accessing an array element. Consequently, it was only possible to + access structures of 255 or fewer elements. Starting in version 1.3, + this restriction was lifted. Structures must now be indexed with uint + constants. Arrays may now be indexed with int, uint, long, or ulong + typed values. The consequence of this was that the bytecode format had + to change in order to accommodate the larger range of structure indices.

      +
      + +
      Short Block Headers
      +
      +

      In version 1.2, block headers were always 8 bytes being comprised of + both an unsigned integer type and an unsigned integer size. For very + small modules, these block headers turn out to be a large fraction of + the total bytecode file size. In an attempt to make these small files + smaller, the type and size information was encoded into a single + unsigned integer (4 bytes) comprised of 5 bits for the block type + (maximum 31 block types) and 27 bits for the block size (max + ~134MBytes). These limits seemed sufficient for any blocks or sizes + forseen in the future. Note that the module block, which encloses all + the other blocks is still written as 8 bytes since bytecode files + larger than 134MBytes might be possible.

      +
      + +
      Dependent Libraries and Target Triples
      +
      +

      In version 1.2, the bytecode format does not store module's target + triple or dependent. These fields have been added to the end of the module global info block. The purpose of these + fields is to allow a front end compiler to specifiy that the generated + module is specific to a particular target triple (operating + system/manufacturer/processor) which makes it non-portable; and to + allow front end compilers to specify the list of libraries that the + module depends on for successful linking.

      +
      + +
      Types Restricted to 24-bits
      +
      +

      In version 1.2, type slot identifiers were written as 32-bit VBR + quantities. In 1.3 this has been reduced to 24-bits in order to ensure + that it is not possible to overflow the type field of a global variable + definition. 24-bits for type slot numbers is deemed sufficient for any + practical use of LLVM.

      +
      + + + + +
      Explicit Primitive Zeros
      +
      +

      In version 1.1, the zero value for primitives was explicitly encoded + into the bytecode format. Since these zero values are constant values + in the LLVM IR and never change, there is no reason to explicitly + encode them. This explicit encoding was removed in version 1.2.

      +
      + +
      Inconsistent Module Global Info
      +
      +

      In version 1.1, the Module Global Info block was not aligned causing + the next block to be read in on an unaligned boundary. This problem was + corrected in version 1.2.
      +
      +

      +
      + + +
      +

      None. Version 1.0 and 1.1 bytecode formats are identical.

      +
      + +
      +
      Valid CSS! + Valid HTML 4.01! + Reid Spencer and Chris Lattner
      + The LLVM Compiler Infrastructure
      + Last modified: $Date: 2006/08/09 05:56:40 $ +
      + + Index: llvm-www/releases/1.8/docs/CFEBuildInstrs.html diff -c /dev/null llvm-www/releases/1.8/docs/CFEBuildInstrs.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/CFEBuildInstrs.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,364 ---- + + + + + + Bootstrapping the LLVM C/C++ Front-End + + + +
      + Bootstrapping the LLVM C/C++ Front-End +
      + +
        +
      1. A Cautionary Note + +
      2. +
      3. llvm-gcc4 Instructions
      4. +
      5. llvm-gcc3 Instructions
      6. +
      7. License Information
      8. +
      + +
      +

      Written by Brian R. Gaeke and + Chris Lattner

      +
      + + + + + +
      +

      This document is intended to explain the process of building the + LLVM C/C++ front-end from its source code. You have to do this, for example, if + you are porting LLVM to a new architecture or operating system, if you are + working from Top-Of-Tree CVS/SVN, or if there is no precompiled snapshot + available.

      + +

      NOTE: This is currently a somewhat fragile, error-prone + process, and you should only try to do it if:

      + +
        +
      1. you really, really, really can't use the binaries we distribute
      2. +
      3. you are an elite GCC hacker.
      4. +
      5. you want to use the latest bits from CVS.
      6. +
      + +

      We welcome patches to help make this process simpler.

      +
      + + + + + +
      +

      If you are building LLVM and the GCC front-end under Cygwin, please note that + the LLVM and GCC makefiles do not correctly handle spaces in paths. To deal + with this issue, make sure that your LLVM and GCC source and build trees are + located in a top-level directory (like /cygdrive/c/llvm and + /cygdrive/c/llvm-cfrontend), not in a directory that contains a space + (which includes your "home directory", because it lives under the "Documents + and Settings" directory). We welcome patches to fix this issue. +

      +

      It has been found that the GCC 3.3.3 compiler provided with recent Cygwin + versions is incapable of compiling the LLVM GCC front-end correctly. If your + Cygwin + installation includes GCC 3.3.3, we strongly recommend that you download + GCC 3.4.3, build it separately, and use it for compiling the LLVM GCC front-end. + This has been + shown to work correctly.

      +

      Some versions of Cygwin utilize an experimental version of GNU binutils that + will cause the GNU ld linker to fail an assertion when linking + components of the libstdc++. It is recommended that you replace the entire + binutils package with version 2.15 such that "ld --version" responds + with

      +
      GNU ld version 2.15
      + not with:
      +
      GNU ld version 2.15.91 20040725
      +
      + + + +
      +

      If you are building LLVM and the GCC front-end under AIX, do NOT use GNU + Binutils. They are not stable under AIX and may produce incorrect and/or + invalid code. Instead, use the system assembler and linker. +

      +
      + + + + + +
      + +

      This section describes how to aquire and build llvm-gcc4, which is based on + the GCC 4.0.1 front-end. This front-end supports C, C++, Objective-C, and + Objective-C++. Note that the instructions for building this front-end are + completely different than those for building llvm-gcc3. +

      + +
        +
      1. +

        Retrieve the appropriate llvm-gcc4-x.y.source.tar.gz archive from the llvm + web site.

        +

        It is also possible to download the sources of the llvm-gcc4 front end from + a read-only mirror using subversion. To check out the code the first time use: +

        + + svn co svn://anonsvn.opensource.apple.com/svn/llvm/trunk + dst-directory + +

        After that, the code can be be updated in the destination directory using; +

        + + svn update + +

        The mirror is brought up to date every evening.

        +
      2. + +
      3. Follow the directions in the top-level README.LLVM file for up-to-date + instructions on how to build llvm-gcc4.
      4. +
      +
      + + + + + +
      +
        +
      1. Aquire llvm-gcc3 from LLVM CVS or + from a release tarball.
      2. + +
      3. Configure and build the LLVM libraries and tools. There are two ways to + do this: either with objdir == srcdir or + objdir != srcdir. It is recommended + that srcdir be the same as objdir for your LLVM tree (but note + that you should always use srcdir != objdir for llvm-gcc):

        +
          +
        • With objdir != srcdir:
          +  % cd objdir
          +  % srcdir/configure --prefix=/some/path/you/can/install/to [options...]
          +  % gmake tools-only
          +   
        • +
        • With objdir == srcdir:
          +  % cd llvm
          +  % ./configure --prefix=/some/path/you/can/install/to [options...]
          +  % gmake tools-only
          +   
        • +
        +

        This will build all of the LLVM tools and libraries. The --prefix + option defaults to /usr/local (per configure standards) but unless you are a + system administrator, you probably won't be able to install LLVM there because + of permissions. Specify a path into which LLVM can be installed (e.g. + --prefix=/home/user/llvm).

        +
      4. + +
      5. Add the directory containing the tools to your PATH.

        +
        +  % set path = ( `cd llvm/Debug/bin && pwd` $path )
        + 
      6. + +
      7. Unpack the C/C++ front-end source into cfrontend/src, either by + untar'ing a cfrontend.source.tar.gz file or checking out CVS into this + directory.

      8. + +
      9. Make "build" and "install" directories as siblings of the "src" tree:

        +
        +  % pwd
        +  /usr/local/example/cfrontend/src
        +  % cd ..
        +  % mkdir build install
        +  % set CFEINSTALL = `pwd`/install
        + 
      10. + + +
      11. Configure, build, and install the GCC front-end:

        + +

        + Linux/x86:
        + Linux/IA-64:
        + MacOS X/PowerPC (requires dlcompat library):
        + AIX/PowerPC: +

        + +
        +  % cd build
        +  % ../src/configure --prefix=$CFEINSTALL --disable-threads --disable-nls \
        +    --disable-shared --enable-languages=c,c++ --program-prefix=llvm-
        +  % gmake all; gmake install
        + 
        + +

        Cygwin/x86:

        + +
        +  % cd build
        +  % ../src/configure --prefix=$CFEINSTALL --disable-threads --disable-nls \
        +    --disable-shared --enable-languages=c,c++ --disable-c-mbchar \
        +    --program-prefix=llvm-
        +  % gmake all; gmake install
        + 
        + +

        Solaris/SPARC:

        + +

        + The GCC front-end can be configured for either SPARC V8 (32 bit) or SPARC V9 (64 + bit). This changes, among other things, the sizes of integer types and the + macros defined for conditional compilation. +

        + +

        + The SPARC V8 ABI support is more robust than the V9 ABI support and can generate + SPARC V9 code. It is highly recommended that you use the V8 ABI with LLVM, as + shown below. Also, + note that Solaris has trouble with various wide (multibyte) character + functions from C as referenced from C++, so we typically configure with + --disable-c-mbchar (cf. Bug 206). +

        + +
        +  % cd build
        +  % ../src/configure --prefix=$CFEINSTALL --disable-threads --disable-nls \
        +    --disable-shared --enable-languages=c,c++ --host=sparc-sun-solaris2.8 \
        +    --disable-c-mbchar --program-prefix=llvm-
        +  % gmake all; gmake install
        + 
        + +

        Common Problem: You may get error messages regarding the fact + that LLVM does not support inline assembly. Here are two common + fixes:

        + +
          +
        • Fix 1: If you have system header files that include + inline assembly, you may have to modify them to remove the inline + assembly and install the modified versions in + $CFEINSTALL/lib/gcc/target-triplet/3.4-llvm/include.

        • + +
        • Fix 2: If you are building the C++ front-end on a CPU we + haven't tried yet, you will probably have to edit the appropriate + version of atomicity.h under + src/libstdc++-v3/config/cpu/name-of-cpu/atomicity.h + and apply a patch so that it does not use inline assembly.
        • +
        + +

        Porting to a new architecture: If you are porting the front-end + to a new architecture or compiling in a configuration that we have + not tried previously, there are probably several changes you will have to make + to the GCC target to get it to work correctly. These include:

        + +

          +
        • Often targets include special assembler or linker flags which + gccas/gccld does not understand. In general, these can + just be removed.
        • +
        • LLVM currently does not support any floating point values other than + 32-bit and 64-bit IEEE floating point. The primary effect of this is + that you may have to map "long double" onto "double".
        • +
        • The profiling hooks in GCC do not apply at all to the LLVM front-end. + These may need to be disabled.
        • +
        • No inline assembly for position independent code. At the LLVM level, + everything is position independent.
        • +
        • We handle .init and .fini differently.
        • +
        • You may have to disable multilib support in your target. Using multilib + support causes the GCC compiler driver to add a lot of "-L" + options to the link line, which do not relate to LLVM and confuse + gccld. To disable multilibs, delete any + MULTILIB_OPTIONS lines from your target files.
        • +
        • Did we mention that we don't support inline assembly? You'll probably + have to add some fixinclude hacks to disable it in the system + headers.
        • +
        +
      12. + +
      13. Put $CFEINSTALL/bin into your PATH environment + variable.

        +
          +
        • sh: export PATH=$CFEINSTALL/bin:$PATH
        • +
        • csh: setenv PATH $CFEINSTALL/bin:$PATH
        • +
        +
      14. + +
      15. Go back into the LLVM source tree proper. Rerun configure, using + the same options as the last time. This will cause the configuration to now find + the newly built llvm-gcc and llvm-g++ executables.

      16. + +
      17. Rebuild your CVS tree. This shouldn't cause the whole thing to be + rebuilt, but it should build the runtime libraries. After the tree is + built, install the runtime libraries into your GCC front-end build tree. + These are the commands you need:

        +
        +  % gmake
        +  % gmake -C runtime install-bytecode
        + 
      18. + +
      19. Optionally, build a symbol table for the newly installed runtime + libraries. Although this step is optional, you are strongly encouraged to + do this as the symbol tables will make a significant difference in your + link times. Use the llvm-ranlib tool to do this, as follows:

        +
        +  % cd $CFEINSTALL/lib
        +  % llvm-ranlib libiberty.a
        +  % llvm-ranlib libstdc++.a
        +  % llvm-ranlib libsupc++.a
        +  % cd $CFEINSTALL/lib/gcc/target-triplet/3.4-llvm
        +  % llvm-ranlib libgcc.a
        +  % llvm-ranlib libgcov.a
        + 
        + +
      20. Test the newly-installed C frontend by one or more of the + following means:

        +
          +
        • running the feature & regression tests via make check
        • +
        • compiling and running a "hello, LLVM" program in C and C++.
        • +
        • running the tests found in the llvm-test CVS module
        • +
      21. +
      +
      + + + + +
      +

      + The LLVM GCC frontend is licensed to you under the GNU General Public License + and the GNU Lesser General Public License. Please see the files COPYING and + COPYING.LIB for more details. +

      + +

      + More information is available in the FAQ. +

      + +
      + + + +
      +
      + Valid CSS! + Valid HTML 4.01! + + Brian Gaeke
      + LLVM Compiler Infrastructure
      + Last modified: $Date: 2006/08/09 05:56:40 $ +
      + + + Index: llvm-www/releases/1.8/docs/CodeGenerator.html diff -c /dev/null llvm-www/releases/1.8/docs/CodeGenerator.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/CodeGenerator.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,1293 ---- + + + + The LLVM Target-Independent Code Generator + + + + +
      + The LLVM Target-Independent Code Generator +
      + +
        +
      1. Introduction + +
      2. +
      3. Target description classes + +
      4. +
      5. Machine code description classes + +
      6. +
      7. Target-independent code generation algorithms + +
      8. +
      9. Target-specific Implementation Notes + +
      10. + +
      + +
      +

      Written by Chris Lattner

      +
      + +
      +

      Warning: This is a work in progress.

      +
      + + + + + +
      + +

      The LLVM target-independent code generator is a framework that provides a + suite of reusable components for translating the LLVM internal representation to + the machine code for a specified target -- either in assembly form (suitable for + a static compiler) or in binary machine code format (usable for a JIT compiler). + The LLVM target-independent code generator consists of five main components:

      + +
        +
      1. Abstract target description interfaces which + capture important properties about various aspects of the machine, independently + of how they will be used. These interfaces are defined in + include/llvm/Target/.
      2. + +
      3. Classes used to represent the machine code being + generated for a target. These classes are intended to be abstract enough to + represent the machine code for any target machine. These classes are + defined in include/llvm/CodeGen/.
      4. + +
      5. Target-independent algorithms used to implement + various phases of native code generation (register allocation, scheduling, stack + frame representation, etc). This code lives in lib/CodeGen/.
      6. + +
      7. Implementations of the abstract target description + interfaces for particular targets. These machine descriptions make use of + the components provided by LLVM, and can optionally provide custom + target-specific passes, to build complete code generators for a specific target. + Target descriptions live in lib/Target/.
      8. + +
      9. The target-independent JIT components. The LLVM JIT is + completely target independent (it uses the TargetJITInfo structure to + interface for target-specific issues. The code for the target-independent + JIT lives in lib/ExecutionEngine/JIT.
      10. + +
      + +

      + Depending on which part of the code generator you are interested in working on, + different pieces of this will be useful to you. In any case, you should be + familiar with the target description and machine code representation classes. If you want to add + a backend for a new target, you will need to implement the + target description classes for your new target and understand the LLVM code representation. If you are interested in + implementing a new code generation algorithm, it + should only depend on the target-description and machine code representation + classes, ensuring that it is portable. +

      + +
      + + + + +
      + +

      The two pieces of the LLVM code generator are the high-level interface to the + code generator and the set of reusable components that can be used to build + target-specific backends. The two most important interfaces (TargetMachine and TargetData) are the only ones that are + required to be defined for a backend to fit into the LLVM system, but the others + must be defined if the reusable code generator components are going to be + used.

      + +

      This design has two important implications. The first is that LLVM can + support completely non-traditional code generation targets. For example, the C + backend does not require register allocation, instruction selection, or any of + the other standard components provided by the system. As such, it only + implements these two interfaces, and does its own thing. Another example of a + code generator like this is a (purely hypothetical) backend that converts LLVM + to the GCC RTL form and uses GCC to emit machine code for a target.

      + +

      This design also implies that it is possible to design and + implement radically different code generators in the LLVM system that do not + make use of any of the built-in components. Doing so is not recommended at all, + but could be required for radically different targets that do not fit into the + LLVM machine description model: programmable FPGAs for example.

      + +
      + + + + +
      + +

      The LLVM target-independent code generator is designed to support efficient and + quality code generation for standard register-based microprocessors. Code + generation in this model is divided into the following stages:

      + +
        +
      1. Instruction Selection - This phase + determines an efficient way to express the input LLVM code in the target + instruction set. + This stage produces the initial code for the program in the target instruction + set, then makes use of virtual registers in SSA form and physical registers that + represent any required register assignments due to target constraints or calling + conventions. This step turns the LLVM code into a DAG of target + instructions.
      2. + +
      3. Scheduling and Formation - This + phase takes the DAG of target instructions produced by the instruction selection + phase, determines an ordering of the instructions, then emits the instructions + as MachineInstrs with that ordering. Note + that we describe this in the instruction selection + section because it operates on a SelectionDAG. +
      4. + +
      5. SSA-based Machine Code Optimizations - This + optional stage consists of a series of machine-code optimizations that + operate on the SSA-form produced by the instruction selector. Optimizations + like modulo-scheduling or peephole optimization work here. +
      6. + +
      7. Register Allocation - The + target code is transformed from an infinite virtual register file in SSA form + to the concrete register file used by the target. This phase introduces spill + code and eliminates all virtual register references from the program.
      8. + +
      9. Prolog/Epilog Code Insertion - Once the + machine code has been generated for the function and the amount of stack space + required is known (used for LLVM alloca's and spill slots), the prolog and + epilog code for the function can be inserted and "abstract stack location + references" can be eliminated. This stage is responsible for implementing + optimizations like frame-pointer elimination and stack packing.
      10. + +
      11. Late Machine Code Optimizations - Optimizations + that operate on "final" machine code can go here, such as spill code scheduling + and peephole optimizations.
      12. + +
      13. Code Emission - The final stage actually + puts out the code for the current function, either in the target assembler + format or in machine code.
      14. + +
      + +

      + The code generator is based on the assumption that the instruction selector will + use an optimal pattern matching selector to create high-quality sequences of + native instructions. Alternative code generator designs based on pattern + expansion and + aggressive iterative peephole optimization are much slower. This design + permits efficient compilation (important for JIT environments) and + aggressive optimization (used when generating code offline) by allowing + components of varying levels of sophistication to be used for any step of + compilation.

      + +

      + In addition to these stages, target implementations can insert arbitrary + target-specific passes into the flow. For example, the X86 target uses a + special pass to handle the 80x87 floating point stack architecture. Other + targets with unusual requirements can be supported with custom passes as needed. +

      + +
      + + + + + +
      + +

      The target description classes require a detailed description of the target + architecture. These target descriptions often have a large amount of common + information (e.g., an add instruction is almost identical to a + sub instruction). + In order to allow the maximum amount of commonality to be factored out, the LLVM + code generator uses the TableGen tool to + describe big chunks of the target machine, which allows the use of + domain-specific and target-specific abstractions to reduce the amount of + repetition. +

      + +

      As LLVM continues to be developed and refined, we plan to move more and more + of the target description to be in .td form. Doing so gives us a + number of advantages. The most important is that it makes it easier to port + LLVM, because it reduces the amount of C++ code that has to be written and the + surface area of the code generator that needs to be understood before someone + can get in an get something working. Second, it is also important to us because + it makes it easier to change things: in particular, if tables and other things + are all emitted by tblgen, we only need to change one place (tblgen) to update + all of the targets to a new interface.

      + +
      + + + + + +
      + +

      The LLVM target description classes (which are located in the + include/llvm/Target directory) provide an abstract description of the + target machine; independent of any particular client. These classes are + designed to capture the abstract properties of the target (such as the + instructions and registers it has), and do not incorporate any particular pieces + of code generation algorithms.

      + +

      All of the target description classes (except the TargetData class) are designed to be subclassed by + the concrete target implementation, and have virtual methods implemented. To + get to these implementations, the TargetMachine class provides accessors that + should be implemented by the target.

      + +
      + + + + +
      + +

      The TargetMachine class provides virtual methods that are used to + access the target-specific implementations of the various target description + classes via the get*Info methods (getInstrInfo, + getRegisterInfo, getFrameInfo, etc.). This class is + designed to be specialized by + a concrete target implementation (e.g., X86TargetMachine) which + implements the various virtual methods. The only required target description + class is the TargetData class, but if the + code generator components are to be used, the other interfaces should be + implemented as well.

      + +
      + + + + + +
      + +

      The TargetData class is the only required target description class, + and it is the only class that is not extensible (you cannot derived a new + class from it). TargetData specifies information about how the target + lays out memory for structures, the alignment requirements for various data + types, the size of pointers in the target, and whether the target is + little-endian or big-endian.

      + +
      + + + + +
      + +

      The TargetLowering class is used by SelectionDAG based instruction + selectors primarily to describe how LLVM code should be lowered to SelectionDAG + operations. Among other things, this class indicates: +

      • an initial register class to use for various ValueTypes
      • +
      • which operations are natively supported by the target machine
      • +
      • the return type of setcc operations
      • +
      • the type to use for shift amounts
      • +
      • various high-level characteristics, like whether it is profitable to turn + division by a constant into a multiplication sequence
      • +

    + +
    + + + + +
    + +

    The MRegisterInfo class (which will eventually be renamed to + TargetRegisterInfo) is used to describe the register file of the + target and any interactions between the registers.

    + +

    Registers in the code generator are represented in the code generator by + unsigned numbers. Physical registers (those that actually exist in the target + description) are unique small numbers, and virtual registers are generally + large. Note that register #0 is reserved as a flag value.

    + +

    Each register in the processor description has an associated + TargetRegisterDesc entry, which provides a textual name for the register + (used for assembly output and debugging dumps) and a set of aliases (used to + indicate that one register overlaps with another). +

    + +

    In addition to the per-register description, the MRegisterInfo class + exposes a set of processor specific register classes (instances of the + TargetRegisterClass class). Each register class contains sets of + registers that have the same properties (for example, they are all 32-bit + integer registers). Each SSA virtual register created by the instruction + selector has an associated register class. When the register allocator runs, it + replaces virtual registers with a physical register in the set.

    + +

    + The target-specific implementations of these classes is auto-generated from a TableGen description of the register file. +

    + +
    + + + + +
    +

    The TargetInstrInfo class is used to describe the machine + instructions supported by the target. It is essentially an array of + TargetInstrDescriptor objects, each of which describes one + instruction the target supports. Descriptors define things like the mnemonic + for the opcode, the number of operands, the list of implicit register uses + and defs, whether the instruction has certain target-independent properties + (accesses memory, is commutable, etc), and holds any target-specific flags.

    +
    + + + + +
    +

    The TargetFrameInfo class is used to provide information about the + stack frame layout of the target. It holds the direction of stack growth, + the known stack alignment on entry to each function, and the offset to the + locals area. The offset to the local area is the offset from the stack + pointer on function entry to the first location where function data (local + variables, spill locations) can be stored.

    +
    + + + + +
    +

    +

    The TargetSubtarget class is used to provide information about the + specific chip set being targeted. A sub-target informs code generation of + which instructions are supported, instruction latencies and instruction + execution itinerary; i.e., which processing units are used, in what order, and + for how long. +

    +
    + + + + + + + + + +
    + +

    + At the high-level, LLVM code is translated to a machine specific representation + formed out of MachineFunction, + MachineBasicBlock, and MachineInstr instances + (defined in include/llvm/CodeGen). This representation is completely target + agnostic, representing instructions in their most abstract form: an opcode and a + series of operands. This representation is designed to support both SSA + representation for machine code, as well as a register allocated, non-SSA form. +

    + +
    + + + + +
    + +

    Target machine instructions are represented as instances of the + MachineInstr class. This class is an extremely abstract way of + representing machine instructions. In particular, it only keeps track of + an opcode number and a set of operands.

    + +

    The opcode number is a simple unsigned number that only has meaning to a + specific backend. All of the instructions for a target should be defined in + the *InstrInfo.td file for the target. The opcode enum values + are auto-generated from this description. The MachineInstr class does + not have any information about how to interpret the instruction (i.e., what the + semantics of the instruction are): for that you must refer to the + TargetInstrInfo class.

    + +

    The operands of a machine instruction can be of several different types: + they can be a register reference, constant integer, basic block reference, etc. + In addition, a machine operand should be marked as a def or a use of the value + (though only registers are allowed to be defs).

    + +

    By convention, the LLVM code generator orders instruction operands so that + all register definitions come before the register uses, even on architectures + that are normally printed in other orders. For example, the SPARC add + instruction: "add %i1, %i2, %i3" adds the "%i1", and "%i2" registers + and stores the result into the "%i3" register. In the LLVM code generator, + the operands should be stored as "%i3, %i1, %i2": with the destination + first.

    + +

    Keeping destination (definition) operands at the beginning of the operand + list has several advantages. In particular, the debugging printer will print + the instruction like this:

    + +
    +   %r3 = add %i1, %i2
    + 
    + +

    If the first operand is a def, and it is also easier to create instructions whose only def is the first + operand.

    + +
    + + + + +
    + +

    Machine instructions are created by using the BuildMI functions, + located in the include/llvm/CodeGen/MachineInstrBuilder.h file. The + BuildMI functions make it easy to build arbitrary machine + instructions. Usage of the BuildMI functions look like this: +

    + +
    +   // Create a 'DestReg = mov 42' (rendered in X86 assembly as 'mov DestReg, 42')
    +   // instruction.  The '1' specifies how many operands will be added.
    +   MachineInstr *MI = BuildMI(X86::MOV32ri, 1, DestReg).addImm(42);
    + 
    +   // Create the same instr, but insert it at the end of a basic block.
    +   MachineBasicBlock &MBB = ...
    +   BuildMI(MBB, X86::MOV32ri, 1, DestReg).addImm(42);
    + 
    +   // Create the same instr, but insert it before a specified iterator point.
    +   MachineBasicBlock::iterator MBBI = ...
    +   BuildMI(MBB, MBBI, X86::MOV32ri, 1, DestReg).addImm(42);
    + 
    +   // Create a 'cmp Reg, 0' instruction, no destination reg.
    +   MI = BuildMI(X86::CMP32ri, 2).addReg(Reg).addImm(0);
    +   // Create an 'sahf' instruction which takes no operands and stores nothing.
    +   MI = BuildMI(X86::SAHF, 0);
    + 
    +   // Create a self looping branch instruction.
    +   BuildMI(MBB, X86::JNE, 1).addMBB(&MBB);
    + 
    + +

    + The key thing to remember with the BuildMI functions is that you have + to specify the number of operands that the machine instruction will take. This + allows for efficient memory allocation. You also need to specify if operands + default to be uses of values, not definitions. If you need to add a definition + operand (other than the optional destination register), you must explicitly + mark it as such. +

    + +
    + + + + +
    + +

    One important issue that the code generator needs to be aware of is the + presence of fixed registers. In particular, there are often places in the + instruction stream where the register allocator must arrange for a + particular value to be in a particular register. This can occur due to + limitations of the instruction set (e.g., the X86 can only do a 32-bit divide + with the EAX/EDX registers), or external factors like calling + conventions. In any case, the instruction selector should emit code that + copies a virtual register into or out of a physical register when needed.

    + +

    For example, consider this simple LLVM example:

    + +
    +   int %test(int %X, int %Y) {
    +     %Z = div int %X, %Y
    +     ret int %Z
    +   }
    + 
    + +

    The X86 instruction selector produces this machine code for the div + and ret (use + "llc X.bc -march=x86 -print-machineinstrs" to get this):

    + +
    +         ;; Start of div
    +         %EAX = mov %reg1024           ;; Copy X (in reg1024) into EAX
    +         %reg1027 = sar %reg1024, 31
    +         %EDX = mov %reg1027           ;; Sign extend X into EDX
    +         idiv %reg1025                 ;; Divide by Y (in reg1025)
    +         %reg1026 = mov %EAX           ;; Read the result (Z) out of EAX
    + 
    +         ;; Start of ret
    +         %EAX = mov %reg1026           ;; 32-bit return value goes in EAX
    +         ret
    + 
    + +

    By the end of code generation, the register allocator has coalesced + the registers and deleted the resultant identity moves, producing the + following code:

    + +
    +         ;; X is in EAX, Y is in ECX
    +         mov %EAX, %EDX
    +         sar %EDX, 31
    +         idiv %ECX
    +         ret 
    + 
    + +

    This approach is extremely general (if it can handle the X86 architecture, + it can handle anything!) and allows all of the target specific + knowledge about the instruction stream to be isolated in the instruction + selector. Note that physical registers should have a short lifetime for good + code generation, and all physical registers are assumed dead on entry and + exit of basic blocks (before register allocation). Thus if you need a value + to be live across basic block boundaries, it must live in a virtual + register.

    + +
    + + + + +
    + +

    MachineInstr's are initially selected in SSA-form, and + are maintained in SSA-form until register allocation happens. For the most + part, this is trivially simple since LLVM is already in SSA form: LLVM PHI nodes + become machine code PHI nodes, and virtual registers are only allowed to have a + single definition.

    + +

    After register allocation, machine code is no longer in SSA-form, as there + are no virtual registers left in the code.

    + +
    + + + + +
    + +

    The MachineBasicBlock class contains a list of machine instructions + (MachineInstr instances). It roughly corresponds to + the LLVM code input to the instruction selector, but there can be a one-to-many + mapping (i.e. one LLVM basic block can map to multiple machine basic blocks). + The MachineBasicBlock class has a "getBasicBlock" method, which returns + the LLVM basic block that it comes from. +

    + +
    + + + + +
    + +

    The MachineFunction class contains a list of machine basic blocks + (MachineBasicBlock instances). It corresponds + one-to-one with the LLVM function input to the instruction selector. In + addition to a list of basic blocks, the MachineFunction contains a + the MachineConstantPool, MachineFrameInfo, MachineFunctionInfo, + SSARegMap, and a set of live in and live out registers for the function. See + MachineFunction.h for more information. +

    + +
    + + + + + + + +
    + +

    This section documents the phases described in the high-level design of the code generator. It + explains how they work and some of the rationale behind their design.

    + +
    + + + + +
    +

    + Instruction Selection is the process of translating LLVM code presented to the + code generator into target-specific machine instructions. There are several + well-known ways to do this in the literature. In LLVM there are two main forms: + the SelectionDAG based instruction selector framework and an old-style 'simple' + instruction selector (which effectively peephole selects each LLVM instruction + into a series of machine instructions). We recommend that all targets use the + SelectionDAG infrastructure. +

    + +

    Portions of the DAG instruction selector are generated from the target + description files (*.td) files. Eventually, we aim for the entire + instruction selector to be generated from these .td files.

    +
    + + + + +
    + +

    + The SelectionDAG provides an abstraction for code representation in a way that + is amenable to instruction selection using automatic techniques + (e.g. dynamic-programming based optimal pattern matching selectors), It is also + well suited to other phases of code generation; in particular, + instruction scheduling (SelectionDAG's are very close to scheduling DAGs + post-selection). Additionally, the SelectionDAG provides a host representation + where a large variety of very-low-level (but target-independent) + optimizations may be + performed: ones which require extensive information about the instructions + efficiently supported by the target. +

    + +

    + The SelectionDAG is a Directed-Acyclic-Graph whose nodes are instances of the + SDNode class. The primary payload of the SDNode is its + operation code (Opcode) that indicates what operation the node performs and + the operands to the operation. + The various operation node types are described at the top of the + include/llvm/CodeGen/SelectionDAGNodes.h file.

    + +

    Although most operations define a single value, each node in the graph may + define multiple values. For example, a combined div/rem operation will define + both the dividend and the remainder. Many other situations require multiple + values as well. Each node also has some number of operands, which are edges + to the node defining the used value. Because nodes may define multiple values, + edges are represented by instances of the SDOperand class, which is + a <SDNode, unsigned> pair, indicating the node and result + value being used, respectively. Each value produced by an SDNode has an + associated MVT::ValueType, indicating what type the value is. +

    + +

    + SelectionDAGs contain two different kinds of values: those that represent data + flow and those that represent control flow dependencies. Data values are simple + edges with an integer or floating point value type. Control edges are + represented as "chain" edges which are of type MVT::Other. These edges provide + an ordering between nodes that have side effects (such as + loads/stores/calls/return/etc). All nodes that have side effects should take a + token chain as input and produce a new one as output. By convention, token + chain inputs are always operand #0, and chain results are always the last + value produced by an operation.

    + +

    + A SelectionDAG has designated "Entry" and "Root" nodes. The Entry node is + always a marker node with an Opcode of ISD::EntryToken. The Root node is the + final side-effecting node in the token chain. For example, in a single basic + block function, this would be the return node. +

    + +

    + One important concept for SelectionDAGs is the notion of a "legal" vs. "illegal" + DAG. A legal DAG for a target is one that only uses supported operations and + supported types. On a 32-bit PowerPC, for example, a DAG with any values of i1, + i8, i16, + or i64 type would be illegal, as would a DAG that uses a SREM or UREM operation. + The legalize + phase is responsible for turning an illegal DAG into a legal DAG. +

    +
    + + + + +
    + +

    + SelectionDAG-based instruction selection consists of the following steps: +

    + +
      +
    1. Build initial DAG - This stage performs + a simple translation from the input LLVM code to an illegal SelectionDAG. +
    2. +
    3. Optimize SelectionDAG - This stage + performs simple optimizations on the SelectionDAG to simplify it and + recognize meta instructions (like rotates and div/rem pairs) for + targets that support these meta operations. This makes the resultant code + more efficient and the 'select instructions from DAG' phase (below) simpler. +
    4. +
    5. Legalize SelectionDAG - This stage + converts the illegal SelectionDAG to a legal SelectionDAG, by eliminating + unsupported operations and data types.
    6. +
    7. Optimize SelectionDAG (#2) - This + second run of the SelectionDAG optimized the newly legalized DAG, to + eliminate inefficiencies introduced by legalization.
    8. +
    9. Select instructions from DAG - Finally, + the target instruction selector matches the DAG operations to target + instructions. This process translates the target-independent input DAG into + another DAG of target instructions.
    10. +
    11. SelectionDAG Scheduling and Formation + - The last phase assigns a linear order to the instructions in the + target-instruction DAG and emits them into the MachineFunction being + compiled. This step uses traditional prepass scheduling techniques.
    12. +
    + +

    After all of these steps are complete, the SelectionDAG is destroyed and the + rest of the code generation passes are run.

    + +

    One great way to visualize what is going on here is to take advantage of a + few LLC command line options. In particular, the -view-isel-dags + option pops up a window with the SelectionDAG input to the Select phase for all + of the code compiled (if you only get errors printed to the console while using + this, you probably need to configure + your system to add support for it). The -view-sched-dags option + views the SelectionDAG output from the Select phase and input to the Scheduler + phase. +

    +
    + + + + +
    + +

    + The initial SelectionDAG is naively peephole expanded from the LLVM input by + the SelectionDAGLowering class in the SelectionDAGISel.cpp file. The + intent of this pass is to expose as much low-level, target-specific details + to the SelectionDAG as possible. This pass is mostly hard-coded (e.g. an LLVM + add turns into an SDNode add while a geteelementptr is expanded into the obvious + arithmetic). This pass requires target-specific hooks to lower calls and + returns, varargs, etc. For these features, the TargetLowering interface is + used. +

    + +
    + + + + +
    + +

    The Legalize phase is in charge of converting a DAG to only use the types and + operations that are natively supported by the target. This involves two major + tasks:

    + +
      +
    1. Convert values of unsupported types to values of supported types.

      +

      There are two main ways of doing this: converting small types to + larger types ("promoting"), and breaking up large integer types + into smaller ones ("expanding"). For example, a target might require + that all f32 values are promoted to f64 and that all i1/i8/i16 values + are promoted to i32. The same target might require that all i64 values + be expanded into i32 values. These changes can insert sign and zero + extensions as + needed to make sure that the final code has the same behavior as the + input.

      +

      A target implementation tells the legalizer which types are supported + (and which register class to use for them) by calling the + "addRegisterClass" method in its TargetLowering constructor.

      +
    2. + +
    3. Eliminate operations that are not supported by the target.

      +

      Targets often have weird constraints, such as not supporting every + operation on every supported datatype (e.g. X86 does not support byte + conditional moves and PowerPC does not support sign-extending loads from + a 16-bit memory location). Legalize takes care by open-coding + another sequence of operations to emulate the operation ("expansion"), by + promoting to a larger type that supports the operation + (promotion), or using a target-specific hook to implement the + legalization (custom).

      +

      A target implementation tells the legalizer which operations are not + supported (and which of the above three actions to take) by calling the + "setOperationAction" method in its TargetLowering constructor.

      +
    4. +
    + +

    + Prior to the existance of the Legalize pass, we required that every + target selector supported and handled every + operator and type even if they are not natively supported. The introduction of + the Legalize phase allows all of the + cannonicalization patterns to be shared across targets, and makes it very + easy to optimize the cannonicalized code because it is still in the form of + a DAG. +

    + +
    + + + + +
    + +

    + The SelectionDAG optimization phase is run twice for code generation: once + immediately after the DAG is built and once after legalization. The first run + of the pass allows the initial code to be cleaned up (e.g. performing + optimizations that depend on knowing that the operators have restricted type + inputs). The second run of the pass cleans up the messy code generated by the + Legalize pass, which allows Legalize to be very simple (it can focus on making + code legal instead of focusing on generating good and legal code). +

    + +

    + One important class of optimizations performed is optimizing inserted sign and + zero extension instructions. We currently use ad-hoc techniques, but could move + to more rigorous techniques in the future. Here are some good + papers on the subject:

    + +

    + "Widening + integer arithmetic"
    + Kevin Redwine and Norman Ramsey
    + International Conference on Compiler Construction (CC) 2004 +

    + + +

    + "Effective + sign extension elimination"
    + Motohiro Kawahito, Hideaki Komatsu, and Toshio Nakatani
    + Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language Design + and Implementation. +

    + +
    + + + + +
    + +

    The Select phase is the bulk of the target-specific code for instruction + selection. This phase takes a legal SelectionDAG as input, + pattern matches the instructions supported by the target to this DAG, and + produces a new DAG of target code. For example, consider the following LLVM + fragment:

    + +
    +    %t1 = add float %W, %X
    +    %t2 = mul float %t1, %Y
    +    %t3 = add float %t2, %Z
    + 
    + +

    This LLVM code corresponds to a SelectionDAG that looks basically like this: +

    + +
    +   (fadd:f32 (fmul:f32 (fadd:f32 W, X), Y), Z)
    + 
    + +

    If a target supports floating point multiply-and-add (FMA) operations, one + of the adds can be merged with the multiply. On the PowerPC, for example, the + output of the instruction selector might look like this DAG:

    + +
    +   (FMADDS (FADDS W, X), Y, Z)
    + 
    + +

    + The FMADDS instruction is a ternary instruction that multiplies its first two + operands and adds the third (as single-precision floating-point numbers). The + FADDS instruction is a simple binary single-precision add instruction. To + perform this pattern match, the PowerPC backend includes the following + instruction definitions: +

    + +
    + def FMADDS : AForm_1<59, 29,
    +                     (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRC, F4RC:$FRB),
    +                     "fmadds $FRT, $FRA, $FRC, $FRB",
    +                     [(set F4RC:$FRT, (fadd (fmul F4RC:$FRA, F4RC:$FRC),
    +                                            F4RC:$FRB))]>;
    + def FADDS : AForm_2<59, 21,
    +                     (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRB),
    +                     "fadds $FRT, $FRA, $FRB",
    +                     [(set F4RC:$FRT, (fadd F4RC:$FRA, F4RC:$FRB))]>;
    + 
    + +

    The portion of the instruction definition in bold indicates the pattern used + to match the instruction. The DAG operators (like fmul/fadd) + are defined in the lib/Target/TargetSelectionDAG.td file. + "F4RC" is the register class of the input and result values.

    + +

    The TableGen DAG instruction selector generator reads the instruction + patterns in the .td and automatically builds parts of the pattern matching code + for your target. It has the following strengths:

    + +
      +
    • At compiler-compiler time, it analyzes your instruction patterns and tells + you if your patterns make sense or not.
    • +
    • It can handle arbitrary constraints on operands for the pattern match. In + particular, it is straight-forward to say things like "match any immediate + that is a 13-bit sign-extended value". For examples, see the + immSExt16 and related tblgen classes in the PowerPC backend.
    • +
    • It knows several important identities for the patterns defined. For + example, it knows that addition is commutative, so it allows the + FMADDS pattern above to match "(fadd X, (fmul Y, Z))" as + well as "(fadd (fmul X, Y), Z)", without the target author having + to specially handle this case.
    • +
    • It has a full-featured type-inferencing system. In particular, you should + rarely have to explicitly tell the system what type parts of your patterns + are. In the FMADDS case above, we didn't have to tell tblgen that all of + the nodes in the pattern are of type 'f32'. It was able to infer and + propagate this knowledge from the fact that F4RC has type 'f32'.
    • +
    • Targets can define their own (and rely on built-in) "pattern fragments". + Pattern fragments are chunks of reusable patterns that get inlined into your + patterns during compiler-compiler time. For example, the integer "(not x)" + operation is actually defined as a pattern fragment that expands as + "(xor x, -1)", since the SelectionDAG does not have a native 'not' + operation. Targets can define their own short-hand fragments as they see + fit. See the definition of 'not' and 'ineg' for examples.
    • +
    • In addition to instructions, targets can specify arbitrary patterns that + map to one or more instructions, using the 'Pat' class. For example, + the PowerPC has no way to load an arbitrary integer immediate into a + register in one instruction. To tell tblgen how to do this, it defines: + +
      +     // Arbitrary immediate support.  Implement in terms of LIS/ORI.
      +     def : Pat<(i32 imm:$imm),
      +               (ORI (LIS (HI16 imm:$imm)), (LO16 imm:$imm))>;
      +     
      + + If none of the single-instruction patterns for loading an immediate into a + register match, this will be used. This rule says "match an arbitrary i32 + immediate, turning it into an ORI ('or a 16-bit immediate') and an LIS + ('load 16-bit immediate, where the immediate is shifted to the left 16 + bits') instruction". To make this work, the LO16/HI16 node transformations + are used to manipulate the input immediate (in this case, take the high or + low 16-bits of the immediate). +
    • +
    • While the system does automate a lot, it still allows you to write custom + C++ code to match special cases, in case there is something that is hard + to express.
    • +
    + +

    + While it has many strengths, the system currently has some limitations, + primarily because it is a work in progress and is not yet finished: +

    + +
      +
    • Overall, there is no way to define or match SelectionDAG nodes that define + multiple values (e.g. ADD_PARTS, LOAD, CALL, etc). This is the biggest + reason that you currently still have to write custom C++ code for + your instruction selector.
    • +
    • There is no great way to support match complex addressing modes yet. In the + future, we will extend pattern fragments to allow them to define multiple + values (e.g. the four operands of the X86 addressing + mode). In addition, we'll extend fragments so that a fragment can match + multiple different patterns.
    • +
    • We don't automatically infer flags like isStore/isLoad yet.
    • +
    • We don't automatically generate the set of supported registers and + operations for the Legalizer yet.
    • +
    • We don't have a way of tying in custom legalized nodes yet.
    • +
    + +

    Despite these limitations, the instruction selector generator is still quite + useful for most of the binary and logical operations in typical instruction + sets. If you run into any problems or can't figure out how to do something, + please let Chris know!

    + +
    + + + + +
    + +

    The scheduling phase takes the DAG of target instructions from the selection + phase and assigns an order. The scheduler can pick an order depending on + various constraints of the machines (i.e. order for minimal register pressure or + try to cover instruction latencies). Once an order is established, the DAG is + converted to a list of MachineInstrs and the + Selection DAG is destroyed. +

    + +

    Note that this phase is logically separate from the instruction selection + phase, but is tied to it closely in the code because it operates on + SelectionDAGs.

    + +
    + + + + +
    + +
      +
    1. Optional function-at-a-time selection.
    2. +
    3. Auto-generate entire selector from .td file.
    4. + +
    + +
    + + + +

    To Be Written

    + + +

    To Be Written

    + + +

    To Be Written

    + + +

    To Be Written

    + + + + + + + +
    + +
    + + + + + +
    +

    For the JIT or .o file writer

    +
    + + + + + + +
    + +

    This section of the document explains features or design decisions that + are specific to the code generator for a particular target.

    + +
    + + + + + +
    + +

    + The X86 code generator lives in the lib/Target/X86 directory. This + code generator currently targets a generic P6-like processor. As such, it + produces a few P6-and-above instructions (like conditional moves), but it does + not make use of newer features like MMX or SSE. In the future, the X86 backend + will have sub-target support added for specific processor families and + implementations.

    + +
    + + + + +
    +

    + The following are the known target triples that are supported by the X86 + backend. This is not an exhaustive list, but it would be useful to add those + that people test. +

    + +
      +
    • i686-pc-linux-gnu - Linux
    • +
    • i386-unknown-freebsd5.3 - FreeBSD 5.3
    • +
    • i686-pc-cygwin - Cygwin on Win32
    • +
    • i686-pc-mingw32 - MingW on Win32
    • +
    • i686-apple-darwin* - Apple Darwin on X86
    • +
    + +
    + + + + +
    + +

    The x86 has a very flexible way of accessing memory. It is capable of + forming memory addresses of the following expression directly in integer + instructions (which use ModR/M addressing):

    + +
    +    Base+[1,2,4,8]*IndexReg+Disp32
    + 
    + +

    In order to represent this, LLVM tracks no less than 4 operands for each + memory operand of this form. This means that the "load" form of 'mov' has the + following MachineOperands in this order:

    + +
    + Index:        0     |    1        2       3           4
    + Meaning:   DestReg, | BaseReg,  Scale, IndexReg, Displacement
    + OperandTy: VirtReg, | VirtReg, UnsImm, VirtReg,   SignExtImm
    + 
    + +

    Stores, and all other instructions, treat the four memory operands in the + same way, in the same order.

    + +
    + + + + +
    + +

    + An instruction name consists of the base name, a default operand size, and a + a character per operand with an optional special size. For example:

    + +

    + ADD8rr -> add, 8-bit register, 8-bit register
    + IMUL16rmi -> imul, 16-bit register, 16-bit memory, 16-bit immediate
    + IMUL16rmi8 -> imul, 16-bit register, 16-bit memory, 8-bit immediate
    + MOVSX32rm16 -> movsx, 32-bit register, 16-bit memory +

    + +
    + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/CodingStandards.html diff -c /dev/null llvm-www/releases/1.8/docs/CodingStandards.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/CodingStandards.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,679 ---- + + + + + A Few Coding Standards + + + +
    + A Few Coding Standards +
    + +
      +
    1. Introduction
    2. +
    3. Mechanical Source Issues +
        +
      1. Source Code Formatting +
          +
        1. Commenting
        2. +
        3. Comment Formatting
        4. +
        5. #include Style
        6. +
        7. Source Code Width
        8. +
        9. Use Spaces Instead of Tabs
        10. +
        11. Indent Code Consistently
        12. +
      2. +
      3. Compiler Issues +
          +
        1. Treat Compiler Warnings Like + Errors
        2. +
        3. Write Portable Code
        4. +
        5. Use of class/struct Keywords
        6. +
      4. +
    4. +
    5. Style Issues +
        +
      1. The High Level Issues +
          +
        1. A Public Header File is a + Module
        2. +
        3. #include as Little as Possible
        4. +
        5. Keep "internal" Headers + Private
        6. +
      2. +
      3. The Low Level Issues +
          +
        1. Assert Liberally
        2. +
        3. Do not use 'using namespace std'
        4. +
        5. Provide a virtual method anchor for clases in headers
        6. +
        7. Prefer Preincrement
        8. +
        9. Avoid std::endl
        10. +
      4. +
    6. +
    7. See Also
    8. +
    + +
    +

    Written by Chris Lattner

    +
    + + + + + + +
    + +

    This document attempts to describe a few coding standards that are being used + in the LLVM source tree. Although no coding standards should be regarded as + absolute requirements to be followed in all instances, coding standards can be + useful.

    + +

    This document intentionally does not prescribe fixed standards for religious + issues such as brace placement and space usage. For issues like this, follow + the golden rule:

    + +
    + +

    If you are adding a significant body of source to a + project, feel free to use whatever style you are most comfortable with. If you + are extending, enhancing, or bug fixing already implemented code, use the style + that is already being used so that the source is uniform and easy to + follow.

    + +
    + +

    The ultimate goal of these guidelines is the increase readability and + maintainability of our common source base. If you have suggestions for topics to + be included, please mail them to Chris.

    + +
    + + + + + + + + + + + +
    + +

    Comments are one critical part of readability and maintainability. Everyone + knows they should comment, so should you. Although we all should probably + comment our code more than we do, there are a few very critical places that + documentation is very useful:

    + + File Headers + +

    Every source file should have a header on it that + describes the basic purpose of the file. If a file does not have a header, it + should not be checked into CVS. Most source trees will probably have a standard + file header format. The standard format for the LLVM source tree looks like + this:

    + +
    +
    + //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
    + // 
    + //                     The LLVM Compiler Infrastructure
    + //
    + // This file was developed by the LLVM research group and is distributed under
    + // the University of Illinois Open Source License. See LICENSE.TXT for details.
    + // 
    + //===----------------------------------------------------------------------===//
    + //
    + // This file contains the declaration of the Instruction class, which is the
    + // base class for all of the VM instructions.
    + //
    + //===----------------------------------------------------------------------===//
    + 
    +
    + +

    A few things to note about this particular format: The "-*- C++ + -*-" string on the first line is there to tell Emacs that the source file + is a C++ file, not a C file (Emacs assumes .h files are C files by default). + Note that this tag is not necessary in .cpp files. The name of the file is also + on the first line, along with a very short description of the purpose of the + file. This is important when printing out code and flipping though lots of + pages.

    + +

    The next section in the file is a concise note that defines the license that + the file is released under. This makes it perfectly clear what terms the source + code can be distributed under.

    + +

    The main body of the description does not have to be very long in most cases. + Here it's only two lines. If an algorithm is being implemented or something + tricky is going on, a reference to the paper where it is published should be + included, as well as any notes or "gotchas" in the code to watch out for.

    + + Class overviews + +

    Classes are one fundamental part of a good object oriented design. As such, + a class definition should have a comment block that explains what the class is + used for... if it's not obvious. If it's so completely obvious your grandma + could figure it out, it's probably safe to leave it out. Naming classes + something sane goes a long ways towards avoiding writing documentation.

    + + + Method information + +

    Methods defined in a class (as well as any global functions) should also be + documented properly. A quick note about what it does any a description of the + borderline behaviour is all that is necessary here (unless something + particularly tricky or insideous is going on). The hope is that people can + figure out how to use your interfaces without reading the code itself... that is + the goal metric.

    + +

    Good things to talk about here are what happens when something unexpected + happens: does the method return null? Abort? Format your hard disk?

    + +
    + + + + +
    + +

    In general, prefer C++ style (//) comments. They take less space, + require less typing, don't have nesting problems, etc. There are a few cases + when it is useful to use C style (/* */) comments however:

    + +
      +
    1. When writing a C code: Obviously if you are writing C code, use C style + comments.
    2. +
    3. When writing a header file that may be #included by a C source + file.
    4. +
    5. When writing a source file that is used by a tool that only accepts C + style comments.
    6. +
    + +

    To comment out a large block of code, use #if 0 and #endif. + These nest properly and are better behaved in general than C style comments.

    + +
    + + + + +
    + +

    Immediately after the header file comment (and + include guards if working on a header file), the minimal list of #includes required by the + file should be listed. We prefer these #includes to be listed in this + order:

    + +
      +
    1. Main Module header
    2. +
    3. Local/Private Headers
    4. +
    5. llvm/*
    6. +
    7. llvm/Analysis/*
    8. +
    9. llvm/Assembly/*
    10. +
    11. llvm/Bytecode/*
    12. +
    13. llvm/CodeGen/*
    14. +
    15. ...
    16. +
    17. Support/*
    18. +
    19. Config/*
    20. +
    21. System #includes
    22. +
    + +

    ... and each catagory should be sorted by name.

    + +

    The "Main Module Header" file applies to .cpp file + which implement an interface defined by a .h file. This #include + should always be included first regardless of where it lives on the file + system. By including a header file first in the .cpp files that implement the + interfaces, we ensure that the header does not have any hidden dependencies + which are not explicitly #included in the header, but should be. It is also a + form of documentation in the .cpp file to indicate where the interfaces it + implements are defined.

    + +
    + + + + +
    + +

    Write your code to fit within 80 columns of text. This helps those of us who + like to print out code and look at your code in an xterm without resizing + it.

    + +
    + + + + +
    + +

    In all cases, prefer spaces to tabs in source files. People have different + prefered indentation levels, and different styles of indentation that they + like... this is fine. What isn't is that different editors/viewers expand tabs + out to different tab stops. This can cause your code to look completely + unreadable, and it is not worth dealing with.

    + +

    As always, follow the Golden Rule above: follow the + style of existing code if your are modifying and extending it. If you like four + spaces of indentation, DO NOT do that in the middle of a chunk of code + with two spaces of indentation. Also, do not reindent a whole source file: it + makes for incredible diffs that are absolutely worthless.

    + +
    + + + + +
    + +

    Okay, your first year of programming you were told that indentation is + important. If you didn't believe and internalize this then, now is the time. + Just do it.

    + +
    + + + + + + + + + +
    + +

    If your code has compiler warnings in it, something is wrong: you aren't + casting values correctly, your have "questionable" constructs in your code, or + you are doing something legitimately wrong. Compiler warnings can cover up + legitimate errors in output and make dealing with a translation unit + difficult.

    + +

    It is not possible to prevent all warnings from all compilers, nor is it + desirable. Instead, pick a standard compiler (like gcc) that provides + a good thorough set of warnings, and stick to them. At least in the case of + gcc, it is possible to work around any spurious errors by changing the + syntax of the code slightly. For example, an warning that annoys me occurs when + I write code like this:

    + +
    +
    + if (V = getValue()) {
    +   ...
    + }
    + 
    +
    + +

    gcc will warn me that I probably want to use the == + operator, and that I probably mistyped it. In most cases, I haven't, and I + really don't want the spurious errors. To fix this particular problem, I + rewrite the code like this:

    + +
    +
    + if ((V = getValue())) {
    +   ...
    + }
    + 
    +
    + +

    ...which shuts gcc up. Any gcc warning that annoys you can + be fixed by massaging the code appropriately.

    + +

    These are the gcc warnings that I prefer to enable: -Wall + -Winline -W -Wwrite-strings -Wno-unused

    + +
    + + + + +
    + +

    In almost all cases, it is possible and within reason to write completely + portable code. If there are cases where it isn't possible to write portable + code, isolate it behind a well defined (and well documented) interface.

    + +

    In practice, this means that you shouldn't assume much about the host + compiler, including its support for "high tech" features like partial + specialization of templates. In fact, Visual C++ 6 could be an important target + for our work in the future, and we don't want to have to rewrite all of our code + to support it.

    + +
    + + + +
    + +

    In C++, the class and struct keywords can be used almost + interchangeably. The only difference is when they are used to declare a class: + class makes all members private by default while struct makes + all members public by default.

    + +

    Unfortunately, not all compilers follow the rules and some will generate + different symbols based on whether class or struct was used to + declare the symbol. This can lead to problems at link time.

    + +

    So, the rule for LLVM is to always use the class keyword, unless + all members are public, in which case struct is allowed.

    + +
    + + + + + + + + + + + + + +
    + +

    C++ doesn't do too well in the modularity department. There is no real + encapsulation or data hiding (unless you use expensive protocol classes), but it + is what we have to work with. When you write a public header file (in the LLVM + source tree, they live in the top level "include" directory), you are defining a + module of functionality.

    + +

    Ideally, modules should be completely independent of each other, and their + header files should only include the absolute minimum number of headers + possible. A module is not just a class, a function, or a namespace: it's a collection + of these that defines an interface. This interface may be several + functions, classes or data structures, but the important issue is how they work + together.

    + +

    In general, a module should be implemented with one or more .cpp + files. Each of these .cpp files should include the header that defines + their interface first. This ensure that all of the dependences of the module + header have been properly added to the module header itself, and are not + implicit. System headers should be included after user headers for a + translation unit.

    + +
    + + + + +
    + +

    #include hurts compile time performance. Don't do it unless you + have to, especially in header files.

    + +

    But wait, sometimes you need to have the definition of a class to use it, or + to inherit from it. In these cases go ahead and #include that header + file. Be aware however that there are many cases where you don't need to have + the full definition of a class. If you are using a pointer or reference to a + class, you don't need the header file. If you are simply returning a class + instance from a prototyped function or method, you don't need it. In fact, for + most cases, you simply don't need the definition of a class... and not + #include'ing speeds up compilation.

    + +

    It is easy to try to go too overboard on this recommendation, however. You + must include all of the header files that you are using, either directly + or indirectly (through another header file). To make sure that you don't + accidently forget to include a header file in your module header, make sure to + include your module header first in the implementation file (as mentioned + above). This way there won't be any hidden dependencies that you'll find out + about later...

    + +
    + + + + +
    + +

    Many modules have a complex implementation that causes them to use more than + one implementation (.cpp) file. It is often tempting to put the + internal communication interface (helper classes, extra functions, etc) in the + public module header file. Don't do this.

    + +

    If you really need to do something like this, put a private header file in + the same directory as the source files, and include it locally. This ensures + that your private interface remains private and undisturbed by outsiders.

    + +

    Note however, that it's okay to put extra implementation methods a public + class itself... just make them private (or protected), and all is well.

    + +
    + + + + + + + + +
    + +

    Use the "assert" function to its fullest. Check all of your + preconditions and assumptions, you never know when a bug (not neccesarily even + yours) might be caught early by an assertion, which reduces debugging time + dramatically. The "<cassert>" header file is probably already + included by the header files you are using, so it doesn't cost anything to use + it.

    + +

    To further assist with debugging, make sure to put some kind of error message + in the assertion statement (which is printed if the assertion is tripped). This + helps the poor debugging make sense of why an assertion is being made and + enforced, and hopefully what to do about it. Here is one complete example:

    + +
    +
    + inline Value *getOperand(unsigned i) { 
    +   assert(i < Operands.size() && "getOperand() out of range!");
    +   return Operands[i]; 
    + }
    + 
    +
    + +

    Here are some examples:

    + +
    +
    + assert(Ty->isPointerType() && "Can't allocate a non pointer type!");
    + 
    + assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");
    + 
    + assert(idx < getNumSuccessors() && "Successor # out of range!");
    + 
    + assert(V1.getType() == V2.getType() && "Constant types must be identical!");
    + 
    + assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
    + 
    +
    + +

    You get the idea...

    + +
    + + + + +
    +

    In LLVM, we prefer to explicitly prefix all identifiers from the standard + namespace with an "std::" prefix, rather than rely on "using namespace std;". +

    + +

    In header files, adding a 'using namespace XXX' directive pollutes the + namespace of any source file that includes the header. This is clearly a bad + thing.

    + +

    In implementation files (e.g. .cpp files) the rule is more of a stylistic + rule, but is still important. Basically, using explicit namespace prefixes + makes + the code more clear - because it is immediately obvious what facilities + are being used and where they are coming from - and more portable - + because namespace clashes cannot occur between LLVM code and other namespaces. + The portability rule is important because different standard library + implementations expose different symbols (potentially ones they shouldn't) and + future revisions to the C++ standard will add more symbols to the std + namespace. As such, we never 'using namespace std;' in LLVM.

    + +

    The exception to the general rule (i.e. it's not an exception for the std + namespace) is for implementation files. For example, all of the code in the + LLVM project implements code that lives in the 'llvm' namespace. As such, it + is ok, and actually more clear, for the .cpp files to have a 'using namespace + llvm' directive at their top, after the #includes. The general form of this + rule is that any .cpp file that implements code in any namespace may use that + namespace (and its parents), but should not use any others.

    + +
    + + + + +
    + +

    If a class is defined in a header file and has a v-table (either it has + virtual methods or it derives from classes with virtual methods), it must + always have at least one out-of-line virtual method in the class. Without + this, the compiler will copy the vtable and RTTI into every .o file that + #includes the header, bloating .o file sizes and increasing link times. +

    + +
    + + + + + +
    + +

    Hard fast rule: Preincrement (++X) may be no slower than + postincrement (X++) and could very well be a lot faster than it. Use + preincrementation whenever possible.

    + +

    The semantics of postincrement include making a copy of the value being + incremented, returning it, and then preincrementing the "work value". For + primitive types, this isn't a big deal... but for iterators, it can be a huge + issue (for example, some iterators contains stack and set objects in them... + copying an iterator could invoke the copy ctor's of these as well). In general, + get in the habit of always using preincrement, and you won't have a problem.

    + +
    + + + + +
    + +

    The std::endl modifier, when used with iostreams outputs a newline + to the output stream specified. In addition to doing this, however, it also + flushes the output stream. In other words, these are equivalent:

    + +
    +
    + std::cout << std::endl;
    + std::cout << '\n' << std::flush;
    + 
    +
    + +

    Most of the time, you probably have no reason to flush the output stream, so + it's better to use a literal '\n'.

    + +
    + + +
    + See Also +
    + + +
    + +

    A lot of these comments and recommendations have been culled for other + sources. Two particularly important books for our work are:

    + +
      + +
    1. Effective + C++ by Scott Meyers. There is an online version of the book (only some + chapters though) available as well. Also + interesting and useful are "More Effective C++" and "Effective STL" by the same + author.
    2. + +
    3. Large-Scale C++ + Software Design by John Lakos
    4. + +
    + +

    If you get some free time, and you haven't read them: do so, you might learn + something.

    + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/CommandLine.html diff -c /dev/null llvm-www/releases/1.8/docs/CommandLine.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/CommandLine.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,1930 ---- + + + + + CommandLine 2.0 Library Manual + + + + +
    + CommandLine 2.0 Library Manual +
    + +
      +
    1. Introduction
    2. + +
    3. Quick Start Guide +
        +
      1. Boolean Arguments
      2. +
      3. Argument Aliases
      4. +
      5. Selecting an alternative from a + set of possibilities
      6. +
      7. Named alternatives
      8. +
      9. Parsing a list of options
      10. +
      11. Collecting options as a set of flags
      12. +
      13. Adding freeform text to help output
      14. +
    4. + +
    5. Reference Guide +
        +
      1. Positional Arguments +
      2. + +
      3. Internal vs External Storage
      4. + +
      5. Option Attributes
      6. + +
      7. Option Modifiers +
      8. + +
      9. Top-Level Classes and Functions +
      10. + +
      11. Builtin parsers +
      12. +
    6. +
    7. Extension Guide +
        +
      1. Writing a custom parser
      2. +
      3. Exploiting external storage
      4. +
      5. Dynamically adding command line + options
      6. +
    8. +
    + +
    +

    Written by Chris Lattner

    +
    + + + + + +
    + +

    This document describes the CommandLine argument processing library. It will + show you how to use it, and what it can do. The CommandLine library uses a + declarative approach to specifying the command line options that your program + takes. By default, these options declarations implicitly hold the value parsed + for the option declared (of course this can be + changed).

    + +

    Although there are a lot of command line argument parsing libraries + out there in many different languages, none of them fit well with what I needed. + By looking at the features and problems of other libraries, I designed the + CommandLine library to have the following features:

    + +
      +
    1. Speed: The CommandLine library is very quick and uses little resources. The + parsing time of the library is directly proportional to the number of arguments + parsed, not the the number of options recognized. Additionally, command line + argument values are captured transparently into user defined global variables, + which can be accessed like any other variable (and with the same + performance).
    2. + +
    3. Type Safe: As a user of CommandLine, you don't have to worry about + remembering the type of arguments that you want (is it an int? a string? a + bool? an enum?) and keep casting it around. Not only does this help prevent + error prone constructs, it also leads to dramatically cleaner source code.
    4. + +
    5. No subclasses required: To use CommandLine, you instantiate variables that + correspond to the arguments that you would like to capture, you don't subclass a + parser. This means that you don't have to write any boilerplate + code.
    6. + +
    7. Globally accessible: Libraries can specify command line arguments that are + automatically enabled in any tool that links to the library. This is possible + because the application doesn't have to keep a "list" of arguments to pass to + the parser. This also makes supporting dynamically + loaded options trivial.
    8. + +
    9. Cleaner: CommandLine supports enum and other types directly, meaning that + there is less error and more security built into the library. You don't have to + worry about whether your integral command line argument accidentally got + assigned a value that is not valid for your enum type.
    10. + +
    11. Powerful: The CommandLine library supports many different types of + arguments, from simple boolean flags to scalars arguments (strings, integers, enums, doubles), to lists of + arguments. This is possible because CommandLine is...
    12. + +
    13. Extensible: It is very simple to add a new argument type to CommandLine. + Simply specify the parser that you want to use with the command line option when + you declare it. Custom parsers are no problem.
    14. + +
    15. Labor Saving: The CommandLine library cuts down on the amount of grunt work + that you, the user, have to do. For example, it automatically provides a + --help option that shows the available command line options for your + tool. Additionally, it does most of the basic correctness checking for + you.
    16. + +
    17. Capable: The CommandLine library can handle lots of different forms of + options often found in real programs. For example, positional arguments, ls style grouping options (to allow processing 'ls + -lad' naturally), ld style prefix + options (to parse '-lmalloc -L/usr/lib'), and interpreter style options.
    18. + +
    + +

    This document will hopefully let you jump in and start using CommandLine in + your utility quickly and painlessly. Additionally it should be a simple + reference manual to figure out how stuff works. If it is failing in some area + (or you want an extension to the library), nag the author, Chris Lattner.

    + +
    + + + + + +
    + +

    This section of the manual runs through a simple CommandLine'ification of a + basic compiler tool. This is intended to show you how to jump into using the + CommandLine library in your own program, and show you some of the cool things it + can do.

    + +

    To start out, you need to include the CommandLine header file into your + program:

    + +
    +   #include "llvm/Support/CommandLine.h"
    + 
    + +

    Additionally, you need to add this as the first line of your main + program:

    + +
    + int main(int argc, char **argv) {
    +   cl::ParseCommandLineOptions(argc, argv);
    +   ...
    + }
    + 
    + +

    ... which actually parses the arguments and fills in the variable + declarations.

    + +

    Now that you are ready to support command line arguments, we need to tell the + system which ones we want, and what type of argument they are. The CommandLine + library uses a declarative syntax to model command line arguments with the + global variable declarations that capture the parsed values. This means that + for every command line option that you would like to support, there should be a + global variable declaration to capture the result. For example, in a compiler, + we would like to support the unix standard '-o <filename>' option + to specify where to put the output. With the CommandLine library, this is + represented like this:

    + + +
    + cl::opt<string> OutputFilename("o", cl::desc("Specify output filename"), cl::value_desc("filename"));
    + 
    + +

    This declares a global variable "OutputFilename" that is used to + capture the result of the "o" argument (first parameter). We specify + that this is a simple scalar option by using the "cl::opt" template (as opposed to the "cl::list template), and tell the CommandLine library + that the data type that we are parsing is a string.

    + +

    The second and third parameters (which are optional) are used to specify what + to output for the "--help" option. In this case, we get a line that + looks like this:

    + +
    + USAGE: compiler [options]
    + 
    + OPTIONS:
    +   -help             - display available options (--help-hidden for more)
    +   -o <filename>     - Specify output filename
    + 
    + +

    Because we specified that the command line option should parse using the + string data type, the variable declared is automatically usable as a + real string in all contexts that a normal C++ string object may be used. For + example:

    + +
    +   ...
    +   ofstream Output(OutputFilename.c_str());
    +   if (Out.good()) ...
    +   ...
    + 
    + +

    There are many different options that you can use to customize the command + line option handling library, but the above example shows the general interface + to these options. The options can be specified in any order, and are specified + with helper functions like cl::desc(...), so + there are no positional dependencies to remember. The available options are + discussed in detail in the Reference Guide.

    + +

    Continuing the example, we would like to have our compiler take an input + filename as well as an output filename, but we do not want the input filename to + be specified with a hyphen (ie, not -filename.c). To support this + style of argument, the CommandLine library allows for positional arguments to be specified for the program. + These positional arguments are filled with command line parameters that are not + in option form. We use this feature like this:

    + +
    + cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
    + 
    + +

    This declaration indicates that the first positional argument should be + treated as the input filename. Here we use the cl::init option to specify an initial value for the + command line option, which is used if the option is not specified (if you do not + specify a cl::init modifier for an option, then + the default constructor for the data type is used to initialize the value). + Command line options default to being optional, so if we would like to require + that the user always specify an input filename, we would add the cl::Required flag, and we could eliminate the + cl::init modifier, like this:

    + +
    + cl::opt<string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::Required);
    + 
    + +

    Again, the CommandLine library does not require the options to be specified + in any particular order, so the above declaration is equivalent to:

    + +
    + cl::opt<string> InputFilename(cl::Positional, cl::Required, cl::desc("<input file>"));
    + 
    + +

    By simply adding the cl::Required flag, + the CommandLine library will automatically issue an error if the argument is not + specified, which shifts all of the command line option verification code out of + your application into the library. This is just one example of how using flags + can alter the default behaviour of the library, on a per-option basis. By + adding one of the declarations above, the --help option synopsis is now + extended to:

    + +
    + USAGE: compiler [options] <input file>
    + 
    + OPTIONS:
    +   -help             - display available options (--help-hidden for more)
    +   -o <filename>     - Specify output filename
    + 
    + +

    ... indicating that an input filename is expected.

    + +
    + + + + +
    + +

    In addition to input and output filenames, we would like the compiler example + to support three boolean flags: "-f" to force overwriting of the output + file, "--quiet" to enable quiet mode, and "-q" for backwards + compatibility with some of our users. We can support these by declaring options + of boolean type like this:

    + +
    + cl::opt<bool> Force ("f", cl::desc("Overwrite output files"));
    + cl::opt<bool> Quiet ("quiet", cl::desc("Don't print informational messages"));
    + cl::opt<bool> Quiet2("q", cl::desc("Don't print informational messages"), cl::Hidden);
    + 
    + +

    This does what you would expect: it declares three boolean variables + ("Force", "Quiet", and "Quiet2") to recognize these + options. Note that the "-q" option is specified with the "cl::Hidden" flag. This modifier prevents it + from being shown by the standard "--help" output (note that it is still + shown in the "--help-hidden" output).

    + +

    The CommandLine library uses a different parser + for different data types. For example, in the string case, the argument passed + to the option is copied literally into the content of the string variable... we + obviously cannot do that in the boolean case, however, so we must use a smarter + parser. In the case of the boolean parser, it allows no options (in which case + it assigns the value of true to the variable), or it allows the values + "true" or "false" to be specified, allowing any of the + following inputs:

    + +
    +  compiler -f          # No value, 'Force' == true
    +  compiler -f=true     # Value specified, 'Force' == true
    +  compiler -f=TRUE     # Value specified, 'Force' == true
    +  compiler -f=FALSE    # Value specified, 'Force' == false
    + 
    + +

    ... you get the idea. The bool parser just turns + the string values into boolean values, and rejects things like 'compiler + -f=foo'. Similarly, the float, double, and int parsers work + like you would expect, using the 'strtol' and 'strtod' C + library calls to parse the string value into the specified data type.

    + +

    With the declarations above, "compiler --help" emits this:

    + +
    + USAGE: compiler [options] <input file>
    + 
    + OPTIONS:
    +   -f     - Overwrite output files
    +   -o     - Override output filename
    +   -quiet - Don't print informational messages
    +   -help  - display available options (--help-hidden for more)
    + 
    + +

    and "opt --help-hidden" prints this:

    + +
    + USAGE: compiler [options] <input file>
    + 
    + OPTIONS:
    +   -f     - Overwrite output files
    +   -o     - Override output filename
    +   -q     - Don't print informational messages
    +   -quiet - Don't print informational messages
    +   -help  - display available options (--help-hidden for more)
    + 
    + +

    This brief example has shown you how to use the 'cl::opt' class to parse simple scalar command line + arguments. In addition to simple scalar arguments, the CommandLine library also + provides primitives to support CommandLine option aliases, + and lists of options.

    + +
    + + + + +
    + +

    So far, the example works well, except for the fact that we need to check the + quiet condition like this now:

    + +
    + ...
    +   if (!Quiet && !Quiet2) printInformationalMessage(...);
    + ...
    + 
    + +

    ... which is a real pain! Instead of defining two values for the same + condition, we can use the "cl::alias" class to make the "-q" + option an alias for the "-quiet" option, instead of providing + a value itself:

    + +
    + cl::opt<bool> Force ("f", cl::desc("Overwrite output files"));
    + cl::opt<bool> Quiet ("quiet", cl::desc("Don't print informational messages"));
    + cl::alias     QuietA("q", cl::desc("Alias for -quiet"), cl::aliasopt(Quiet));
    + 
    + +

    The third line (which is the only one we modified from above) defines a + "-q alias that updates the "Quiet" variable (as specified by + the cl::aliasopt modifier) whenever it is + specified. Because aliases do not hold state, the only thing the program has to + query is the Quiet variable now. Another nice feature of aliases is + that they automatically hide themselves from the -help output + (although, again, they are still visible in the --help-hidden + output).

    + +

    Now the application code can simply use:

    + +
    + ...
    +   if (!Quiet) printInformationalMessage(...);
    + ...
    + 
    + +

    ... which is much nicer! The "cl::alias" + can be used to specify an alternative name for any variable type, and has many + uses.

    + +
    + + + + +
    + +

    So far, we have seen how the CommandLine library handles builtin types like + std::string, bool and int, but how does it handle + things it doesn't know about, like enums or 'int*'s?

    + +

    The answer is that it uses a table driven generic parser (unless you specify + your own parser, as described in the Extension + Guide). This parser maps literal strings to whatever type is required, and + requires you to tell it what this mapping should be.

    + +

    Lets say that we would like to add four optimization levels to our + optimizer, using the standard flags "-g", "-O0", + "-O1", and "-O2". We could easily implement this with boolean + options like above, but there are several problems with this strategy:

    + +
      +
    1. A user could specify more than one of the options at a time, for example, + "opt -O3 -O2". The CommandLine library would not be able to catch this + erroneous input for us.
    2. + +
    3. We would have to test 4 different variables to see which ones are set.
    4. + +
    5. This doesn't map to the numeric levels that we want... so we cannot easily + see if some level >= "-O1" is enabled.
    6. + +
    + +

    To cope with these problems, we can use an enum value, and have the + CommandLine library fill it in with the appropriate level directly, which is + used like this:

    + +
    + enum OptLevel {
    +   g, O1, O2, O3
    + };
    + 
    + cl::opt<OptLevel> OptimizationLevel(cl::desc("Choose optimization level:"),
    +   cl::values(
    +     clEnumVal(g , "No optimizations, enable debugging"),
    +     clEnumVal(O1, "Enable trivial optimizations"),
    +     clEnumVal(O2, "Enable default optimizations"),
    +     clEnumVal(O3, "Enable expensive optimizations"),
    +    clEnumValEnd));
    + 
    + ...
    +   if (OptimizationLevel >= O2) doPartialRedundancyElimination(...);
    + ...
    + 
    + +

    This declaration defines a variable "OptimizationLevel" of the + "OptLevel" enum type. This variable can be assigned any of the values + that are listed in the declaration (Note that the declaration list must be + terminated with the "clEnumValEnd" argument!). The CommandLine + library enforces + that the user can only specify one of the options, and it ensure that only valid + enum values can be specified. The "clEnumVal" macros ensure that the + command line arguments matched the enum values. With this option added, our + help output now is:

    + +
    + USAGE: compiler [options] <input file>
    + 
    + OPTIONS:
    +   Choose optimization level:
    +     -g          - No optimizations, enable debugging
    +     -O1         - Enable trivial optimizations
    +     -O2         - Enable default optimizations
    +     -O3         - Enable expensive optimizations
    +   -f            - Overwrite output files
    +   -help         - display available options (--help-hidden for more)
    +   -o <filename> - Specify output filename
    +   -quiet        - Don't print informational messages
    + 
    + +

    In this case, it is sort of awkward that flag names correspond directly to + enum names, because we probably don't want a enum definition named "g" + in our program. Because of this, we can alternatively write this example like + this:

    + +
    + enum OptLevel {
    +   Debug, O1, O2, O3
    + };
    + 
    + cl::opt<OptLevel> OptimizationLevel(cl::desc("Choose optimization level:"),
    +   cl::values(
    +    clEnumValN(Debug, "g", "No optimizations, enable debugging"),
    +     clEnumVal(O1        , "Enable trivial optimizations"),
    +     clEnumVal(O2        , "Enable default optimizations"),
    +     clEnumVal(O3        , "Enable expensive optimizations"),
    +    clEnumValEnd));
    + 
    + ...
    +   if (OptimizationLevel == Debug) outputDebugInfo(...);
    + ...
    + 
    + +

    By using the "clEnumValN" macro instead of "clEnumVal", we + can directly specify the name that the flag should get. In general a direct + mapping is nice, but sometimes you can't or don't want to preserve the mapping, + which is when you would use it.

    + +
    + + + + +
    + +

    Another useful argument form is a named alternative style. We shall use this + style in our compiler to specify different debug levels that can be used. + Instead of each debug level being its own switch, we want to support the + following options, of which only one can be specified at a time: + "--debug-level=none", "--debug-level=quick", + "--debug-level=detailed". To do this, we use the exact same format as + our optimization level flags, but we also specify an option name. For this + case, the code looks like this:

    + +
    + enum DebugLev {
    +   nodebuginfo, quick, detailed
    + };
    + 
    + // Enable Debug Options to be specified on the command line
    + cl::opt<DebugLev> DebugLevel("debug_level", cl::desc("Set the debugging level:"),
    +   cl::values(
    +     clEnumValN(nodebuginfo, "none", "disable debug information"),
    +      clEnumVal(quick,               "enable quick debug information"),
    +      clEnumVal(detailed,            "enable detailed debug information"),
    +     clEnumValEnd));
    + 
    + +

    This definition defines an enumerated command line variable of type "enum + DebugLev", which works exactly the same way as before. The difference here + is just the interface exposed to the user of your program and the help output by + the "--help" option:

    + +
    + USAGE: compiler [options] <input file>
    + 
    + OPTIONS:
    +   Choose optimization level:
    +     -g          - No optimizations, enable debugging
    +     -O1         - Enable trivial optimizations
    +     -O2         - Enable default optimizations
    +     -O3         - Enable expensive optimizations
    +   -debug_level  - Set the debugging level:
    +     =none       - disable debug information
    +     =quick      - enable quick debug information
    +     =detailed   - enable detailed debug information
    +   -f            - Overwrite output files
    +   -help         - display available options (--help-hidden for more)
    +   -o <filename> - Specify output filename
    +   -quiet        - Don't print informational messages
    + 
    + +

    Again, the only structural difference between the debug level declaration and + the optimization level declaration is that the debug level declaration includes + an option name ("debug_level"), which automatically changes how the + library processes the argument. The CommandLine library supports both forms so + that you can choose the form most appropriate for your application.

    + +
    + + + + +
    + +

    Now that we have the standard run of the mill argument types out of the way, + lets get a little wild and crazy. Lets say that we want our optimizer to accept + a list of optimizations to perform, allowing duplicates. For example, we + might want to run: "compiler -dce -constprop -inline -dce -strip". In + this case, the order of the arguments and the number of appearances is very + important. This is what the "cl::list" + template is for. First, start by defining an enum of the optimizations that you + would like to perform:

    + +
    + enum Opts {
    +   // 'inline' is a C++ keyword, so name it 'inlining'
    +   dce, constprop, inlining, strip
    + };
    + 
    + +

    Then define your "cl::list" variable:

    + +
    + cl::list<Opts> OptimizationList(cl::desc("Available Optimizations:"),
    +   cl::values(
    +     clEnumVal(dce               , "Dead Code Elimination"),
    +     clEnumVal(constprop         , "Constant Propagation"),
    +    clEnumValN(inlining, "inline", "Procedure Integration"),
    +     clEnumVal(strip             , "Strip Symbols"),
    +   clEnumValEnd));
    + 
    + +

    This defines a variable that is conceptually of the type + "std::vector<enum Opts>". Thus, you can access it with standard + vector methods:

    + +
    +   for (unsigned i = 0; i != OptimizationList.size(); ++i)
    +     switch (OptimizationList[i])
    +        ...
    + 
    + +

    ... to iterate through the list of options specified.

    + +

    Note that the "cl::list" template is + completely general and may be used with any data types or other arguments that + you can use with the "cl::opt" template. One + especially useful way to use a list is to capture all of the positional + arguments together if there may be more than one specified. In the case of a + linker, for example, the linker takes several '.o' files, and needs to + capture them into a list. This is naturally specified as:

    + +
    + ...
    + cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<Input files>"), cl::OneOrMore);
    + ...
    + 
    + +

    This variable works just like a "vector<string>" object. As + such, accessing the list is simple, just like above. In this example, we used + the cl::OneOrMore modifier to inform the + CommandLine library that it is an error if the user does not specify any + .o files on our command line. Again, this just reduces the amount of + checking we have to do.

    + +
    + + + + +
    + +

    Instead of collecting sets of options in a list, it is also possible to + gather information for enum values in a bit vector. The represention used by + the cl::bits class is an unsigned + integer. An enum value is represented by a 0/1 in the enum's ordinal value bit + position. 1 indicating that the enum was specified, 0 otherwise. As each + specified value is parsed, the resulting enum's bit is set in the option's bit + vector:

    + +
    +   bits |= 1 << (unsigned)enum;
    + 
    + +

    Options that are specified multiple times are redundant. Any instances after + the first are discarded.

    + +

    Reworking the above list example, we could replace + cl::list with cl::bits:

    + +
    + cl::bits<Opts> OptimizationBits(cl::desc("Available Optimizations:"),
    +   cl::values(
    +     clEnumVal(dce               , "Dead Code Elimination"),
    +     clEnumVal(constprop         , "Constant Propagation"),
    +    clEnumValN(inlining, "inline", "Procedure Integration"),
    +     clEnumVal(strip             , "Strip Symbols"),
    +   clEnumValEnd));
    + 
    + +

    To test to see if constprop was specified, we can use the + cl:bits::isSet function:

    + +
    +   if (OptimizationBits.isSet(constprop)) {
    +     ...
    +   }
    + 
    + +

    It's also possible to get the raw bit vector using the + cl::bits::getBits function:

    + +
    +   unsigned bits = OptimizationBits.getBits();
    + 
    + +

    Finally, if external storage is used, then the location specified must be of + type unsigned. In all other ways a cl::bits option is morally equivalent to a cl::list option.

    + +
    + + + + + +
    + +

    As our program grows and becomes more mature, we may decide to put summary + information about what it does into the help output. The help output is styled + to look similar to a Unix man page, providing concise information about + a program. Unix man pages, however often have a description about what + the program does. To add this to your CommandLine program, simply pass a third + argument to the cl::ParseCommandLineOptions + call in main. This additional argument is then printed as the overview + information for your program, allowing you to include any additional information + that you want. For example:

    + +
    + int main(int argc, char **argv) {
    +   cl::ParseCommandLineOptions(argc, argv, " CommandLine compiler example\n\n"
    +                               "  This program blah blah blah...\n");
    +   ...
    + }
    + 
    + +

    would yield the help output:

    + +
    + OVERVIEW: CommandLine compiler example
    + 
    +   This program blah blah blah...
    + 
    + USAGE: compiler [options] <input file>
    + 
    + OPTIONS:
    +   ...
    +   -help             - display available options (--help-hidden for more)
    +   -o <filename>     - Specify output filename
    + 
    + +
    + + + + + + +
    + +

    Now that you know the basics of how to use the CommandLine library, this + section will give you the detailed information you need to tune how command line + options work, as well as information on more "advanced" command line option + processing capabilities.

    + +
    + + + + +
    + +

    Positional arguments are those arguments that are not named, and are not + specified with a hyphen. Positional arguments should be used when an option is + specified by its position alone. For example, the standard Unix grep + tool takes a regular expression argument, and an optional filename to search + through (which defaults to standard input if a filename is not specified). + Using the CommandLine library, this would be specified as:

    + +
    + cl::opt<string> Regex   (cl::Positional, cl::desc("<regular expression>"), cl::Required);
    + cl::opt<string> Filename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
    + 
    + +

    Given these two option declarations, the --help output for our grep + replacement would look like this:

    + +
    + USAGE: spiffygrep [options] <regular expression> <input file>
    + 
    + OPTIONS:
    +   -help - display available options (--help-hidden for more)
    + 
    + +

    ... and the resultant program could be used just like the standard + grep tool.

    + +

    Positional arguments are sorted by their order of construction. This means + that command line options will be ordered according to how they are listed in a + .cpp file, but will not have an ordering defined if the positional arguments + are defined in multiple .cpp files. The fix for this problem is simply to + define all of your positional arguments in one .cpp file.

    + +
    + + + + + +
    + +

    Sometimes you may want to specify a value to your positional argument that + starts with a hyphen (for example, searching for '-foo' in a file). At + first, you will have trouble doing this, because it will try to find an argument + named '-foo', and will fail (and single quotes will not save you). + Note that the system grep has the same problem:

    + +
    +   $ spiffygrep '-foo' test.txt
    +   Unknown command line argument '-foo'.  Try: spiffygrep --help'
    + 
    +   $ grep '-foo' test.txt
    +   grep: illegal option -- f
    +   grep: illegal option -- o
    +   grep: illegal option -- o
    +   Usage: grep -hblcnsviw pattern file . . .
    + 
    + +

    The solution for this problem is the same for both your tool and the system + version: use the '--' marker. When the user specifies '--' on + the command line, it is telling the program that all options after the + '--' should be treated as positional arguments, not options. Thus, we + can use it like this:

    + +
    +   $ spiffygrep -- -foo test.txt
    +     ...output...
    + 
    + +
    + + + +
    +

    Sometimes an option can affect or modify the meaning of another option. For + example, consider gcc's -x LANG option. This tells + gcc to ignore the suffix of subsequent positional arguments and force + the file to be interpreted as if it contained source code in language + LANG. In order to handle this properly , you need to know the + absolute position of each argument, especially those in lists, so their + interaction(s) can be applied correctly. This is also useful for options like + -llibname which is actually a positional argument that starts with + a dash.

    +

    So, generally, the problem is that you have two cl::list variables + that interact in some way. To ensure the correct interaction, you can use the + cl::list::getPosition(optnum) method. This method returns the + absolute position (as found on the command line) of the optnum + item in the cl::list.

    +

    The idiom for usage is like this:

    + +
    +   static cl::list<std::string> Files(cl::Positional, cl::OneOrMore);
    +   static cl::listlt;std::string> Libraries("l", cl::ZeroOrMore);
    + 
    +   int main(int argc, char**argv) {
    +     // ...
    +     std::vector<std::string>::iterator fileIt = Files.begin();
    +     std::vector<std::string>::iterator libIt  = Libraries.begin();
    +     unsigned libPos = 0, filePos = 0;
    +     while ( 1 ) {
    +       if ( libIt != Libraries.end() )
    +         libPos = Libraries.getPosition( libIt - Libraries.begin() );
    +       else
    +         libPos = 0;
    +       if ( fileIt != Files.end() )
    +         filePos = Files.getPosition( fileIt - Files.begin() );
    +       else
    +         filePos = 0;
    + 
    +       if ( filePos != 0 && (libPos == 0 || filePos < libPos) ) {
    +         // Source File Is next
    +         ++fileIt;
    +       }
    +       else if ( libPos != 0 && (filePos == 0 || libPos < filePos) ) {
    +         // Library is next
    +         ++libIt;
    +       }
    +       else
    +         break; // we're done with the list
    +     }
    +   }
    + +

    Note that, for compatibility reasons, the cl::opt also supports an + unsigned getPosition() option that will provide the absolute position + of that option. You can apply the same approach as above with a + cl::opt and a cl::list option as you can with two lists.

    +
    + + + + +
    + +

    The cl::ConsumeAfter formatting option is + used to construct programs that use "interpreter style" option processing. With + this style of option processing, all arguments specified after the last + positional argument are treated as special interpreter arguments that are not + interpreted by the command line argument.

    + +

    As a concrete example, lets say we are developing a replacement for the + standard Unix Bourne shell (/bin/sh). To run /bin/sh, first + you specify options to the shell itself (like -x which turns on trace + output), then you specify the name of the script to run, then you specify + arguments to the script. These arguments to the script are parsed by the bourne + shell command line option processor, but are not interpreted as options to the + shell itself. Using the CommandLine library, we would specify this as:

    + +
    + cl::opt<string> Script(cl::Positional, cl::desc("<input script>"), cl::init("-"));
    + cl::list<string>  Argv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
    + cl::opt<bool>    Trace("x", cl::desc("Enable trace output"));
    + 
    + +

    which automatically provides the help output:

    + +
    + USAGE: spiffysh [options] <input script> <program arguments>...
    + 
    + OPTIONS:
    +   -help - display available options (--help-hidden for more)
    +   -x    - Enable trace output
    + 
    + +

    At runtime, if we run our new shell replacement as `spiffysh -x test.sh + -a -x -y bar', the Trace variable will be set to true, the + Script variable will be set to "test.sh", and the + Argv list will contain ["-a", "-x", "-y", "bar"], because they + were specified after the last positional argument (which is the script + name).

    + +

    There are several limitations to when cl::ConsumeAfter options can + be specified. For example, only one cl::ConsumeAfter can be specified + per program, there must be at least one positional + argument specified, there must not be any cl::list + positional arguments, and the cl::ConsumeAfter option should be a cl::list option.

    + +
    + + + + +
    + +

    By default, all command line options automatically hold the value that they + parse from the command line. This is very convenient in the common case, + especially when combined with the ability to define command line options in the + files that use them. This is called the internal storage model.

    + +

    Sometimes, however, it is nice to separate the command line option processing + code from the storage of the value parsed. For example, lets say that we have a + '-debug' option that we would like to use to enable debug information + across the entire body of our program. In this case, the boolean value + controlling the debug code should be globally accessable (in a header file, for + example) yet the command line option processing code should not be exposed to + all of these clients (requiring lots of .cpp files to #include + CommandLine.h).

    + +

    To do this, set up your .h file with your option, like this for example:

    + +
    +
    + // DebugFlag.h - Get access to the '-debug' command line option
    + //
    + 
    + // DebugFlag - This boolean is set to true if the '-debug' command line option
    + // is specified.  This should probably not be referenced directly, instead, use
    + // the DEBUG macro below.
    + //
    + extern bool DebugFlag;
    + 
    + // DEBUG macro - This macro should be used by code to emit debug information.
    + // In the '-debug' option is specified on the command line, and if this is a
    + // debug build, then the code specified as the option to the macro will be
    + // executed.  Otherwise it will not be.  Example:
    + //
    + // DEBUG(std::cerr << "Bitset contains: " << Bitset << "\n");
    + //
    + #ifdef NDEBUG
    + #define DEBUG(X)
    + #else
    + #define DEBUG(X) do { if (DebugFlag) { X; } } while (0)
    + #endif
    + 
    +
    + +

    This allows clients to blissfully use the DEBUG() macro, or the + DebugFlag explicitly if they want to. Now we just need to be able to + set the DebugFlag boolean when the option is set. To do this, we pass + an additial argument to our command line argument processor, and we specify + where to fill in with the cl::location + attribute:

    + +
    +
    + bool DebugFlag;                  // the actual value
    + static cl::opt<bool, true>       // The parser
    + Debug("debug", cl::desc("Enable debug output"), cl::Hidden, cl::location(DebugFlag));
    + 
    +
    + +

    In the above example, we specify "true" as the second argument to + the cl::opt template, indicating that the + template should not maintain a copy of the value itself. In addition to this, + we specify the cl::location attribute, so + that DebugFlag is automatically set.

    + +
    + + + + +
    + +

    This section describes the basic attributes that you can specify on + options.

    + +
      + +
    • The option name attribute (which is required for all options, except positional options) specifies what the option name is. + This option is specified in simple double quotes: + +
      + cl::opt<bool> Quiet("quiet");
      + 
      + +
    • + +
    • The cl::desc attribute specifies a + description for the option to be shown in the --help output for the + program.
    • + +
    • The cl::value_desc attribute + specifies a string that can be used to fine tune the --help output for + a command line option. Look here for an + example.
    • + +
    • The cl::init attribute specifies an + inital value for a scalar option. If this attribute is + not specified then the command line option value defaults to the value created + by the default constructor for the type. Warning: If you specify both + cl::init and cl::location for an option, + you must specify cl::location first, so that when the + command-line parser sees cl::init, it knows where to put the + initial value. (You will get an error at runtime if you don't put them in + the right order.)
    • + +
    • The cl::location attribute where to + store the value for a parsed command line option if using external storage. See + the section on Internal vs External Storage for more + information.
    • + +
    • The cl::aliasopt attribute + specifies which option a cl::alias option is + an alias for.
    • + +
    • The cl::values attribute specifies + the string-to-value mapping to be used by the generic parser. It takes a + clEnumValEnd terminated list of (option, value, description) triplets + that + specify the option name, the value mapped to, and the description shown in the + --help for the tool. Because the generic parser is used most + frequently with enum values, two macros are often useful: + +
        + +
      1. The clEnumVal macro is used as a + nice simple way to specify a triplet for an enum. This macro automatically + makes the option name be the same as the enum name. The first option to the + macro is the enum, the second is the description for the command line + option.
      2. + +
      3. The clEnumValN macro is used to + specify macro options where the option name doesn't equal the enum name. For + this macro, the first argument is the enum value, the second is the flag name, + and the second is the description.
      4. + +
      + + You will get a compile time error if you try to use cl::values with a parser + that does not support it.
    • + +
    + +
    + + + + +
    + +

    Option modifiers are the flags and expressions that you pass into the + constructors for cl::opt and cl::list. These modifiers give you the ability to + tweak how options are parsed and how --help output is generated to fit + your application well.

    + +

    These options fall into five main catagories:

    + +
      +
    1. Hiding an option from --help output
    2. +
    3. Controlling the number of occurrences + required and allowed
    4. +
    5. Controlling whether or not a value must be + specified
    6. +
    7. Controlling other formatting options
    8. +
    9. Miscellaneous option modifiers
    10. +
    + +

    It is not possible to specify two options from the same catagory (you'll get + a runtime error) to a single option, except for options in the miscellaneous + catagory. The CommandLine library specifies defaults for all of these settings + that are the most useful in practice and the most common, which mean that you + usually shouldn't have to worry about these.

    + +
    + + + + +
    + +

    The cl::NotHidden, cl::Hidden, and + cl::ReallyHidden modifiers are used to control whether or not an option + appears in the --help and --help-hidden output for the + compiled program:

    + +
      + +
    • The cl::NotHidden modifier + (which is the default for cl::opt and cl::list options), indicates the option is to appear + in both help listings.
    • + +
    • The cl::Hidden modifier (which is the + default for cl::alias options), indicates that + the option should not appear in the --help output, but should appear in + the --help-hidden output.
    • + +
    • The cl::ReallyHidden modifier, + indicates that the option should not appear in any help output.
    • + +
    + +
    + + + + +
    + +

    This group of options is used to control how many time an option is allowed + (or required) to be specified on the command line of your program. Specifying a + value for this setting allows the CommandLine library to do error checking for + you.

    + +

    The allowed values for this option group are:

    + +
      + +
    • The cl::Optional modifier (which + is the default for the cl::opt and cl::alias classes) indicates that your program will + allow either zero or one occurrence of the option to be specified.
    • + +
    • The cl::ZeroOrMore modifier + (which is the default for the cl::list class) + indicates that your program will allow the option to be specified zero or more + times.
    • + +
    • The cl::Required modifier + indicates that the specified option must be specified exactly one time.
    • + +
    • The cl::OneOrMore modifier + indicates that the option must be specified at least one time.
    • + +
    • The cl::ConsumeAfter modifier is described in the Positional arguments section
    • + +
    + +

    If an option is not specified, then the value of the option is equal to the + value specified by the cl::init attribute. If + the cl::init attribute is not specified, the + option value is initialized with the default constructor for the data type.

    + +

    If an option is specified multiple times for an option of the cl::opt class, only the last value will be + retained.

    + +
    + + + + +
    + +

    This group of options is used to control whether or not the option allows a + value to be present. In the case of the CommandLine library, a value is either + specified with an equal sign (e.g. '-index-depth=17') or as a trailing + string (e.g. '-o a.out').

    + +

    The allowed values for this option group are:

    + +
      + +
    • The cl::ValueOptional modifier + (which is the default for bool typed options) specifies that it is + acceptable to have a value, or not. A boolean argument can be enabled just by + appearing on the command line, or it can have an explicit '-foo=true'. + If an option is specified with this mode, it is illegal for the value to be + provided without the equal sign. Therefore '-foo true' is illegal. To + get this behavior, you must use the cl::ValueRequired modifier.
    • + +
    • The cl::ValueRequired modifier + (which is the default for all other types except for unnamed alternatives using the generic parser) + specifies that a value must be provided. This mode informs the command line + library that if an option is not provides with an equal sign, that the next + argument provided must be the value. This allows things like '-o + a.out' to work.
    • + +
    • The cl::ValueDisallowed + modifier (which is the default for unnamed + alternatives using the generic parser) indicates that it is a runtime error + for the user to specify a value. This can be provided to disallow users from + providing options to boolean options (like '-foo=true').
    • + +
    + +

    In general, the default values for this option group work just like you would + want them to. As mentioned above, you can specify the cl::ValueDisallowed modifier to a boolean + argument to restrict your command line parser. These options are mostly useful + when extending the library.

    + +
    + + + + +
    + +

    The formatting option group is used to specify that the command line option + has special abilities and is otherwise different from other command line + arguments. As usual, you can only specify at most one of these arguments.

    + +
      + +
    • The cl::NormalFormatting + modifier (which is the default all options) specifies that this option is + "normal".
    • + +
    • The cl::Positional modifier + specifies that this is a positional argument, that does not have a command line + option associated with it. See the Positional + Arguments section for more information.
    • + +
    • The cl::ConsumeAfter modifier + specifies that this option is used to capture "interpreter style" arguments. See this section for more information.
    • + +
    • The cl::Prefix modifier specifies + that this option prefixes its value. With 'Prefix' options, the equal sign does + not separate the value from the option name specified. Instead, the value is + everything after the prefix, including any equal sign if present. This is useful + for processing odd arguments like -lmalloc and -L/usr/lib in a + linker tool or -DNAME=value in a compiler tool. Here, the + 'l', 'D' and 'L' options are normal string (or list) + options, that have the cl::Prefix + modifier added to allow the CommandLine library to recognize them. Note that + cl::Prefix options must not have the + cl::ValueDisallowed modifier + specified.
    • + +
    • The cl::Grouping modifier is used + to implement unix style tools (like ls) that have lots of single letter + arguments, but only require a single dash. For example, the 'ls -labF' + command actually enables four different options, all of which are single + letters. Note that cl::Grouping + options cannot have values.
    • + +
    + +

    The CommandLine library does not restrict how you use the cl::Prefix or cl::Grouping modifiers, but it is possible to + specify ambiguous argument settings. Thus, it is possible to have multiple + letter options that are prefix or grouping options, and they will still work as + designed.

    + +

    To do this, the CommandLine library uses a greedy algorithm to parse the + input option into (potentially multiple) prefix and grouping options. The + strategy basically looks like this:

    + +
    parse(string OrigInput) { + +
      +
    1. string input = OrigInput; +
    2. if (isOption(input)) return getOption(input).parse();    // Normal option +
    3. while (!isOption(input) && !input.empty()) input.pop_back();    // Remove the last letter +
    4. if (input.empty()) return error();    // No matching option +
    5. if (getOption(input).isPrefix())
      +   return getOption(input).parse(input);
      +
    6. while (!input.empty()) {    // Must be grouping options
      +   getOption(input).parse();
      +   OrigInput.erase(OrigInput.begin(), OrigInput.begin()+input.length());
      +   input = OrigInput;
      +   while (!isOption(input) && !input.empty()) input.pop_back();
      + }
      +
    7. if (!OrigInput.empty()) error();
    8. +
    + +

    }

    +
    + +
    + + + + +
    + +

    The miscellaneous option modifiers are the only flags where you can specify + more than one flag from the set: they are not mutually exclusive. These flags + specify boolean properties that modify the option.

    + +
      + +
    • The cl::CommaSeparated modifier + indicates that any commas specified for an option's value should be used to + split the value up into multiple values for the option. For example, these two + options are equivalent when cl::CommaSeparated is specified: + "-foo=a -foo=b -foo=c" and "-foo=a,b,c". This option only + makes sense to be used in a case where the option is allowed to accept one or + more values (i.e. it is a cl::list option).
    • + +
    • The + cl::PositionalEatsArgs modifier (which only applies to + positional arguments, and only makes sense for lists) indicates that positional + argument should consume any strings after it (including strings that start with + a "-") up until another recognized positional argument. For example, if you + have two "eating" positional arguments "pos1" and "pos2" the + string "-pos1 -foo -bar baz -pos2 -bork" would cause the "-foo -bar + -baz" strings to be applied to the "-pos1" option and the + "-bork" string to be applied to the "-pos2" option.
    • + +
    + +

    So far, these are the only two miscellaneous option modifiers.

    + +
    + + + + +
    + +

    Despite all of the built-in flexibility, the CommandLine option library + really only consists of one function (cl::ParseCommandLineOptions) + and three main classes: cl::opt, cl::list, and cl::alias. This section describes these three + classes in detail.

    + +
    + + + + +
    + +

    The cl::ParseCommandLineOptions function is designed to be called + directly from main, and is used to fill in the values of all of the + command line option variables once argc and argv are + available.

    + +

    The cl::ParseCommandLineOptions function requires two parameters + (argc and argv), but may also take an optional third parameter + which holds additional extra text to emit when the + --help option is invoked.

    + +
    + + + + +
    + +

    The cl::ParseEnvironmentOptions function has mostly the same effects + as cl::ParseCommandLineOptions, + except that it is designed to take values for options from an environment + variable, for those cases in which reading the command line is not convenient or + not desired. It fills in the values of all the command line option variables + just like cl::ParseCommandLineOptions + does.

    + +

    It takes three parameters: first, the name of the program (since + argv may not be available, it can't just look in argv[0]), + second, the name of the environment variable to examine, and third, the optional + additional extra text to emit when the + --help option is invoked.

    + +

    cl::ParseEnvironmentOptions will break the environment + variable's value up into words and then process them using + cl::ParseCommandLineOptions. + Note: Currently cl::ParseEnvironmentOptions does not support + quoting, so an environment variable containing -option "foo bar" will + be parsed as three words, -option, "foo, and bar", + which is different from what you would get from the shell with the same + input.

    + +
    + + + + +
    + +

    The cl::SetVersionPrinter function is designed to be called + directly from main, and before + cl::ParseCommandLineOptions. Its use is optional. It simply arranges + for a function to be called in response to the --version option instead + of having the CommandLine library print out the usual version string + for LLVM. This is useful for programs that are not part of LLVM but wish to use + the CommandLine facilities. Such programs should just define a small + function that takes no arguments and returns void and that prints out + whatever version information is appropriate for the program. Pass the address + of that function to cl::SetVersionPrinter to arrange for it to be + called when the --version option is given by the user.

    + +
    + + + +
    + +

    The cl::opt class is the class used to represent scalar command line + options, and is the one used most of the time. It is a templated class which + can take up to three arguments (all except for the first have default values + though):

    + +
    + namespace cl {
    +   template <class DataType, bool ExternalStorage = false,
    +             class ParserClass = parser<DataType> >
    +   class opt;
    + }
    + 
    + +

    The first template argument specifies what underlying data type the command + line argument is, and is used to select a default parser implementation. The + second template argument is used to specify whether the option should contain + the storage for the option (the default) or whether external storage should be + used to contain the value parsed for the option (see Internal + vs External Storage for more information).

    + +

    The third template argument specifies which parser to use. The default value + selects an instantiation of the parser class based on the underlying + data type of the option. In general, this default works well for most + applications, so this option is only used when using a custom parser.

    + +
    + + + + +
    + +

    The cl::list class is the class used to represent a list of command + line options. It too is a templated class which can take up to three + arguments:

    + +
    + namespace cl {
    +   template <class DataType, class Storage = bool,
    +             class ParserClass = parser<DataType> >
    +   class list;
    + }
    + 
    + +

    This class works the exact same as the cl::opt class, except that the second argument is + the type of the external storage, not a boolean value. For this class, + the marker type 'bool' is used to indicate that internal storage should + be used.

    + +
    + + + + +
    + +

    The cl::bits class is the class used to represent a list of command + line options in the form of a bit vector. It is also a templated class which + can take up to three arguments:

    + +
    + namespace cl {
    +   template <class DataType, class Storage = bool,
    +             class ParserClass = parser<DataType> >
    +   class bits;
    + }
    + 
    + +

    This class works the exact same as the cl::lists class, except that the second argument + must be of type unsigned if external storage is used.

    + +
    + + + + +
    + +

    The cl::alias class is a nontemplated class that is used to form + aliases for other arguments.

    + +
    + namespace cl {
    +   class alias;
    + }
    + 
    + +

    The cl::aliasopt attribute should be + used to specify which option this is an alias for. Alias arguments default to + being Hidden, and use the aliased options parser to do + the conversion from string to data.

    + +
    + + + + +
    + +

    The cl::extrahelp class is a nontemplated class that allows extra + help text to be printed out for the --help option.

    + +
    + namespace cl {
    +   struct extrahelp;
    + }
    + 
    + +

    To use the extrahelp, simply construct one with a const char* + parameter to the constructor. The text passed to the constructor will be printed + at the bottom of the help message, verbatim. Note that multiple + cl::extrahelp can be used, but this practice is discouraged. If + your tool needs to print additional help information, put all that help into a + single cl::extrahelp instance.

    +

    For example:

    +
    +   cl::extrahelp("\nADDITIONAL HELP:\n\n  This is the extra help\n");
    + 
    +
    + + + + +
    + +

    Parsers control how the string value taken from the command line is + translated into a typed value, suitable for use in a C++ program. By default, + the CommandLine library uses an instance of parser<type> if the + command line option specifies that it uses values of type 'type'. + Because of this, custom option processing is specified with specializations of + the 'parser' class.

    + +

    The CommandLine library provides the following builtin parser + specializations, which are sufficient for most applications. It can, however, + also be extended to work with new data types and new ways of interpreting the + same data. See the Writing a Custom Parser for more + details on this type of library extension.

    + +
      + +
    • The generic parser<t> parser + can be used to map strings values to any data type, through the use of the cl::values property, which specifies the mapping + information. The most common use of this parser is for parsing enum values, + which allows you to use the CommandLine library for all of the error checking to + make sure that only valid enum values are specified (as opposed to accepting + arbitrary strings). Despite this, however, the generic parser class can be used + for any data type.
    • + +
    • The parser<bool> specialization + is used to convert boolean strings to a boolean value. Currently accepted + strings are "true", "TRUE", "True", "1", + "false", "FALSE", "False", and "0".
    • + +
    • The parser<string> + specialization simply stores the parsed string into the string value + specified. No conversion or modification of the data is performed.
    • + +
    • The parser<int> specialization + uses the C strtol function to parse the string input. As such, it will + accept a decimal number (with an optional '+' or '-' prefix) which must start + with a non-zero digit. It accepts octal numbers, which are identified with a + '0' prefix digit, and hexadecimal numbers with a prefix of + '0x' or '0X'.
    • + +
    • The parser<double> and + parser<float> specializations use the standard C + strtod function to convert floating point strings into floating point + values. As such, a broad range of string formats is supported, including + exponential notation (ex: 1.7e15) and properly supports locales. +
    • + +
    + +
    + + + + + +
    + +

    Although the CommandLine library has a lot of functionality built into it + already (as discussed previously), one of its true strengths lie in its + extensibility. This section discusses how the CommandLine library works under + the covers and illustrates how to do some simple, common, extensions.

    + +
    + + + + +
    + +

    One of the simplest and most common extensions is the use of a custom parser. + As discussed previously, parsers are the portion + of the CommandLine library that turns string input from the user into a + particular parsed data type, validating the input in the process.

    + +

    There are two ways to use a new parser:

    + +
      + +
    1. + +

      Specialize the cl::parser template for + your custom data type.

      + +

      This approach has the advantage that users of your custom data type will + automatically use your custom parser whenever they define an option with a value + type of your data type. The disadvantage of this approach is that it doesn't + work if your fundamental data type is something that is already supported.

      + +
    2. + +
    3. + +

      Write an independent class, using it explicitly from options that need + it.

      + +

      This approach works well in situations where you would line to parse an + option using special syntax for a not-very-special data-type. The drawback of + this approach is that users of your parser have to be aware that they are using + your parser, instead of the builtin ones.

      + +
    4. + +
    + +

    To guide the discussion, we will discuss a custom parser that accepts file + sizes, specified with an optional unit after the numeric size. For example, we + would like to parse "102kb", "41M", "1G" into the appropriate integer value. In + this case, the underlying data type we want to parse into is + 'unsigned'. We choose approach #2 above because we don't want to make + this the default for all unsigned options.

    + +

    To start out, we declare our new FileSizeParser class:

    + +
    + struct FileSizeParser : public cl::basic_parser<unsigned> {
    +   // parse - Return true on error.
    +   bool parse(cl::Option &O, const char *ArgName, const std::string &ArgValue,
    +              unsigned &Val);
    + };
    + 
    + +

    Our new class inherits from the cl::basic_parser template class to + fill in the default, boiler plate, code for us. We give it the data type that + we parse into (the last argument to the parse method so that clients of + our custom parser know what object type to pass in to the parse method (here we + declare that we parse into 'unsigned' variables.

    + +

    For most purposes, the only method that must be implemented in a custom + parser is the parse method. The parse method is called + whenever the option is invoked, passing in the option itself, the option name, + the string to parse, and a reference to a return value. If the string to parse + is not well formed, the parser should output an error message and return true. + Otherwise it should return false and set 'Val' to the parsed value. In + our example, we implement parse as:

    + +
    + bool FileSizeParser::parse(cl::Option &O, const char *ArgName,
    +                            const std::string &Arg, unsigned &Val) {
    +   const char *ArgStart = Arg.c_str();
    +   char *End;
    +  
    +   // Parse integer part, leaving 'End' pointing to the first non-integer char
    +   Val = (unsigned)strtol(ArgStart, &End, 0);
    + 
    +   while (1) {
    +     switch (*End++) {
    +     case 0: return false;   // No error
    +     case 'i':               // Ignore the 'i' in KiB if people use that
    +     case 'b': case 'B':     // Ignore B suffix
    +       break;
    + 
    +     case 'g': case 'G': Val *= 1024*1024*1024; break;
    +     case 'm': case 'M': Val *= 1024*1024;      break;
    +     case 'k': case 'K': Val *= 1024;           break;
    + 
    +     default:
    +       // Print an error message if unrecognized character!
    +       return O.error(": '" + Arg + "' value invalid for file size argument!");
    +     }
    +   }
    + }
    + 
    + +

    This function implements a very simple parser for the kinds of strings we are + interested in. Although it has some holes (it allows "123KKK" for + example), it is good enough for this example. Note that we use the option + itself to print out the error message (the error method always returns + true) in order to get a nice error message (shown below). Now that we have our + parser class, we can use it like this:

    + +
    + static cl::opt<unsigned, false, FileSizeParser>
    + MFS("max-file-size", cl::desc("Maximum file size to accept"),
    +     cl::value_desc("size"));
    + 
    + +

    Which adds this to the output of our program:

    + +
    + OPTIONS:
    +   -help                 - display available options (--help-hidden for more)
    +   ...
    +   -max-file-size=<size> - Maximum file size to accept
    + 
    + +

    And we can test that our parse works correctly now (the test program just + prints out the max-file-size argument value):

    + +
    + $ ./test
    + MFS: 0
    + $ ./test -max-file-size=123MB
    + MFS: 128974848
    + $ ./test -max-file-size=3G
    + MFS: 3221225472
    + $ ./test -max-file-size=dog
    + -max-file-size option: 'dog' value invalid for file size argument!
    + 
    + +

    It looks like it works. The error message that we get is nice and helpful, + and we seem to accept reasonable file sizes. This wraps up the "custom parser" + tutorial.

    + +
    + + + + +
    +

    Several of the LLVM libraries define static cl::opt instances that + will automatically be included in any program that links with that library. + This is a feature. However, sometimes it is necessary to know the value of the + command line option outside of the library. In these cases the library does or + should provide an external storage location that is accessible to users of the + library. Examples of this include the llvm::DebugFlag exported by the + lib/Support/Debug.cpp file and the llvm::TimePassesIsEnabled + flag exported by the lib/VMCore/Pass.cpp file.

    + +

    TODO: complete this section

    + +
    + + + + +
    + +

    TODO: fill in this section

    + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/CompilerDriver.html diff -c /dev/null llvm-www/releases/1.8/docs/CompilerDriver.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/CompilerDriver.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,823 ---- + + + + + The LLVM Compiler Driver (llvmc) + + + + + +
    The LLVM Compiler Driver (llvmc)
    +

    NOTE: This document is a work in progress!

    +
      +
    1. Abstract
    2. +
    3. Introduction +
        +
      1. Purpose
      2. +
      3. Operation
      4. +
      5. Phases
      6. +
      7. Actions
      8. +
      +
    4. +
    5. Configuration +
        +
      1. Overview
      2. +
      3. Configuration Files
      4. +
      5. Syntax
      6. +
      7. Substitutions
      8. +
      9. Sample Config File
      10. +
      +
    6. Glossary +
    +
    +

    Written by Reid Spencer +

    +
    + + + + +
    +

    This document describes the requirements, design, and configuration of the + LLVM compiler driver, llvmc. The compiler driver knows about LLVM's + tool set and can be configured to know about a variety of compilers for + source languages. It uses this knowledge to execute the tools necessary + to accomplish general compilation, optimization, and linking tasks. The main + purpose of llvmc is to provide a simple and consistent interface to + all compilation tasks. This reduces the burden on the end user who can just + learn to use llvmc instead of the entire LLVM tool set and all the + source language compilers compatible with LLVM.

    +
    + + + +
    +

    The llvmc tool is a configurable compiler + driver. As such, it isn't a compiler, optimizer, + or a linker itself but it drives (invokes) other software that perform those + tasks. If you are familiar with the GNU Compiler Collection's gcc + tool, llvmc is very similar.

    +

    The following introductory sections will help you understand why this tool + is necessary and what it does.

    +
    + + + +
    +

    llvmc was invented to make compilation of user programs with + LLVM-based tools easier. To accomplish this, llvmc strives to:

    +
      +
    • Be the single point of access to most of the LLVM tool set.
    • +
    • Hide the complexities of the LLVM tools through a single interface.
    • +
    • Provide a consistent interface for compiling all languages.
    • +
    +

    Additionally, llvmc makes it easier to write a compiler for use + with LLVM, because it:

    +
      +
    • Makes integration of existing non-LLVM tools simple.
    • +
    • Extends the capabilities of minimal compiler tools by optimizing their + output.
    • +
    • Reduces the number of interfaces a compiler writer must know about + before a working compiler can be completed (essentially only the VMCore + interfaces need to be understood).
    • +
    • Supports source language translator invocation via both dynamically + loadable shared objects and invocation of an executable.
    • +
    +
    + + + +
    +

    At a high level, llvmc operation is very simple. The basic action + taken by llvmc is to simply invoke some tool or set of tools to fill + the user's request for compilation. Every execution of llvmctakes the + following sequence of steps:

    +
    +
    Collect Command Line Options
    +
    The command line options provide the marching orders to llvmc + on what actions it should perform. This is the request the user is making + of llvmc and it is interpreted first. See the llvmc + manual page for details on the + options.
    +
    Read Configuration Files
    +
    Based on the options and the suffixes of the filenames presented, a set + of configuration files are read to configure the actions llvmc will + take. Configuration files are provided by either LLVM or the + compiler tools that llvmc invokes. These files determine what + actions llvmc will take in response to the user's request. See + the section on configuration for more details. +
    +
    Determine Phases To Execute
    +
    Based on the command line options and configuration files, + llvmc determines the compilation phases that + must be executed by the user's request. This is the primary work of + llvmc.
    +
    Determine Actions To Execute
    +
    Each phase to be executed can result in the + invocation of one or more actions. An action is + either a whole program or a function in a dynamically linked shared library. + In this step, llvmc determines the sequence of actions that must be + executed. Actions will always be executed in a deterministic order.
    +
    Execute Actions
    +
    The actions necessary to support the user's + original request are executed sequentially and deterministically. All + actions result in either the invocation of a whole program to perform the + action or the loading of a dynamically linkable shared library and invocation + of a standard interface function within that library.
    +
    Termination
    +
    If any action fails (returns a non-zero result code), llvmc + also fails and returns the result code from the failing action. If + everything succeeds, llvmc will return a zero result code.
    +
    +

    llvmc's operation must be simple, regular and predictable. + Developers need to be able to rely on it to take a consistent approach to + compilation. For example, the invocation:

    + + llvmc -O2 x.c y.c z.c -o xyz +

    must produce exactly the same results as:

    +
    
    +     llvmc -O2 x.c -o x.o
    +     llvmc -O2 y.c -o y.o
    +     llvmc -O2 z.c -o z.o
    +     llvmc -O2 x.o y.o z.o -o xyz
    +

    To accomplish this, llvmc uses a very simple goal oriented + procedure to do its work. The overall goal is to produce a functioning + executable. To accomplish this, llvmc always attempts to execute a + series of compilation phases in the same sequence. + However, the user's options to llvmc can cause the sequence of phases + to start in the middle or finish early.

    +
    + + +
    Phases
    +
    +

    llvmc breaks every compilation task into the following five + distinct phases:

    +
    Preprocessing
    Not all languages support preprocessing; + but for those that do, this phase can be invoked. This phase is for + languages that provide combining, filtering, or otherwise altering with the + source language input before the translator parses it. Although C and C++ + are the most common users of this phase, other languages may provide their + own preprocessor (whether its the C pre-processor or not).
    +
    +
    Translation
    The translation phase converts the source + language input into something that LLVM can interpret and use for + downstream phases. The translation is essentially from "non-LLVM form" to + "LLVM form".
    +
    +
    Optimization
    Once an LLVM Module has been obtained from + the translation phase, the program enters the optimization phase. This phase + attempts to optimize all of the input provided on the command line according + to the options provided.
    +
    +
    Linking
    The inputs are combined to form a complete + program.
    +
    +

    The following table shows the inputs, outputs, and command line options + applicable to each phase.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PhaseInputsOutputsOptions
    Preprocessing
    • Source Language File
    • Source Language File
    +
    -E
    +
    Stops the compilation after preprocessing
    +
    Translation
      +
    • Source Language File
    • +
      +
    • LLVM Assembly
    • +
    • LLVM Bytecode
    • +
    • LLVM C++ IR
    • +
    +
    -c
    +
    Stops the compilation after translation so that optimization and + linking are not done.
    +
    -S
    +
    Stops the compilation before object code is written so that only + assembly code remains.
    +
    Optimization
      +
    • LLVM Assembly
    • +
    • LLVM Bytecode
    • +
      +
    • LLVM Bytecode
    • +
    +
    -Ox +
    This group of options controls the amount of optimization + performed.
    +
    Linking
      +
    • LLVM Bytecode
    • +
    • Native Object Code
    • +
    • LLVM Library
    • +
    • Native Library
    • +
      +
    • LLVM Bytecode Executable
    • +
    • Native Executable
    • +
    +
    -L
    Specifies a path for library search.
    +
    -l
    Specifies a library to link in.
    +
    +
    + + +
    Actions
    +
    +

    An action, with regard to llvmc is a basic operation that it takes + in order to fulfill the user's request. Each phase of compilation will invoke + zero or more actions in order to accomplish that phase.

    +

    Actions come in two forms:

    +
      +
    • Invokable Executables
    • +
    • Functions in a shared library
    • +
    +
    + + + + +
    +

    This section of the document describes the configuration files used by + llvmc. Configuration information is relatively static for a + given release of LLVM and a compiler tool. However, the details may + change from release to release of either. Users are encouraged to simply use + the various options of the llvmc command and ignore the configuration + of the tool. These configuration files are for compiler writers and LLVM + developers. Those wishing to simply use llvmc don't need to understand + this section but it may be instructive on how the tool works.

    +
    + + +
    Overview
    +
    +

    llvmc is highly configurable both on the command line and in + configuration files. The options it understands are generic, consistent and + simple by design. Furthermore, the llvmc options apply to the + compilation of any LLVM enabled programming language. To be enabled as a + supported source language compiler, a compiler writer must provide a + configuration file that tells llvmc how to invoke the compiler + and what its capabilities are. The purpose of the configuration files then + is to allow compiler writers to specify to llvmc how the compiler + should be invoked. Users may but are not advised to alter the compiler's + llvmc configuration.

    + +

    Because llvmc just invokes other programs, it must deal with the + available command line options for those programs regardless of whether they + were written for LLVM or not. Furthermore, not all compiler tools will + have the same capabilities. Some compiler tools will simply generate LLVM assembly + code, others will be able to generate fully optimized byte code. In general, + llvmc doesn't make any assumptions about the capabilities or command + line options of a sub-tool. It simply uses the details found in the + configuration files and leaves it to the compiler writer to specify the + configuration correctly.

    + +

    This approach means that new compiler tools can be up and working very + quickly. As a first cut, a tool can simply compile its source to raw + (unoptimized) bytecode or LLVM assembly and llvmc can be configured + to pick up the slack (translate LLVM assembly to bytecode, optimize the + bytecode, generate native assembly, link, etc.). In fact, the compiler tools + need not use any LLVM libraries, and it could be written in any language + (instead of C++). The configuration data will allow the full range of + optimization, assembly, and linking capabilities that LLVM provides to be added + to these kinds of tools. Enabling the rapid development of front-ends is one + of the primary goals of llvmc.

    + +

    As a compiler tool matures, it may utilize the LLVM libraries and tools + to more efficiently produce optimized bytecode directly in a single compilation + and optimization program. In these cases, multiple tools would not be needed + and the configuration data for the compiler would change.

    + +

    Configuring llvmc to the needs and capabilities of a source language + compiler is relatively straight-forward. A compiler writer must provide a + definition of what to do for each of the five compilation phases for each of + the optimization levels. The specification consists simply of prototypical + command lines into which llvmc can substitute command line + arguments and file names. Note that any given phase can be completely blank if + the source language's compiler combines multiple phases into a single program. + For example, quite often pre-processing, translation, and optimization are + combined into a single program. The specification for such a compiler would have + blank entries for pre-processing and translation but a full command line for + optimization.

    +
    + + + + +
    +

    Each configuration file provides the details for a single source language + that is to be compiled. This configuration information tells llvmc + how to invoke the language's pre-processor, translator, optimizer, assembler + and linker. Note that a given source language needn't provide all these tools + as many of them exist in llvm currently.

    +
    + + + +
    +

    llvmc always looks for files of a specific name. It uses the + first file with the name its looking for by searching directories in the + following order:
    +

      +
    1. Any directory specified by the -config-dir option will be + checked first.
    2. +
    3. If the environment variable LLVM_CONFIG_DIR is set, and it contains + the name of a valid directory, that directory will be searched next.
    4. +
    5. If the user's home directory (typically /home/user contains + a sub-directory named .llvm and that directory contains a + sub-directory named etc then that directory will be tried + next.
    6. +
    7. If the LLVM installation directory (typically /usr/local/llvm + contains a sub-directory named etc then that directory will be + tried last.
    8. +
    9. A standard "system" directory will be searched next. This is typically + /etc/llvm on UNIX™ and C:\WINNT on Microsoft + Windows™.
    10. +
    11. If the configuration file sought still can't be found, llvmc + will print an error message and exit.
    12. +
    +

    The first file found in this search will be used. Other files with the + same name will be ignored even if they exist in one of the subsequent search + locations.

    +
    + + +
    +

    In the directories searched, each configuration file is given a specific + name to foster faster lookup (so llvmc doesn't have to do directory searches). + The name of a given language specific configuration file is simply the same + as the suffix used to identify files containing source in that language. + For example, a configuration file for C++ source might be named + cpp, C, or cxx. For languages that support multiple + file suffixes, multiple (probably identical) files (or symbolic links) will + need to be provided.

    +
    + + +
    +

    Which configuration files are read depends on the command line options and + the suffixes of the file names provided on llvmc's command line. Note + that the -x LANGUAGE option alters the language that llvmc + uses for the subsequent files on the command line. Only the configuration + files actually needed to complete llvmc's task are read. Other + language specific files will be ignored.

    +
    + + +
    Syntax
    +
    +

    The syntax of the configuration files is very simple and somewhat + compatible with Java's property files. Here are the syntax rules:

    +
      +
    • The file encoding is ASCII.
    • +
    • The file is line oriented. There should be one configuration definition + per line. Lines are terminated by the newline (0x0A) and/or carriage return + characters (0x0D)
    • +
    • A backslash (\) before a newline causes the newline to be + ignored. This is useful for line continuation of long definitions. A + backslash anywhere else is recognized as a backslash.
    • +
    • A configuration item consists of a name, an = and a value.
    • +
    • A name consists of a sequence of identifiers separated by period.
    • +
    • An identifier consists of specific keywords made up of only lower case + and upper case letters (e.g. lang.name).
    • +
    • Values come in four flavors: booleans, integers, commands and + strings.
    • +
    • Valid "false" boolean values are false False FALSE no No NO + off Off and OFF.
    • +
    • Valid "true" boolean values are true True TRUE yes Yes YES + on On and ON.
    • +
    • Integers are simply sequences of digits.
    • +
    • Commands start with a program name and are followed by a sequence of + words that are passed to that program as command line arguments. Program + arguments that begin and end with the % sign will have their value + substituted. Program names beginning with / are considered to be + absolute. Otherwise the PATH will be applied to find the program to + execute.
    • +
    • Strings are composed of multiple sequences of characters from the + character class [-A-Za-z0-9_:%+/\\|,] separated by white + space.
    • +
    • White space on a line is folded. Multiple blanks or tabs will be + reduced to a single blank.
    • +
    • White space before the configuration item's name is ignored.
    • +
    • White space on either side of the = is ignored.
    • +
    • White space in a string value is used to separate the individual + components of the string value but otherwise ignored.
    • +
    • Comments are introduced by the # character. Everything after a + # and before the end of line is ignored.
    • +
    +
    + + + +
    +

    The table below provides definitions of the allowed configuration items + that may appear in a configuration file. Every item has a default value and + does not need to appear in the configuration file. Missing items will have the + default value. Each identifier may appear as all lower case, first letter + capitalized or all upper case.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameValue TypeDescriptionDefault

    LLVMC ITEMS

    versionstringProvides the version string for the contents of this + configuration file. What is accepted as a legal configuration file + will change over time and this item tells llvmc which version + should be expected.b

    LANG ITEMS

    lang.namestringProvides the common name for a language definition. + For example "C++", "Pascal", "FORTRAN", etc.blank
    lang.opt1stringSpecifies the parameters to give the optimizer when + -O1 is specified on the llvmc command line.-simplifycfg -instcombine -mem2reg
    lang.opt2stringSpecifies the parameters to give the optimizer when + -O2 is specified on the llvmc command line.TBD
    lang.opt3stringSpecifies the parameters to give the optimizer when + -O3 is specified on the llvmc command line.TBD
    lang.opt4stringSpecifies the parameters to give the optimizer when + -O4 is specified on the llvmc command line.TBD
    lang.opt5stringSpecifies the parameters to give the optimizer when + -O5 is specified on the llvmc command line.TBD

    PREPROCESSOR ITEMS

    preprocessor.commandcommandThis provides the command prototype that will be used + to run the preprocessor. This is generally only used with the + -E option.<blank>
    preprocessor.requiredbooleanThis item specifies whether the pre-processing phase + is required by the language. If the value is true, then the + preprocessor.command value must not be blank. With this option, + llvmc will always run the preprocessor as it assumes that the + translation and optimization phases don't know how to pre-process their + input.false

    TRANSLATOR ITEMS

    translator.commandcommandThis provides the command prototype that will be used + to run the translator. Valid substitutions are %in% for the + input file and %out% for the output file.<blank>
    translator.outputbytecode or assemblyThis item specifies the kind of output the language's + translator generates.bytecode
    translator.preprocessesbooleanIndicates that the translator also preprocesses. If + this is true, then llvmc will skip the pre-processing phase + whenever the final phase is not pre-processing.false

    OPTIMIZER ITEMS

    optimizer.commandcommandThis provides the command prototype that will be used + to run the optimizer. Valid substitutions are %in% for the + input file and %out% for the output file.<blank>
    optimizer.outputbytecode or assemblyThis item specifies the kind of output the language's + optimizer generates. Valid values are "assembly" and "bytecode"bytecode
    optimizer.preprocessesbooleanIndicates that the optimizer also preprocesses. If + this is true, then llvmc will skip the pre-processing phase + whenever the final phase is optimization or later.false
    optimizer.translatesbooleanIndicates that the optimizer also translates. If + this is true, then llvmc will skip the translation phase + whenever the final phase is optimization or later.false

    ASSEMBLER ITEMS

    assembler.commandcommandThis provides the command prototype that will be used + to run the assembler. Valid substitutions are %in% for the + input file and %out% for the output file.<blank>
    +
    + + + +
    +

    On any configuration item that ends in command, you must + specify substitution tokens. Substitution tokens begin and end with a percent + sign (%) and are replaced by the corresponding text. Any substitution + token may be given on any command line but some are more useful than + others. In particular each command should have both an %in% + and an %out% substitution. The table below provides definitions of + each of the allowed substitution tokens.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Substitution TokenReplacement Description
    %args%Replaced with all the tool-specific arguments given + to llvmc via the -T set of options. This just allows + you to place these arguments in the correct place on the command line. + If the %args% option does not appear on your command line, + then you are explicitly disallowing the -T option for your + tool. +
    %force%Replaced with the -f option if it was + specified on the llvmc command line. This is intended to tell + the compiler tool to force the overwrite of output files. +
    %in%Replaced with the full path of the input file. You + needn't worry about the cascading of file names. llvmc will + create temporary files and ensure that the output of one phase is the + input to the next phase.
    %opt%Replaced with the optimization options for the + tool. If the tool understands the -O options then that will + be passed. Otherwise, the lang.optN series of configuration + items will specify which arguments are to be given.
    %out%Replaced with the full path of the output file. + Note that this is not necessarily the output file specified with the + -o option on llvmc's command line. It might be a + temporary file that will be passed to a subsequent phase's input. +
    %stats%If your command accepts the -stats option, + use this substitution token. If the user requested -stats + from the llvmc command line then this token will be replaced + with -stats, otherwise it will be ignored. +
    %target%Replaced with the name of the target "machine" for + which code should be generated. The value used here is taken from the + llvmc option -march. +
    %time%If your command accepts the -time-passes + option, use this substitution token. If the user requested + -time-passes from the llvmc command line then this + token will be replaced with -time-passes, otherwise it will + be ignored. +
    +
    + + + +
    +

    Since an example is always instructive, here's how the Stacker language + configuration file looks.

    +
    
    + # Stacker Configuration File For llvmc
    + 
    + ##########################################################
    + # Language definitions
    + ##########################################################
    +   lang.name=Stacker 
    +   lang.opt1=-simplifycfg -instcombine -mem2reg
    +   lang.opt2=-simplifycfg -instcombine -mem2reg -load-vn \
    +     -gcse -dse -scalarrepl -sccp 
    +   lang.opt3=-simplifycfg -instcombine -mem2reg -load-vn \
    +     -gcse -dse -scalarrepl -sccp -branch-combine -adce \
    +     -globaldce -inline -licm 
    +   lang.opt4=-simplifycfg -instcombine -mem2reg -load-vn \
    +     -gcse -dse -scalarrepl -sccp -ipconstprop \
    +     -branch-combine -adce -globaldce -inline -licm 
    +   lang.opt5=-simplifycfg -instcombine -mem2reg --load-vn \
    +     -gcse -dse scalarrepl -sccp -ipconstprop \
    +     -branch-combine -adce -globaldce -inline -licm \
    +     -block-placement
    + 
    + ##########################################################
    + # Pre-processor definitions
    + ##########################################################
    + 
    +   # Stacker doesn't have a preprocessor but the following
    +   # allows the -E option to be supported
    +   preprocessor.command=cp %in% %out%
    +   preprocessor.required=false
    + 
    + ##########################################################
    + # Translator definitions
    + ##########################################################
    + 
    +   # To compile stacker source, we just run the stacker
    +   # compiler with a default stack size of 2048 entries.
    +   translator.command=stkrc -s 2048 %in% -o %out% %time% \
    +     %stats% %force% %args%
    + 
    +   # stkrc doesn't preprocess but we set this to true so
    +   # that we don't run the cp command by default.
    +   translator.preprocesses=true
    + 
    +   # The translator is required to run.
    +   translator.required=true
    + 
    +   # stkrc doesn't handle the -On options
    +   translator.output=bytecode
    + 
    + ##########################################################
    + # Optimizer definitions
    + ##########################################################
    +   
    +   # For optimization, we use the LLVM "opt" program
    +   optimizer.command=opt %in% -o %out% %opt% %time% %stats% \
    +     %force% %args%
    + 
    +   optimizer.required = true
    + 
    +   # opt doesn't translate
    +   optimizer.translates = no
    + 
    +   # opt doesn't preprocess
    +   optimizer.preprocesses=no
    + 
    +   # opt produces bytecode
    +   optimizer.output = bc
    + 
    + ##########################################################
    + # Assembler definitions
    + ##########################################################
    +   assembler.command=llc %in% -o %out% %target% %time% %stats%
    + 
    +
    + + + + +
    +

    This document uses precise terms in reference to the various artifacts and + concepts related to compilation. The terms used throughout this document are + defined below.

    +
    +
    assembly
    +
    A compilation phase in which LLVM bytecode or + LLVM assembly code is assembled to a native code format (either target + specific aseembly language or the platform's native object file format). +
    + +
    compiler
    +
    Refers to any program that can be invoked by llvmc to accomplish + the work of one or more compilation phases.
    + +
    driver
    +
    Refers to llvmc itself.
    + +
    linking
    +
    A compilation phase in which LLVM bytecode files + and (optionally) native system libraries are combined to form a complete + executable program.
    + +
    optimization
    +
    A compilation phase in which LLVM bytecode is + optimized.
    + +
    phase
    +
    Refers to any one of the five compilation phases that that + llvmc supports. The five phases are: + preprocessing, + translation, + optimization, + assembly, + linking.
    + +
    source language
    +
    Any common programming language (e.g. C, C++, Java, Stacker, ML, + FORTRAN). These languages are distinguished from any of the lower level + languages (such as LLVM or native assembly), by the fact that a + translation phase + is required before LLVM can be applied.
    + +
    tool
    +
    Refers to any program in the LLVM tool set.
    + +
    translation
    +
    A compilation phase in which + source language code is translated into + either LLVM assembly language or LLVM bytecode.
    +
    +
    + +
    +
    Valid CSS!Valid HTML 4.01!Reid Spencer
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/CompilerWriterInfo.html diff -c /dev/null llvm-www/releases/1.8/docs/CompilerWriterInfo.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/CompilerWriterInfo.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,260 ---- + + + + + Architecture/platform information for compiler writers + + + +
    + Architecture/platform information for compiler writers +
    + +
    +

    Note: This document is a work-in-progress. Additions and clarifications + are welcome.

    +
    + +
      +
    1. Hardware +
        +
      1. Alpha
      2. +
      3. ARM
      4. +
      5. Itanium
      6. +
      7. MIPS
      8. +
      9. PowerPC
      10. +
      11. SPARC
      12. +
      13. X86
      14. +
      15. Other lists
      16. +
    2. +
    3. Application Binary Interface (ABI) +
        +
      1. Linux
      2. +
      3. OS X
      4. +
    4. +
    5. Miscellaneous resources
    6. +
    + +
    +

    Compiled by Misha Brukman

    +
    + + + + + + + + +
    + +
    + + + + + + + + + + + + + + + + + + + + +
    IBM - Official manuals and docs
    + + + + +
    Other documents, collections, notes
    + + + + + + + + + + + + +
    AMD - Official manuals and docs
    + + + + +
    Intel - Official manuals and docs
    + + + + +
    Other x86-specific information
    + + + + + + +
    + + + +
    + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Misha Brukman
    + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/ExtendingLLVM.html diff -c /dev/null llvm-www/releases/1.8/docs/ExtendingLLVM.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/ExtendingLLVM.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,389 ---- + + + + Extending LLVM: Adding instructions, intrinsics, types, etc. + + + + + +
    + Extending LLVM: Adding instructions, intrinsics, types, etc. +
    + +
      +
    1. Introduction and Warning
    2. +
    3. Adding a new intrinsic function
    4. +
    5. Adding a new instruction
    6. +
    7. Adding a new SelectionDAG node
    8. +
    9. Adding a new type +
        +
      1. Adding a new fundamental type
      2. +
      3. Adding a new derived type
      4. +
    10. +
    + +
    +

    Written by Misha Brukman, + Brad Jones, Nate Begeman, + and Chris Lattner

    +
    + + + + + +
    + +

    During the course of using LLVM, you may wish to customize it for your + research project or for experimentation. At this point, you may realize that + you need to add something to LLVM, whether it be a new fundamental type, a new + intrinsic function, or a whole new instruction.

    + +

    When you come to this realization, stop and think. Do you really need to + extend LLVM? Is it a new fundamental capability that LLVM does not support at + its current incarnation or can it be synthesized from already pre-existing LLVM + elements? If you are not sure, ask on the LLVM-dev list. The + reason is that extending LLVM will get involved as you need to update all the + different passes that you intend to use with your extension, and there are + many LLVM analyses and transformations, so it may be quite a bit of + work.

    + +

    Adding an intrinsic function is far easier than + adding an instruction, and is transparent to optimization passes. If your added + functionality can be expressed as a + function call, an intrinsic function is the method of choice for LLVM + extension.

    + +

    Before you invest a significant amount of effort into a non-trivial + extension, ask on the list if what you are + looking to do can be done with already-existing infrastructure, or if maybe + someone else is already working on it. You will save yourself a lot of time and + effort by doing so.

    + +
    + + + + + +
    + +

    Adding a new intrinsic function to LLVM is much easier than adding a new + instruction. Almost all extensions to LLVM should start as an intrinsic + function and then be turned into an instruction if warranted.

    + +
      +
    1. llvm/docs/LangRef.html: + Document the intrinsic. Decide whether it is code generator specific and + what the restrictions are. Talk to other people about it so that you are + sure it's a good idea.
    2. + +
    3. llvm/include/llvm/Intrinsics*.td: + Add an entry for your intrinsic. Describe its memory access characteristics + for optimization (this controls whether it will be DCE'd, CSE'd, etc).
    4. + +
    5. llvm/lib/Analysis/ConstantFolding.cpp: If it is possible to + constant fold your intrinsic, add support to it in the + canConstantFoldCallTo and ConstantFoldCall functions.
    6. + +
    7. llvm/test/Regression/*: Add test cases for your test cases to the + test suite
    8. +
    + +

    Once the intrinsic has been added to the system, you must add code generator + support for it. Generally you must do the following steps:

    + +
    +
    Add support to the C backend in lib/Target/CBackend/
    + +
    Depending on the intrinsic, there are a few ways to implement this. For + most intrinsics, it makes sense to add code to lower your intrinsic in + LowerIntrinsicCall in lib/CodeGen/IntrinsicLowering.cpp. + Second, if it makes sense to lower the intrinsic to an expanded sequence of C + code in all cases, just emit the expansion in visitCallInst in + Writer.cpp. If the intrinsic has some way to express it with GCC + (or any other compiler) extensions, it can be conditionally supported based on + the compiler compiling the CBE output (see llvm.prefetch for an + example). + Third, if the intrinsic really has no way to be lowered, just have the code + generator emit code that prints an error message and calls abort if executed. +
    + +
    +
    Add support to the .td file for the target(s) of your choice in + lib/Target/*/*.td.
    + +
    This is usually a matter of adding a pattern to the .td file that matches + the intrinsic, though it may obviously require adding the instructions you + want to generate as well. There are lots of examples in the PowerPC and X86 + backend to follow.
    + +
    + + + + + +
    + +

    As with intrinsics, adding a new SelectionDAG node to LLVM is much easier + than adding a new instruction. New nodes are often added to help represent + instructions common to many targets. These nodes often map to an LLVM + instruction (add, sub) or intrinsic (byteswap, population count). In other + cases, new nodes have been added to allow many targets to perform a common task + (converting between floating point and integer representation) or capture more + complicated behavior in a single node (rotate).

    + +
      +
    1. include/llvm/CodeGen/SelectionDAGNodes.h: + Add an enum value for the new SelectionDAG node.
    2. +
    3. lib/CodeGen/SelectionDAG/SelectionDAG.cpp: + Add code to print the node to getOperationName. If your new node + can be evaluated at compile time when given constant arguments (such as an + add of a constant with another constant), find the getNode method + that takes the appropriate number of arguments, and add a case for your node + to the switch statement that performs constant folding for nodes that take + the same number of arguments as your new node.
    4. +
    5. lib/CodeGen/SelectionDAG/LegalizeDAG.cpp: + Add code to legalize, + promote, and expand the node as necessary. At a minimum, you will need + to add a case statement for your node in LegalizeOp which calls + LegalizeOp on the node's operands, and returns a new node if any of the + operands changed as a result of being legalized. It is likely that not all + targets supported by the SelectionDAG framework will natively support the + new node. In this case, you must also add code in your node's case + statement in LegalizeOp to Expand your node into simpler, legal + operations. The case for ISD::UREM for expanding a remainder into + a divide, multiply, and a subtract is a good example.
    6. +
    7. lib/CodeGen/SelectionDAG/LegalizeDAG.cpp: + If targets may support the new node being added only at certain sizes, you + will also need to add code to your node's case statement in + LegalizeOp to Promote your node's operands to a larger size, and + perform the correct operation. You will also need to add code to + PromoteOp to do this as well. For a good example, see + ISD::BSWAP, + which promotes its operand to a wider size, performs the byteswap, and then + shifts the correct bytes right to emulate the narrower byteswap in the + wider type.
    8. +
    9. lib/CodeGen/SelectionDAG/LegalizeDAG.cpp: + Add a case for your node in ExpandOp to teach the legalizer how to + perform the action represented by the new node on a value that has been + split into high and low halves. This case will be used to support your + node with a 64 bit operand on a 32 bit target.
    10. +
    11. lib/CodeGen/SelectionDAG/DAGCombiner.cpp: + If your node can be combined with itself, or other existing nodes in a + peephole-like fashion, add a visit function for it, and call that function + from . There are several good examples for simple combines you + can do; visitFABS and visitSRL are good starting places. +
    12. +
    13. lib/Target/PowerPC/PPCISelLowering.cpp: + Each target has an implementation of the TargetLowering class, + usually in its own file (although some targets include it in the same + file as the DAGToDAGISel). The default behavior for a target is to + assume that your new node is legal for all types that are legal for + that target. If this target does not natively support your node, then + tell the target to either Promote it (if it is supported at a larger + type) or Expand it. This will cause the code you wrote in + LegalizeOp above to decompose your new node into other legal + nodes for this target.
    14. +
    15. lib/Target/TargetSelectionDAG.td: + Most current targets supported by LLVM generate code using the DAGToDAG + method, where SelectionDAG nodes are pattern matched to target-specific + nodes, which represent individual instructions. In order for the targets + to match an instruction to your new node, you must add a def for that node + to the list in this file, with the appropriate type constraints. Look at + add, bswap, and fadd for examples.
    16. +
    17. lib/Target/PowerPC/PPCInstrInfo.td: + Each target has a tablegen file that describes the target's instruction + set. For targets that use the DAGToDAG instruction selection framework, + add a pattern for your new node that uses one or more target nodes. + Documentation for this is a bit sparse right now, but there are several + decent examples. See the patterns for rotl in + PPCInstrInfo.td.
    18. +
    19. TODO: document complex patterns.
    20. +
    21. llvm/test/Regression/CodeGen/*: Add test cases for your new node + to the test suite. llvm/test/Regression/CodeGen/X86/bswap.ll is + a good example.
    22. +
    + +
    + + + + + +
    + +

    WARNING: adding instructions changes the bytecode + format, and it will take some effort to maintain compatibility with + the previous version. Only add an instruction if it is absolutely + necessary.

    + +
      + +
    1. llvm/include/llvm/Instruction.def: + add a number for your instruction and an enum name
    2. + +
    3. llvm/include/llvm/Instructions.h: + add a definition for the class that will represent your instruction
    4. + +
    5. llvm/include/llvm/Support/InstVisitor.h: + add a prototype for a visitor to your new instruction type
    6. + +
    7. llvm/lib/AsmParser/Lexer.l: + add a new token to parse your instruction from assembly text file
    8. + +
    9. llvm/lib/AsmParser/llvmAsmParser.y: + add the grammar on how your instruction can be read and what it will + construct as a result
    10. + +
    11. llvm/lib/Bytecode/Reader/Reader.cpp: + add a case for your instruction and how it will be parsed from bytecode
    12. + +
    13. llvm/lib/VMCore/Instruction.cpp: + add a case for how your instruction will be printed out to assembly
    14. + +
    15. llvm/lib/VMCore/Instructions.cpp: + implement the class you defined in + llvm/include/llvm/Instructions.h
    16. + +
    17. Test your instruction
    18. + +
    19. llvm/lib/Target/*: + Add support for your instruction to code generators, or add a lowering + pass.
    20. + +
    21. llvm/test/Regression/*: add your test cases to the test suite.
    22. + +
    + +

    Also, you need to implement (or modify) any analyses or passes that you want + to understand this new instruction.

    + +
    + + + + + + +
    + +

    WARNING: adding new types changes the bytecode + format, and will break compatibility with currently-existing LLVM + installations. Only add new types if it is absolutely necessary.

    + +
    + + + + +
    + +
      + +
    1. llvm/include/llvm/Type.h: + add enum for the new type; add static Type* for this type
    2. + +
    3. llvm/lib/VMCore/Type.cpp: + add mapping from TypeID => Type*; + initialize the static Type*
    4. + +
    5. llvm/lib/AsmReader/Lexer.l: + add ability to parse in the type from text assembly
    6. + +
    7. llvm/lib/AsmReader/llvmAsmParser.y: + add a token for that type
    8. + +
    + +
    + + + + +
    + +
      +
    1. llvm/include/llvm/Type.h: + add enum for the new type; add a forward declaration of the type + also
    2. + +
    3. llvm/include/llvm/DerivedTypes.h: + add new class to represent new class in the hierarchy; add forward + declaration to the TypeMap value type
    4. + +
    5. llvm/lib/VMCore/Type.cpp: + add support for derived type to: +
      +
      + std::string getTypeDescription(const Type &Ty,
      +   std::vector<const Type*> &TypeStack)
      + bool TypesEqual(const Type *Ty, const Type *Ty2,
      +   std::map<const Type*, const Type*> & EqTypes)
      + 
      +
      + add necessary member functions for type, and factory methods
    6. + +
    7. llvm/lib/AsmReader/Lexer.l: + add ability to parse in the type from text assembly
    8. + +
    9. llvm/lib/ByteCode/Writer/Writer.cpp: + modify void BytecodeWriter::outputType(const Type *T) to serialize + your type
    10. + +
    11. llvm/lib/ByteCode/Reader/Reader.cpp: + modify const Type *BytecodeReader::ParseType() to read your data + type
    12. + +
    13. llvm/lib/VMCore/AsmWriter.cpp: + modify +
      +
      + void calcTypeName(const Type *Ty,
      +                   std::vector<const Type*> &TypeStack,
      +                   std::map<const Type*,std::string> &TypeNames,
      +                   std::string & Result)
      + 
      +
      + to output the new derived type +
    14. + + +
    + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + The LLVM Compiler Infrastructure +
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/FAQ.html diff -c /dev/null llvm-www/releases/1.8/docs/FAQ.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/FAQ.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,678 ---- + + + + LLVM: Frequently Asked Questions + + + + +
    + LLVM: Frequently Asked Questions +
    + +
      +
    1. License +
        +
      1. Why are the LLVM source code and the front-end distributed under different + licenses?
      2. +
      3. Does the University of Illinois Open Source License really qualify as an + "open source" license?
      4. +
      5. Can I modify LLVM source code and redistribute the modified source?
      6. +
      7. Can I modify LLVM source code and redistribute binaries or other tools + based on it, without redistributing the source?
      8. +
    2. + +
    3. Source code +
        +
      1. In what language is LLVM written?
      2. +
      3. How portable is the LLVM source code?
      4. +
    4. + +
    5. Build Problems +
        +
      1. When I run configure, it finds the wrong C compiler.
      2. +
      3. I compile the code, and I get some error about /localhome.
      4. +
      5. The configure script finds the right C compiler, but it uses the + LLVM linker from a previous build. What do I do?
      6. +
      7. When creating a dynamic library, I get a strange GLIBC error.
      8. +
      9. I've updated my source tree from CVS, and now my build is trying to use a + file/directory that doesn't exist.
      10. +
      11. I've modified a Makefile in my source tree, but my build tree keeps using + the old version. What do I do?
      12. +
      13. I've upgraded to a new version of LLVM, and I get strange build + errors.
      14. +
      15. I've built LLVM and am testing it, but the tests freeze.
      16. +
      17. Why do test results differ when I perform different types of builds?
      18. +
      19. Compiling LLVM with GCC 3.3.2 fails, what should I do?
      20. +
      21. When I use the test suite, all of the C Backend tests fail. What is + wrong?
      22. +
      23. After CVS update, rebuilding gives the error "No rule to make + target".
      24. +
    6. + +
    7. Source Languages +
        +
      1. What source languages are supported?
      2. +
      3. What support is there for higher level source + language constructs for building a compiler?
      4. +
      + +
    8. Using the GCC Front End +
        +
      1. + When I compile software that uses a configure script, the configure script + thinks my system has all of the header files and libraries it is testing + for. How do I get configure to work correctly? +
      2. + +
      3. + When I compile code using the LLVM GCC front end, it complains that it + cannot find libcrtend.a. +
      4. + +
      5. + How can I disable all optimizations when compiling code using the LLVM GCC front end? +
      6. + +
      7. Can I use LLVM to convert C++ code to C code?
      8. + +
      +
    9. + +
    10. Questions about code generated by the GCC front-end +
        +
      1. What is this __main() call that gets inserted into + main()?
      2. +
      3. What is this llvm.global_ctors and + _GLOBAL__I__tmp_webcompile... stuff that happens when I + #include <iostream>?
      4. +
      5. Where did all of my code go??
      6. +
      7. What is this "undef" thing that shows up in my code?
      8. +
      +
    11. +
    + +
    +

    Written by The LLVM Team

    +
    + + + +
    + License +
    + + +
    +

    Why are the LLVM source code and the front-end distributed under different + licenses?

    +
    + +
    +

    The C/C++ front-ends are based on GCC and must be distributed under the GPL. + Our aim is to distribute LLVM source code under a much less restrictive + license, in particular one that does not compel users who distribute tools based + on modifying the source to redistribute the modified source code as well.

    +
    + +
    +

    Does the University of Illinois Open Source License really qualify as an + "open source" license?

    +
    + +
    +

    Yes, the license is certified by the Open + Source Initiative (OSI).

    +
    + +
    +

    Can I modify LLVM source code and redistribute the modified source?

    +
    + +
    +

    Yes. The modified source distribution must retain the copyright notice and + follow the three bulletted conditions listed in the LLVM license.

    +
    + +
    +

    Can I modify LLVM source code and redistribute binaries or other tools based + on it, without redistributing the source?

    +
    + +
    +

    Yes, this is why we distribute LLVM under a less restrictive license than + GPL, as explained in the first question above.

    +
    + + + + + +
    +

    In what language is LLVM written?

    +
    + +
    +

    All of the LLVM tools and libraries are written in C++ with extensive use of + the STL.

    +
    + +
    +

    How portable is the LLVM source code?

    +
    + +
    +

    The LLVM source code should be portable to most modern UNIX-like operating + systems. Most of the code is written in standard C++ with operating system + services abstracted to a support library. The tools required to build and test + LLVM have been ported to a plethora of platforms.

    + +

    Some porting problems may exist in the following areas:

    + +
      + +
    • The GCC front end code is not as portable as the LLVM suite, so it may not + compile as well on unsupported platforms.
    • + +
    • The LLVM build system relies heavily on UNIX shell tools, like the Bourne + Shell and sed. Porting to systems without these tools (MacOS 9, Plan 9) will + require more effort.
    • + +
    + +
    + + + + + +
    +

    When I run configure, it finds the wrong C compiler.

    +
    + +
    + +

    The configure script attempts to locate first gcc and then + cc, unless it finds compiler paths set in CC and CXX + for the C and C++ compiler, respectively.

    + +

    If configure finds the wrong compiler, either adjust your + PATH environment variable or set CC and CXX + explicitly.

    + +
    + +
    +

    I compile the code, and I get some error about /localhome.

    +
    + +
    + +

    There are several possible causes for this. The first is that you didn't set + a pathname properly when using configure, and it defaulted to a + pathname that we use on our research machines.

    + +

    Another possibility is that we hardcoded a path in our Makefiles. If you see + this, please email the LLVM bug mailing list with the name of the offending + Makefile and a description of what is wrong with it.

    + +
    + +
    +

    The configure script finds the right C compiler, but it uses the + LLVM linker from a previous build. What do I do?

    +
    + +
    +

    The configure script uses the PATH to find executables, so + if it's grabbing the wrong linker/assembler/etc, there are two ways to fix + it:

    + +
      + +
    1. Adjust your PATH environment variable so that the correct + program appears first in the PATH. This may work, but may not be + convenient when you want them first in your path for other + work.

    2. + +
    3. Run configure with an alternative PATH that is + correct. In a Borne compatible shell, the syntax would be:

      + +

      PATH=[the path without the bad program] ./configure ...

      + +

      This is still somewhat inconvenient, but it allows configure + to do its work without having to adjust your PATH + permanently.

    4. + +
    + +
    + +
    +

    When creating a dynamic library, I get a strange GLIBC error.

    +
    + +
    +

    Under some operating systems (i.e. Linux), libtool does not work correctly if + GCC was compiled with the --disable-shared option. To work around this, install + your own version of GCC that has shared libraries enabled by default.

    +
    + +
    +

    I've updated my source tree from CVS, and now my build is trying to use a + file/directory that doesn't exist.

    +
    + +
    +

    You need to re-run configure in your object directory. When new Makefiles + are added to the source tree, they have to be copied over to the object tree in + order to be used by the build.

    +
    + +
    +

    I've modified a Makefile in my source tree, but my build tree keeps using the + old version. What do I do?

    +
    + +
    + +

    If the Makefile already exists in your object tree, you + can just run the following command in the top level directory of your object + tree:

    + +

    ./config.status <relative path to Makefile>

    + +

    If the Makefile is new, you will have to modify the configure script to copy + it over.

    + +
    + +
    +

    I've upgraded to a new version of LLVM, and I get strange build errors.

    +
    + +
    + +

    Sometimes, changes to the LLVM source code alters how the build system works. + Changes in libtool, autoconf, or header file dependencies are especially prone + to this sort of problem.

    + +

    The best thing to try is to remove the old files and re-build. In most + cases, this takes care of the problem. To do this, just type make + clean and then make in the directory that fails to build.

    + +
    + +
    +

    I've built LLVM and am testing it, but the tests freeze.

    +
    + +
    + +

    This is most likely occurring because you built a profile or release + (optimized) build of LLVM and have not specified the same information on the + gmake command line.

    + +

    For example, if you built LLVM with the command:

    + +

    gmake ENABLE_PROFILING=1 + +

    ...then you must run the tests with the following commands:

    + +

    cd llvm/test
    gmake ENABLE_PROFILING=1

    + +
    + +
    +

    Why do test results differ when I perform different types of builds?

    +
    + +
    + +

    The LLVM test suite is dependent upon several features of the LLVM tools and + libraries.

    + +

    First, the debugging assertions in code are not enabled in optimized or + profiling builds. Hence, tests that used to fail may pass.

    + +

    Second, some tests may rely upon debugging options or behavior that is only + available in the debug build. These tests will fail in an optimized or profile + build.

    + +
    + +
    +

    Compiling LLVM with GCC 3.3.2 fails, what should I do?

    +
    + +
    +

    This is a bug in GCC, and + affects projects other than LLVM. Try upgrading or downgrading your GCC.

    +
    + +
    +

    After CVS update, rebuilding gives the error "No rule to make target".

    +
    + +
    +

    If the error is of the form:

    + +
    + + gmake[2]: *** No rule to make target `/path/to/somefile', needed by + `/path/to/another/file.d'.
    + Stop. +
    +
    + +

    This may occur anytime files are moved within the CVS repository or removed + entirely. In this case, the best solution is to erase all .d files, + which list dependencies for source files, and rebuild:

    + +
    +
    + % cd $LLVM_OBJ_DIR
    + % rm -f `find . -name \*\.d` 
    + % gmake 
    + 
    +
    + +

    In other cases, it may be necessary to run make clean before + rebuilding.

    +
    + + + + + +
    +

    LLVM currently has full support for C and C++ source languages. These are + available through a special version of GCC that LLVM calls the + C Front End

    +

    There is an incomplete version of a Java front end available in the + llvm-java CVS repository. There is no documentation on this yet so + you'll need to download the code, compile it, and try it.

    +

    In the examples/BFtoLLVM directory is a translator for the + BrainF*** language (2002 Language Specification).

    +

    In the projects/Stacker directory is a compiler and runtime + library for the Stacker language, a "toy" language loosely based on Forth.

    +

    The PyPy developers are working on integrating LLVM into the PyPy backend + so that PyPy language can translate to LLVM.

    +
    + +
    +

    Currently, there isn't much. LLVM supports an intermediate representation + which is useful for code representation but will not support the high level + (abstract syntax tree) representation needed by most compilers. There are no + facilities for lexical nor semantic analysis. There is, however, a mostly + implemented configuration-driven + compiler driver which simplifies the task + of running optimizations, linking, and executable generation.

    +
    + + + +
    +

    + When I compile software that uses a configure script, the configure script + thinks my system has all of the header files and libraries it is testing for. + How do I get configure to work correctly? +

    +
    + +
    +

    + The configure script is getting things wrong because the LLVM linker allows + symbols to be undefined at link time (so that they can be resolved during JIT + or translation to the C back end). That is why configure thinks your system + "has everything." +

    +

    + To work around this, perform the following steps: +

    + +
      +
    1. + Make sure the CC and CXX environment variables contains the full path to the + LLVM GCC front end. +
    2. + +
    3. + Make sure that the regular C compiler is first in your PATH. +
    4. + +
    5. + Add the string "-Wl,-native" to your CFLAGS environment variable. +
    6. +
    + +

    + This will allow the gccld linker to create a native code executable instead of + a shell script that runs the JIT. Creating native code requires standard + linkage, which in turn will allow the configure script to find out if code is + not linking on your system because the feature isn't available on your system. +

    +
    + +
    +

    + When I compile code using the LLVM GCC front end, it complains that it cannot + find libcrtend.a. +

    +
    + +
    +

    + The only way this can happen is if you haven't installed the runtime library. To + correct this, do:

    +
    +   % cd llvm/runtime
    +   % make clean ; make install-bytecode
    + 
    +
    + +
    +

    + How can I disable all optimizations when compiling code using the LLVM GCC front end? +

    +
    + +
    +

    + Passing "-Wa,-disable-opt -Wl,-disable-opt" will disable *all* cleanup and + optimizations done at the llvm level, leaving you with the truly horrible + code that you desire. +

    +
    + + + + +
    +

    Yes, you can use LLVM to convert code from any language LLVM supports to C. + Note that the generated C code will be very low level (all loops are lowered + to gotos, etc) and not very pretty (comments are stripped, original source + formatting is totally lost, variables are renamed, expressions are regrouped), + so this may not be what you're looking for. However, this is a good way to add + C++ support for a processor that does not otherwise have a C++ compiler. +

    + +

    Use commands like this:

    + +
      +
    1. Compile your program as normal with llvm-g++:

    2. + +
      $ llvm-g++ x.cpp -o program
      + +

      or:

      + +
      + llvm-g++ a.cpp -c + llvm-g++ b.cpp -c + llvm-g++ a.o b.o -o program +
      + +

      With llvm-gcc3, this will generate program and program.bc. The .bc file is + the LLVM version of the program all linked together.

      + +
    3. Convert the LLVM code to C code, using the LLC tool with the C + backend:

    4. + +
      $ llc -march=c program.bc -o program.c
      + +
    5. Finally, compile the c file:

    6. + +
      $ cc x.c
      + +
    + +

    Note that, by default, the C backend does not support exception handling. + If you want/need it for a certain program, you can enable it by passing + "-enable-correct-eh-support" to the llc program. The resultant code will + use setjmp/longjmp to implement exception support that is correct but + relatively slow. +

    +
    + + + + + + +

    + + What is this __main() call that gets inserted into main()? +

    + +
    +

    + The __main call is inserted by the C/C++ compiler in order to guarantee + that static constructors and destructors are called when the program starts up + and shuts down. In C, you can create static constructors and destructors by + using GCC extensions, and in C++ you can do so by creating a global variable + whose class has a ctor or dtor. +

    + +

    + The actual implementation of __main lives in the + llvm/runtime/GCCLibraries/crtend/ directory in the source-base, and is + linked in automatically when you link the program. +

    +
    + + + +
    + +

    What is this llvm.global_ctors and + _GLOBAL__I__tmp_webcompile... stuff that happens when I #include + <iostream>?

    +
    + +
    + +

    If you #include the <iostream> header into a C++ translation unit, the + file will probably use the std::cin/std::cout/... global + objects. However, C++ does not guarantee an order of initialization between + static objects in different translation units, so if a static ctor/dtor in your + .cpp file used std::cout, for example, the object would not necessarily + be automatically initialized before your use.

    + +

    To make std::cout and friends work correctly in these scenarios, the + STL that we use declares a static object that gets created in every translation + unit that includes <iostream>. This object has a static + constructor and destructor that initializes and destroys the global iostream + objects before they could possibly be used in the file. The code that you see + in the .ll file corresponds to the constructor and destructor registration code. +

    + +

    If you would like to make it easier to understand the LLVM code + generated by the compiler in the demo page, consider using printf() + instead of iostreams to print values.

    + +
    + + + +

    + + Where did all of my code go?? +

    + +
    +

    + If you are using the LLVM demo page, you may often wonder what happened to all + of the code that you typed in. Remember that the demo script is running the + code through the LLVM optimizers, so if your code doesn't actually do anything + useful, it might all be deleted. +

    + +

    + To prevent this, make sure that the code is actually needed. For example, if + you are computing some expression, return the value from the function instead of + leaving it in a local variable. If you really want to constrain the optimizer, + you can read from and assign to volatile global variables. +

    +
    + + + +

    + +

    What is this "undef" thing that shows up in my code? +

    + +
    +

    + undef is the LLVM way of representing + a value that is not defined. You can get these if you do not initialize a + variable before you use it. For example, the C function:

    + +
    + int X() { int i; return i; } +
    + +

    Is compiled to "ret int undef" because "i" never has a value + specified for it. +

    +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/GarbageCollection.html diff -c /dev/null llvm-www/releases/1.8/docs/GarbageCollection.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/GarbageCollection.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,533 ---- + + + + Accurate Garbage Collection with LLVM + + + + +
    + Accurate Garbage Collection with LLVM +
    + +
      +
    1. Introduction + +
    2. + +
    3. Interfaces for user programs + +
    4. + +
    5. Implementing a garbage collector + +
    6. +
    7. GC implementations available + +
    8. + + +
    + +
    +

    Written by Chris Lattner

    +
    + + + + + +
    + +

    Garbage collection is a widely used technique that frees the programmer from + having to know the life-times of heap objects, making software easier to produce + and maintain. Many programming languages rely on garbage collection for + automatic memory management. There are two primary forms of garbage collection: + conservative and accurate.

    + +

    Conservative garbage collection often does not require any special support + from either the language or the compiler: it can handle non-type-safe + programming languages (such as C/C++) and does not require any special + information from the compiler. The [LINK] Boehm collector is an example of a + state-of-the-art conservative collector.

    + +

    Accurate garbage collection requires the ability to identify all pointers in + the program at run-time (which requires that the source-language be type-safe in + most cases). Identifying pointers at run-time requires compiler support to + locate all places that hold live pointer variables at run-time, including the + processor stack and registers.

    + +

    + Conservative garbage collection is attractive because it does not require any + special compiler support, but it does have problems. In particular, because the + conservative garbage collector cannot know that a particular word in the + machine is a pointer, it cannot move live objects in the heap (preventing the + use of compacting and generational GC algorithms) and it can occasionally suffer + from memory leaks due to integer values that happen to point to objects in the + program. In addition, some aggressive compiler transformations can break + conservative garbage collectors (though these seem rare in practice). +

    + +

    + Accurate garbage collectors do not suffer from any of these problems, but they + can suffer from degraded scalar optimization of the program. In particular, + because the runtime must be able to identify and update all pointers active in + the program, some optimizations are less effective. In practice, however, the + locality and performance benefits of using aggressive garbage allocation + techniques dominates any low-level losses. +

    + +

    + This document describes the mechanisms and interfaces provided by LLVM to + support accurate garbage collection. +

    + +
    + + + + +
    + +

    + LLVM provides support for a broad class of garbage collection algorithms, + including compacting semi-space collectors, mark-sweep collectors, generational + collectors, and even reference counting implementations. It includes support + for read and write barriers, and associating meta-data with stack objects (used for tagless garbage + collection). All LLVM code generators support garbage collection, including the + C backend. +

    + +

    + We hope that the primitive support built into LLVM is sufficient to support a + broad class of garbage collected languages, including Scheme, ML, scripting + languages, Java, C#, etc. That said, the implemented garbage collectors may + need to be extended to support language-specific features such as finalization, + weak references, or other features. As these needs are identified and + implemented, they should be added to this specification. +

    + +

    + LLVM does not currently support garbage collection of multi-threaded programs or + GC-safe points other than function calls, but these will be added in the future + as there is interest. +

    + +
    + + + + + +
    + +

    This section describes the interfaces provided by LLVM and by the garbage + collector run-time that should be used by user programs. As such, this is the + interface that front-end authors should generate code for. +

    + +
    + + + + +
    + +
    + void %llvm.gcroot(<ty>** %ptrloc, <ty2>* %metadata) +
    + +

    + The llvm.gcroot intrinsic is used to inform LLVM of a pointer variable + on the stack. The first argument contains the address of the variable on the + stack, and the second contains a pointer to metadata that should be associated + with the pointer (which must be a constant or global value address). At + runtime, the llvm.gcroot intrinsic stores a null pointer into the + specified location to initialize the pointer.

    + +

    + Consider the following fragment of Java code: +

    + +
    +        {
    +          Object X;   // A null-initialized reference to an object
    +          ...
    +        }
    + 
    + +

    + This block (which may be located in the middle of a function or in a loop nest), + could be compiled to this LLVM code: +

    + +
    + Entry:
    +    ;; In the entry block for the function, allocate the
    +    ;; stack space for X, which is an LLVM pointer.
    +    %X = alloca %Object*
    +    ...
    + 
    +    ;; "CodeBlock" is the block corresponding to the start
    +    ;;  of the scope above.
    + CodeBlock:
    +    ;; Initialize the object, telling LLVM that it is now live.
    +    ;; Java has type-tags on objects, so it doesn't need any
    +    ;; metadata.
    +    call void %llvm.gcroot(%Object** %X, sbyte* null)
    +    ...
    + 
    +    ;; As the pointer goes out of scope, store a null value into
    +    ;; it, to indicate that the value is no longer live.
    +    store %Object* null, %Object** %X
    +    ...
    + 
    + +
    + + + + +
    + +
    + sbyte *%llvm_gc_allocate(unsigned %Size) +
    + +

    The llvm_gc_allocate function is a global function defined by the + garbage collector implementation to allocate memory. It returns a + zeroed-out block of memory of the appropriate size.

    + +
    + + + + +
    + +
    + sbyte *%llvm.gcread(sbyte *, sbyte **)
    + void %llvm.gcwrite(sbyte*, sbyte*, sbyte**) +
    + +

    Several of the more interesting garbage collectors (e.g., generational + collectors) need to be informed when the mutator (the program that needs garbage + collection) reads or writes object references into the heap. In the case of a + generational collector, it needs to keep track of which "old" generation objects + have references stored into them. The amount of code that typically needs to be + executed is usually quite small (and not on the critical path of any + computation), so the overall performance impact of the inserted code is + tolerable.

    + +

    To support garbage collectors that use read or write barriers, LLVM provides + the llvm.gcread and llvm.gcwrite intrinsics. The first + intrinsic has exactly the same semantics as a non-volatile LLVM load and the + second has the same semantics as a non-volatile LLVM store, with the + additions that they also take a pointer to the start of the memory + object as an argument. At code generation + time, these intrinsics are replaced with calls into the garbage collector + (llvm_gc_read and llvm_gc_write respectively), which are then + inlined into the code. +

    + +

    + If you are writing a front-end for a garbage collected language, every load or + store of a reference from or to the heap should use these intrinsics instead of + normal LLVM loads/stores.

    + +
    + + + + +
    + +
    + void %llvm_gc_initialize(unsigned %InitialHeapSize) +
    + +

    + The llvm_gc_initialize function should be called once before any other + garbage collection functions are called. This gives the garbage collector the + chance to initialize itself and allocate the heap spaces. The initial heap size + to allocate should be specified as an argument. +

    + +
    + + + + +
    + +
    + void %llvm_gc_collect() +
    + +

    + The llvm_gc_collect function is exported by the garbage collector + implementations to provide a full collection, even when the heap is not + exhausted. This can be used by end-user code as a hint, and may be ignored by + the garbage collector. +

    + +
    + + + + + + +
    + +

    + Implementing a garbage collector for LLVM is fairly straight-forward. The LLVM + garbage collectors are provided in a form that makes them easy to link into the + language-specific runtime that a language front-end would use. They require + functionality from the language-specific runtime to get information about where pointers are located in heap objects. +

    + +

    The + implementation must include the llvm_gc_allocate and llvm_gc_collect functions, and it must implement + the read/write barrier functions as well. To + do this, it will probably have to trace through the roots + from the stack and understand the GC descriptors + for heap objects. Luckily, there are some example + implementations available. +

    +
    + + + + + +
    +
    + void *llvm_gc_read(void*, void **)
    + void llvm_gc_write(void*, void *, void**) +
    + +

    + These functions must be implemented in every garbage collector, even if + they do not need read/write barriers. In this case, just load or store the + pointer, then return. +

    + +

    + If an actual read or write barrier is needed, it should be straight-forward to + implement it. +

    + +
    + + + + +
    +

    + Garbage collector implementations make use of call-back functions that are + implemented by other parts of the LLVM system. +

    +
    + + + + +
    +
    + void llvm_cg_walk_gcroots(void (*FP)(void **Root, void *Meta)); +
    + +

    + The llvm_cg_walk_gcroots function is a function provided by the code + generator that iterates through all of the GC roots on the stack, calling the + specified function pointer with each record. For each GC root, the address of + the pointer and the meta-data (from the llvm.gcroot intrinsic) are provided. +

    +
    + + + + +
    + TODO +
    + + + + + +
    +

    + The three most common ways to keep track of where pointers live in heap objects + are (listed in order of space overhead required):

    + +
      +
    1. In languages with polymorphic objects, pointers from an object header are + usually used to identify the GC pointers in the heap object. This is common for + object-oriented languages like Self, Smalltalk, Java, or C#.
    2. + +
    3. If heap objects are not polymorphic, often the "shape" of the heap can be + determined from the roots of the heap or from some other meta-data [Appel89, Goldberg91, Tolmach94]. In this case, the garbage collector can + propagate the information around from meta data stored with the roots. This + often eliminates the need to have a header on objects in the heap. This is + common in the ML family.
    4. + +
    5. If all heap objects have pointers in the same locations, or pointers can be + distinguished just by looking at them (e.g., the low order bit is clear), no + book-keeping is needed at all. This is common for Lisp-like languages.
    6. +
    + +

    The LLVM garbage collectors are capable of supporting all of these styles of + language, including ones that mix various implementations. To do this, it + allows the source-language to associate meta-data with the stack roots, and the heap tracing routines can propagate the + information. In addition, LLVM allows the front-end to extract GC information + from in any form from a specific object pointer (this supports situations #1 and + #3). +

    + +

    Making this efficient

    + + + +
    + + + + + + + +
    + +

    + To make this more concrete, the currently implemented LLVM garbage collectors + all live in the llvm/runtime/GC/* directories in the LLVM source-base. + If you are interested in implementing an algorithm, there are many interesting + possibilities (mark/sweep, a generational collector, a reference counting + collector, etc), or you could choose to improve one of the existing algorithms. +

    + +
    + + + + +
    +

    + SemiSpace is a very simple copying collector. When it starts up, it allocates + two blocks of memory for the heap. It uses a simple bump-pointer allocator to + allocate memory from the first block until it runs out of space. When it runs + out of space, it traces through all of the roots of the program, copying blocks + to the other half of the memory space. +

    + +
    + + +
    + Possible Improvements +
    + +
    + +

    + If a collection cycle happens and the heap is not compacted very much (say less + than 25% of the allocated memory was freed), the memory regions should be + doubled in size.

    + +
    + + + + + +
    + +

    [Appel89] Runtime Tags Aren't Necessary. Andrew + W. Appel. Lisp and Symbolic Computation 19(7):703-705, July 1989.

    + +

    [Goldberg91] Tag-free garbage collection for + strongly typed programming languages. Benjamin Goldberg. ACM SIGPLAN + PLDI'91.

    + +

    [Tolmach94] Tag-free garbage collection using + explicit type parameters. Andrew Tolmach. Proceedings of the 1994 ACM + conference on LISP and functional programming.

    + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/GettingStarted.html diff -c /dev/null llvm-www/releases/1.8/docs/GettingStarted.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/GettingStarted.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,1601 ---- + + + + + Getting Started with LLVM System + + + + +
    + Getting Started with the LLVM System +
    + + + +
    +

    Written by: + John Criswell, + Chris Lattner, + Misha Brukman, + Vikram Adve, and + Guochun Shi. +

    +
    + + + +
    + Overview +
    + + +
    + +

    Welcome to LLVM! In order to get started, you first need to know some + basic information.

    + +

    First, LLVM comes in two pieces. The first piece is the LLVM suite. This + contains all of the tools, libraries, and header files needed to use the low + level virtual machine. It contains an assembler, disassembler, bytecode + analyzer, and bytecode optimizer. It also contains a test suite that can be + used to test the LLVM tools and the GCC front end.

    + +

    The second piece is the GCC front end. This component provides a version of + GCC that compiles C and C++ code into LLVM bytecode. Currently, the GCC front + end is a modified version of GCC 3.4 (we track the GCC 3.4 development). Once + compiled into LLVM bytecode, a program can be manipulated with the LLVM tools + from the LLVM suite.

    + +

    + There is a third, optional piece called llvm-test. It is a suite of programs + with a testing harness that can be used to further test LLVM's functionality + and performance. +

    + +
    + + + + + +
    + +

    Here's the short story for getting up and running quickly with LLVM:

    + +
      +
    1. Read the documentation.
    2. +
    3. Read the documentation.
    4. +
    5. Remember that you were warned twice about reading the documentation.
    6. +
    7. Install the GCC front end if you intend to compile C or C++: +
        +
      1. cd where-you-want-the-C-front-end-to-live
      2. +
      3. gunzip --stdout cfrontend.platform.tar.gz | tar -xvf - +
      4. +
      5. cd cfrontend/platform
        + ./fixheaders
      6. +
      7. Add the cfrontend's "bin" directory to your PATH variable.
      8. +
    8. + +
    9. Get the LLVM Source Code +
        +
      • With the distributed files (or use CVS): +
          +
        1. cd where-you-want-llvm-to-live +
        2. gunzip --stdout llvm-version.tar.gz | tar -xvf - +
      • + +
    10. + +
    11. [Optional] Get the Test Suite Source Code +
        +
      • With the distributed files (or use CVS): +
          +
        1. cd where-you-want-llvm-to-live +
        2. cd llvm/projects +
        3. gunzip --stdout llvm-test-version.tar.gz | tar -xvf - +
      • + +
    12. + + +
    13. Configure the LLVM Build Environment +
        +
      1. cd where-you-want-to-build-llvm
      2. +
      3. /path/to/llvm/configure [options]
        + Some common options: + +
          +
        • --prefix=directory +

          Specify for directory the full pathname of where you + want the LLVM tools and libraries to be installed (default + /usr/local).

        • +
        • --with-llvmgccdir=directory +

          Optionally, specify for directory the full pathname of the + C/C++ front end installation to use with this LLVM configuration. If + not specified, the PATH will be searched.

        • +
        • --enable-spec2000=directory +

          Enable the SPEC2000 benchmarks for testing. The SPEC2000 + benchmarks should be available in + directory.

        • +
        +
    14. + +
    15. Build the LLVM Suite: +
        +
      1. gmake -k |& tee gnumake.out +    # this is csh or tcsh syntax
      2. +
      3. If you get an "internal compiler error (ICE)" see below.
      4. +
      + +
    + +

    Consult the Getting Started with LLVM section for + detailed information on configuring and compiling LLVM. See Setting Up Your Environment for tips that simplify + working with the GCC front end and LLVM tools. Go to Program + Layout to learn about the layout of the source code tree.

    + +
    + + + + + +
    + +

    Before you begin to use the LLVM system, review the requirements given below. + This may save you some trouble by knowing ahead of time what hardware and + software you will need.

    + +
    + + +
    + Hardware +
    + +
    + +

    LLVM is known to work on the following platforms:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    OSArchCompilers
    Linuxx861GCC
    SolarisV9 (Ultrasparc)GCC
    FreeBSDx861GCC
    MacOS X2PowerPCGCC
    MacOS X2x86GCC
    Cygwin/Win32x861,8GCC 3.4.X, binutils 2.15
    MinGW/Win32x861,6,8GCC 3.4.X, binutils 2.15
    Linuxamd643GCC
    + +

    LLVM has partial support for the following platforms:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    OSArchCompilers
    Windowsx861Visual Studio .NET4,5
    AIX3,4PowerPCGCC
    Linux3,5PowerPCGCC
    Linux7AlphaGCC
    Linux7Itanium (IA-64)GCC
    HP-UX7Itanium (IA-64)HP aCC
    + +

    Notes:

    + + + +

    Note that you will need about 1-3 GB of space for a full LLVM build in Debug + mode, depending on the system (it is so large because of all the debugging + information and the fact that the libraries are statically linked into multiple + tools). If you do not need many of the tools and you are space-conscious, + you can disable them individually in llvm/tools/Makefile. The Release + build requires considerably less space.

    + +

    The LLVM suite may compile on other platforms, but it is not + guaranteed to do so. If compilation is successful, the LLVM utilities should be + able to assemble, disassemble, analyze, and optimize LLVM bytecode. Code + generation should work as well, although the generated native code may not work + on your platform.

    + +

    The GCC front end is not very portable at the moment. If you want to get it + to work on another platform, you can download a copy of the source and try to compile it on your platform.

    + +
    + + + +
    +

    Compiling LLVM requires that you have several software packages + installed. The table below lists those required packages. The Package column + is the usual name for the software package that LLVM depends on. The Version + column provides "known to work" versions of the package. The Notes column + describes how LLVM uses the package and provides other details.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PackageVersionNotes
    GNU Make3.79, 3.79.1Makefile/build processor
    GCC3.4.2C/C++ compiler1
    TeXinfo4.5For building the CFE
    Flex2.5.4LEX compiler
    Bison1.28, 1.35, 1.75, 1.875d, 2.0, or 2.1
    (not 1.85 or 1.875)
    YACC compiler
    CVS≥1.11CVS access to LLVM2
    DejaGnu1.4.2Automated test suite3
    tcl8.3, 8.4Automated test suite3
    expect5.38.0Automated test suite3
    perl≥5.6.0Nightly tester, utilities
    GNU M4 + 1.4Macro processor for configuration4
    GNU Autoconf2.59Configuration script builder4
    GNU Automake1.9.2aclocal macro generator4
    libtool1.5.10Shared library manager4
    + +

    Notes:

    + + +

    Additionally, your compilation host is expected to have the usual + plethora of Unix utilities. Specifically:

    +
      +
    • ar - archive library builder
    • +
    • bzip2* - bzip2 command for distribution generation
    • +
    • bunzip2* - bunzip2 command for distribution checking
    • +
    • chmod - change permissions on a file
    • +
    • cat - output concatenation utility
    • +
    • cp - copy files
    • +
    • date - print the current date/time
    • +
    • echo - print to standard output
    • +
    • egrep - extended regular expression search utility
    • +
    • etags - C/C++ tag file creator for vim/emacs
    • +
    • find - find files/dirs in a file system
    • +
    • grep - regular expression search utility
    • +
    • gzip* - gzip command for distribution generation
    • +
    • gunzip* - gunzip command for distribution checking
    • +
    • install - install directories/files
    • +
    • mkdir - create a directory
    • +
    • mv - move (rename) files
    • +
    • ranlib - symbol table builder for archive libraries
    • +
    • rm - remove (delete) files and directories
    • +
    • sed - stream editor for transforming output
    • +
    • sh - Bourne shell for make build scripts
    • +
    • tar - tape archive for distribution generation
    • +
    • test - test things in file system
    • +
    • unzip* - unzip command for distribution checking
    • +
    • zip* - zip command for distribution generation
    • +
    +
    + + + + +
    + +

    LLVM is very demanding of the host C++ compiler, and as such tends to expose + bugs in the compiler. In particular, several versions of GCC crash when trying + to compile LLVM. We routinely use GCC 3.3.3, 3.4.0, and Apple 4.0.1 + successfully with them (however, see below). Other versions of GCC will + probably work as well. GCC versions listed + here are known to not work. If you are using one of these versions, please try + to upgrade your GCC to something more recent. If you run into a problem with a + version of GCC not listed here, please let + us know. Please use the "gcc -v" command to find out which version + of GCC you are using. +

    + +

    GCC versions prior to 3.0: GCC 2.96.x and before had several + problems in the STL that effectively prevent it from compiling LLVM. +

    + +

    GCC 3.2.2: This version of GCC fails to compile LLVM.

    + +

    GCC 3.3.2: This version of GCC suffered from a serious bug which causes it to crash in + the "convert_from_eh_region_ranges_1" GCC function.

    + +

    Cygwin GCC 3.3.3: The version of GCC 3.3.3 commonly shipped with + Cygwin does not work. Please upgrade + to a newer version if possible.

    +

    SuSE GCC 3.3.3: The version of GCC 3.3.3 shipped with SuSE 9.1 (and + possibly others) does not compile LLVM correctly (it appears that exception + handling is broken in some cases). Please download the FSF 3.3.3 or upgrade + to a newer version of GCC.

    +

    IA-64 GCC 4.0.0: The IA-64 version of GCC 4.0.0 is known to + miscompile LLVM.

    +

    Apple Xcode 2.3: GCC crashes when compiling LLVM at -O3 (which is the + default with ENABLE_OPTIMIZED=1. To work around this, build with + "ENABLE_OPTIMIZED=1 OPTIMIZE_OPTION=-O2".

    +
    + + + + + + + +
    + +

    The remainder of this guide is meant to get you up and running with + LLVM and to give you some basic information about the LLVM environment.

    + +

    The later sections of this guide describe the general layout of the the LLVM source tree, a simple example using the LLVM tool chain, and links to find more information about LLVM or to get + help via e-mail.

    +
    + + + + +
    + +

    Throughout this manual, the following names are used to denote paths + specific to the local system and working environment. These are not + environment variables you need to set but just strings used in the rest + of this document below. In any of the examples below, simply replace + each of these names with the appropriate pathname on your local system. + All these paths are absolute:

    + +
    +
    SRC_ROOT +
    + This is the top level directory of the LLVM source tree. +

    + +

    OBJ_ROOT +
    + This is the top level directory of the LLVM object tree (i.e. the + tree where object files and compiled programs will be placed. It + can be the same as SRC_ROOT). +

    + +

    LLVMGCCDIR +
    + This is where the LLVM GCC Front End is installed. +

    + For the pre-built GCC front end binaries, the LLVMGCCDIR is + cfrontend/platform/llvm-gcc. +

    + +
    + + + + +
    + +

    + In order to compile and use LLVM, you may need to set some environment + variables. + +

    +
    LLVM_LIB_SEARCH_PATH=/path/to/your/bytecode/libs
    +
    [Optional] This environment variable helps LLVM linking tools find the + locations of your bytecode libraries. It is provided only as a + convenience since you can specify the paths using the -L options of the + tools and the C/C++ front-end will automatically use the bytecode files + installed in its + lib directory.
    +
    + +
    + + + + +
    + +

    + If you have the LLVM distribution, you will need to unpack it before you + can begin to compile it. LLVM is distributed as a set of two files: the LLVM + suite and the LLVM GCC front end compiled for your platform. There is an + additional test suite that is optional. Each file is a TAR archive that is + compressed with the gzip program. +

    + +

    The files are as follows, with x.y marking the version number: +

    +
    llvm-x.y.tar.gz
    +
    Source release for the LLVM libraries and tools.
    + +
    llvm-test-x.y.tar.gz
    +
    Source release for the LLVM test suite.
    + +
    cfrontend-x.y.source.tar.gz
    +
    Source release of the GCC front end.
    + +
    cfrontend-x.y.i686-redhat-linux-gnu.tar.gz
    +
    Binary release of the GCC front end for Linux/x86.
    + +
    llvm-gcc4-x.y.source.tar.gz
    +
    Source release of the llvm-gcc4 front end. See README.LLVM in the root + directory for build instructions.
    + +
    llvm-gcc4-x.y.powerpc-apple-darwin8.6.0.tar.gz
    +
    Binary release of the llvm-gcc4 front end for MacOS X/PowerPC.
    + +
    llvm-gcc4-x.y.i686-apple-darwin8.6.1.tar.gz
    +
    Binary release of the llvm-gcc4 front end for MacOS X/X86.
    +
    + +

    It is also possible to download the sources of the llvm-gcc4 front end from a + read-only subversion mirror at + svn://anonsvn.opensource.apple.com/svn/llvm/trunk.

    + +
    + + + + +
    + +

    If you have access to our CVS repository, you can get a fresh copy of + the entire source code. All you need to do is check it out from CVS as + follows:

    + +
      +
    • cd where-you-want-llvm-to-live +
    • cvs -d :pserver:anon at llvm-cvs.cs.uiuc.edu:/var/cvs/llvm login +
    • Hit the return key when prompted for the password. +
    • cvs -z3 -d :pserver:anon at llvm-cvs.cs.uiuc.edu:/var/cvs/llvm co + llvm +
    + +

    This will create an 'llvm' directory in the current + directory and fully populate it with the LLVM source code, Makefiles, + test directories, and local copies of documentation files.

    + +

    If you want to get a specific release (as opposed to the most recent + revision), you can specify a label. The following releases have the following + labels:

    + +
      +
    • Release 1.7: RELEASE_17
    • +
    • Release 1.6: RELEASE_16
    • +
    • Release 1.5: RELEASE_15
    • +
    • Release 1.4: RELEASE_14
    • +
    • Release 1.3: RELEASE_13
    • +
    • Release 1.2: RELEASE_12
    • +
    • Release 1.1: RELEASE_11
    • +
    • Release 1.0: RELEASE_1
    • +
    + +

    If you would like to get the LLVM test suite (a separate package as of 1.4), + you get it from the CVS repository:

    +
    +   cd llvm/projects
    +   cvs -z3 -d :pserver:anon at llvm-cvs.cs.uiuc.edu:/var/cvs/llvm co llvm-test
    + 
    +

    By placing it in the llvm/projects, it will be automatically + configured by the LLVM configure script as well as automatically updated when + you run cvs update.

    + +

    If you would like to get the GCC 3.4 front end source code, you can also get it from the CVS repository:

    + +
    +   cvs -z3 -d :pserver:anon at llvm-cvs.cs.uiuc.edu:/var/cvs/llvm co llvm-gcc
    + 
    + +

    Please note that you must follow these + instructions to successfully build the LLVM GCC front-end.

    + +
    + + + + +
    + +

    Before configuring and compiling the LLVM suite, you need to extract the LLVM + GCC front end from the binary distribution. It is used for building the + bytecode libraries later used by the GCC front end for linking programs, and its + location must be specified when the LLVM suite is configured.

    + +

    To install the GCC front end, do the following:

    + +
      +
    1. cd where-you-want-the-front-end-to-live
    2. +
    3. gunzip --stdout cfrontend-version.platform.tar.gz | tar -xvf + -
    4. +
    + +

    Next, you will need to fix your system header files:

    + +

    cd cfrontend/platform
    + ./fixheaders

    + +

    The binary versions of the GCC front end may not suit all of your needs. For + example, the binary distribution may include an old version of a system header + file, not "fix" a header file that needs to be fixed for GCC, or it may be + linked with libraries not available on your system.

    + +

    In cases like these, you may want to try building the GCC front end from source. This is + not for the faint of heart, so be forewarned.

    + +
    + + + + +
    + +

    Once checked out from the CVS repository, the LLVM suite source code must be + configured via the configure script. This script sets variables in the + various *.in files, most notably llvm/Makefile.config and + llvm/include/Config/config.h. It also populates OBJ_ROOT with + the Makefiles needed to begin building LLVM.

    + +

    The following environment variables are used by the configure + script to configure the build system:

    + + + + + + + + + + + +
    VariablePurpose
    CCTells configure which C compiler to use. By default, + configure will look for the first GCC C compiler in + PATH. Use this variable to override + configure's default behavior.
    CXXTells configure which C++ compiler to use. By default, + configure will look for the first GCC C++ compiler in + PATH. Use this variable to override + configure's default behavior.
    + +

    The following options can be used to set or enable LLVM specific options:

    + +
    +
    --with-llvmgccdir
    +
    Path to the LLVM C/C++ FrontEnd to be used with this LLVM configuration. + The value of this option should specify the full pathname of the C/C++ Front + End to be used. If this option is not provided, the PATH will be searched for + a program named llvm-gcc and the C/C++ FrontEnd install directory will + be inferred from the path found. If the option is not given, and no llvm-gcc + can be found in the path then a warning will be produced by + configure indicating this situation. LLVM may still be built with + the tools-only target but attempting to build the runtime libraries + will fail as these libraries require llvm-gcc and llvm-g++. See + Install the GCC Front End for details on installing + the C/C++ Front End. See + Bootstrapping the LLVM C/C++ Front-End + for details on building the C/C++ Front End.
    +
    --with-tclinclude
    +
    Path to the tcl include directory under which tclsh can be + found. Use this if you have multiple tcl installations on your machine and you + want to use a specific one (8.x) for LLVM. LLVM only uses tcl for running the + dejagnu based test suite in llvm/test. If you don't specify this + option, the LLVM configure script will search for the tcl 8.4 and 8.3 + releases. +

    +
    +
    --enable-optimized
    +
    + Enables optimized compilation by default (debugging symbols are removed + and GCC optimization flags are enabled). The default is to use an + unoptimized build (also known as a debug build). +

    +
    +
    --enable-debug-runtime
    +
    + Enables debug symbols in the runtime libraries. The default is to strip + debug symbols from the runtime libraries. +
    +
    --enable-jit
    +
    + Compile the Just In Time (JIT) compiler functionality. This is not + available + on all platforms. The default is dependent on platform, so it is best + to explicitly enable it if you want it. +

    +
    +
    --enable-targets=target-option
    +
    Controls which targets will be built and linked into llc. The default + value for target_options is "all" which builds and links all + available targets. The value "host-only" can be specified to build only a + native compiler (no cross-compiler targets available). The "native" target is + selected as the target of the build host. You can also specify a comma + separated list of target names that you want available in llc. The target + names use all lower case. The current set of targets is:
    + alpha, ia64, powerpc, skeleton, sparc, x86. +

    +
    --enable-doxygen
    +
    Look for the doxygen program and enable construction of doxygen based + documentation from the source code. This is disabled by default because + generating the documentation can take a long time and producess 100s of + megabytes of output.
    +
    + +

    To configure LLVM, follow these steps:

    + +
      +
    1. Change directory into the object root directory: +
      + cd OBJ_ROOT +

      + +

    2. Run the configure script located in the LLVM source tree: +
      + SRC_ROOT/configure --prefix=/install/path [other options] +

      +

    + +
    + + + + +
    + +

    Once you have configured LLVM, you can build it. There are three types of + builds:

    + +
    +
    Debug Builds +
    + These builds are the default when one types gmake (unless the + --enable-optimized option was used during configuration). The + build system will compile the tools and libraries with debugging + information. +

    + +

    Release (Optimized) Builds +
    + These builds are enabled with the --enable-optimized option to + configure or by specifying ENABLE_OPTIMIZED=1 on the + gmake command line. For these builds, the build system will + compile the tools and libraries with GCC optimizations enabled and strip + debugging information from the libraries and executables it generates. +

    + +

    Profile Builds +
    + These builds are for use with profiling. They compile profiling + information into the code for use with programs like gprof. + Profile builds must be started by specifying ENABLE_PROFILING=1 + on the gmake command line. +
    + +

    Once you have LLVM configured, you can build it by entering the + OBJ_ROOT directory and issuing the following command:

    + +

    gmake

    + +

    If the build fails, please check here to see if you + are using a version of GCC that is known not to compile LLVM.

    + +

    + If you have multiple processors in your machine, you may wish to use some of + the parallel build options provided by GNU Make. For example, you could use the + command:

    + +

    gmake -j2

    + +

    There are several special targets which are useful when working with the LLVM + source code:

    + +
    +
    gmake clean +
    + Removes all files generated by the build. This includes object files, + generated C/C++ files, libraries, and executables. +

    + +

    gmake dist-clean +
    + Removes everything that gmake clean does, but also removes files + generated by configure. It attempts to return the source tree to the + original state in which it was shipped. +

    + +

    gmake install +
    + Installs LLVM header files, libraries, tools, and documentation in a + hierarchy + under $PREFIX, specified with ./configure --prefix=[dir], which + defaults to /usr/local. +

    + +

    gmake -C runtime install-bytecode +
    + Assuming you built LLVM into $OBJDIR, when this command is run, it will + install bytecode libraries into the GCC front end's bytecode library + directory. If you need to update your bytecode libraries, + this is the target to use once you've built them. +

    +

    + +

    Please see the Makefile Guide for further + details on these make targets and descriptions of other targets + available.

    + +

    It is also possible to override default values from configure by + declaring variables on the command line. The following are some examples:

    + +
    +
    gmake ENABLE_OPTIMIZED=1 +
    + Perform a Release (Optimized) build. +

    + +

    gmake ENABLE_OPTIMIZED=1 DISABLE_ASSERTIONS=1 +
    + Perform a Release (Optimized) build without assertions enabled. +

    + +

    gmake ENABLE_PROFILING=1 +
    + Perform a Profiling build. +

    + +

    gmake VERBOSE=1 +
    + Print what gmake is doing on standard output. +

    + +

    gmake TOOL_VERBOSE=1
    +
    Ask each tool invoked by the makefiles to print out what it is doing on + the standard output. This also implies VERBOSE=1. +

    +
    + +

    Every directory in the LLVM object tree includes a Makefile to build + it and any subdirectories that it contains. Entering any directory inside the + LLVM object tree and typing gmake should rebuild anything in or below + that directory that is out of date.

    + +
    + + + + +
    +

    It is possible to cross-compile LLVM. That is, you can create LLVM + executables and libraries for a platform different than the one one which you + are compiling. To do this, a few additional steps are + required. 1 To cross-compile LLVM, use + these instructions:

    +
      +
    1. Configure and build LLVM as a native compiler. You will need + just TableGen from that build. +
        +
      • If you have $LLVM_OBJ_ROOT=$LLVM_SRC_ROOT just execute + make -C utils/TableGen after configuring.
      • +
      • Otherwise you will need to monitor building process and terminate + it just after TableGen was built.
      • +
      +
    2. +
    3. Copy the TableGen binary to somewhere safe (out of your build tree). +
    4. +
    5. Configure LLVM to build with a cross-compiler. To do this, supply the + configure script with --build and --host options that + are different. The values of these options must be legal target triples + that your GCC compiler supports.
    6. +
    7. Put the saved TableGen executable into the + into $LLVM_OBJ_ROOT/{BUILD_TYPE}/bin directory (e.g. into + .../Release/bin for a Release build).
    8. +
    9. Build LLVM as usual.
    10. +
    +

    The result of such a build will produce executables that are not executable + on your build host (--build option) but can be executed on your compile host + (--host option).

    +

    Notes:

    +
    +
      +
    1. Cross-compiling was tested only with Linux as + build platform and Windows as host using mingw32 cross-compiler. Other + combinations have not been tested.
    2. +
    +
    +
    + + + + +
    + +

    The LLVM build system is capable of sharing a single LLVM source tree among + several LLVM builds. Hence, it is possible to build LLVM for several different + platforms or configurations using the same source tree.

    + +

    This is accomplished in the typical autoconf manner:

    + +
      +
    • Change directory to where the LLVM object files should live:

      + +

      cd OBJ_ROOT

    • + +
    • Run the configure script found in the LLVM source + directory:

      + +

      SRC_ROOT/configure

    • +
    + +

    The LLVM build will place files underneath OBJ_ROOT in directories + named after the build type:

    + +
    +
    Debug Builds +
    +
    +
    Tools +
    OBJ_ROOT/Debug/bin +
    Libraries +
    OBJ_ROOT/Debug/lib +
    +

    + +

    Release Builds +
    +
    +
    Tools +
    OBJ_ROOT/Release/bin +
    Libraries +
    OBJ_ROOT/Release/lib +
    +

    + +

    Profile Builds +
    +
    +
    Tools +
    OBJ_ROOT/Profile/bin +
    Libraries +
    OBJ_ROOT/Profile/lib +
    +
    + +
    + + + + +
    + +

    + If you're running on a Linux system that supports the " + binfmt_misc" + module, and you have root access on the system, you can set your system up to + execute LLVM bytecode files directly. To do this, use commands like this (the + first command may not be required if you are already using the module):

    + +
    +
    +    $ mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
    +    $ echo ':llvm:M::llvm::/path/to/lli:' > /proc/sys/fs/binfmt_misc/register
    +    $ chmod u+x hello.bc                (if needed)
    +    $ ./hello.bc
    + 
    +
    + +

    + This allows you to execute LLVM bytecode files directly. Thanks to Jack + Cummings for pointing this out! +

    + +
    + + + + + + +
    + +

    One useful source of information about the LLVM source base is the LLVM doxygen documentation available at http://llvm.org/doxygen/. + The following is a brief introduction to code layout:

    + +
    + + + +
    +

    Every directory checked out of CVS will contain a CVS directory; for + the most part these can just be ignored.

    +
    + + + +
    +

    This directory contains some simple examples of how to use the LLVM IR and + JIT.

    +
    + + + +
    + +

    This directory contains public header files exported from the LLVM + library. The three main subdirectories of this directory are:

    + +
    +
    llvm/include/llvm
    +
    This directory contains all of the LLVM specific header files. This + directory also has subdirectories for different portions of LLVM: + Analysis, CodeGen, Target, Transforms, + etc...
    + +
    llvm/include/llvm/Support
    +
    This directory contains generic support libraries that are provided with + LLVM but not necessarily specific to LLVM. For example, some C++ STL utilities + and a Command Line option processing library store their header files here. +
    + +
    llvm/include/llvm/Config
    +
    This directory contains header files configured by the configure + script. They wrap "standard" UNIX and C header files. Source code can + include these header files which automatically take care of the conditional + #includes that the configure script generates.
    +
    +
    + + + +
    + +

    This directory contains most of the source files of the LLVM system. In LLVM, + almost all code exists in libraries, making it very easy to share code among the + different tools.

    + +
    +
    llvm/lib/VMCore/
    +
    This directory holds the core LLVM source files that implement core + classes like Instruction and BasicBlock.
    + +
    llvm/lib/AsmParser/
    +
    This directory holds the source code for the LLVM assembly language parser + library.
    + +
    llvm/lib/ByteCode/
    +
    This directory holds code for reading and write LLVM bytecode.
    + +
    llvm/lib/Analysis/
    This directory contains a variety of + different program analyses, such as Dominator Information, Call Graphs, + Induction Variables, Interval Identification, Natural Loop Identification, + etc.
    + +
    llvm/lib/Transforms/
    +
    This directory contains the source code for the LLVM to LLVM program + transformations, such as Aggressive Dead Code Elimination, Sparse Conditional + Constant Propagation, Inlining, Loop Invariant Code Motion, Dead Global + Elimination, and many others.
    + +
    llvm/lib/Target/
    +
    This directory contains files that describe various target architectures + for code generation. For example, the llvm/lib/Target/X86 + directory holds the X86 machine description while + llvm/lib/Target/CBackend implements the LLVM-to-C converter.
    + +
    llvm/lib/CodeGen/
    +
    This directory contains the major parts of the code generator: Instruction + Selector, Instruction Scheduling, and Register Allocation.
    + +
    llvm/lib/Debugger/
    +
    This directory contains the source level debugger library that makes + it possible to instrument LLVM programs so that a debugger could identify + source code locations at which the program is executing.
    + +
    llvm/lib/ExecutionEngine/
    +
    This directory contains libraries for executing LLVM bytecode directly + at runtime in both interpreted and JIT compiled fashions.
    + +
    llvm/lib/Support/
    +
    This directory contains the source code that corresponds to the header + files located in llvm/include/Support/.
    + +
    llvm/lib/System/
    +
    This directory contains the operating system abstraction layer that + shields LLVM from platform-specific coding.
    +
    + +
    + + + +
    +

    This directory contains projects that are not strictly part of LLVM but are + shipped with LLVM. This is also the directory where you should create your own + LLVM-based projects. See llvm/projects/sample for an example of how + to set up your own project. See llvm/projects/Stacker for a fully + functional example of a compiler front end.

    +
    + + + +
    + +

    This directory contains libraries which are compiled into LLVM bytecode and + used when linking programs with the GCC front end. Most of these libraries are + skeleton versions of real libraries; for example, libc is a stripped down + version of glibc.

    + +

    Unlike the rest of the LLVM suite, this directory needs the LLVM GCC front + end to compile.

    + +
    + + + +
    +

    This directory contains feature and regression tests and other basic sanity + checks on the LLVM infrastructure. These are intended to run quickly and cover + a lot of territory without being exhaustive.

    +
    + + + +
    +

    This is not a directory in the normal llvm module; it is a separate CVS + module that must be checked out (usually to projects/llvm-test). This + module contains a comprehensive correctness, performance, and benchmarking + test + suite for LLVM. It is a separate CVS module because not every LLVM user is + interested in downloading or building such a comprehensive test suite. For + further details on this test suite, please see the + Testing Guide document.

    +
    + + + +
    + +

    The tools directory contains the executables built out of the + libraries above, which form the main part of the user interface. You can + always get help for a tool by typing tool_name --help. The + following is a brief introduction to the most important tools. More detailed + information is in the Command Guide.

    + +
    +
    analyze
    +
    analyze is used to run a specific + analysis on an input LLVM bytecode file and print out the results. It is + primarily useful for debugging analyses, or familiarizing yourself with + what an analysis does.
    + +
    bugpoint
    +
    bugpoint is used to debug + optimization passes or code generation backends by narrowing down the + given test case to the minimum number of passes and/or instructions that + still cause a problem, whether it is a crash or miscompilation. See HowToSubmitABug.html for more information + on using bugpoint.
    + +
    llvmc
    +
    The LLVM Compiler Driver. This program can + be configured to utilize both LLVM and non-LLVM compilation tools to enable + pre-processing, translation, optimization, assembly, and linking of programs + all from one command line. llvmc also takes care of processing the + dependent libraries found in bytecode. This reduces the need to get the + traditional -l<name> options right on the command line. Please + note that this tool, while functional, is still experimental and not feature + complete.
    + +
    llvm-ar
    +
    The archiver produces an archive containing + the given LLVM bytecode files, optionally with an index for faster + lookup.
    + +
    llvm-as
    +
    The assembler transforms the human readable LLVM assembly to LLVM + bytecode.
    + +
    llvm-dis
    +
    The disassembler transforms the LLVM bytecode to human readable + LLVM assembly.
    + +
    llvm-ld
    +
    llvm-ld is very similar to gccld and provides a general purpose + and extensible linker for LLVM. This is the linker invoked by llvmc. + It allows optimization modules to be loaded so that language specific + optimizations can be applied at link time. This tool is considered + experimental.
    + +
    llvm-link
    +
    llvm-link, not surprisingly, links multiple LLVM modules into + a single program.
    + +
    lli
    +
    lli is the LLVM interpreter, which + can directly execute LLVM bytecode (although very slowly...). In addition + to a simple interpreter, lli also has a tracing mode (entered by + specifying -trace on the command line). Finally, for + architectures that support it (currently x86, Sparc, and PowerPC), by default, + lli will function as a Just-In-Time compiler (if the + functionality was compiled in), and will execute the code much + faster than the interpreter.
    + +
    llc
    +
    llc is the LLVM backend compiler, which + translates LLVM bytecode to a native code assembly file or to C code (with + the -march=c option).
    + +
    llvm-gcc
    +
    llvm-gcc is a GCC-based C frontend + that has been retargeted to emit LLVM code as the machine code output. It + works just like any other GCC compiler, taking the typical -c, -S, -E, + -o options that are typically used. The source code for the + llvm-gcc tool is available as a separate CVS module. +
    +
    +
    gccas
    +
    This tool is invoked by the llvm-gcc frontend as the + "assembler" part of the compiler. This tool actually assembles LLVM + assembly to LLVM bytecode, performs a variety of optimizations, and + outputs LLVM bytecode. Thus when you invoke + llvm-gcc -c x.c -o x.o, you are causing gccas to be + run, which writes the x.o file (which is an LLVM bytecode file + that can be disassembled or manipulated just like any other bytecode + file). The command line interface to gccas is designed to be + as close as possible to the system `as' utility so that + the gcc frontend itself did not have to be modified to interface to + a "weird" assembler.
    + +
    gccld
    +
    gccld links together several LLVM bytecode files into one + bytecode file and does some optimization. It is the linker invoked by + the GCC frontend when multiple .o files need to be linked together. + Like gccas, the command line interface of gccld is + designed to match the system linker, to aid interfacing with the GCC + frontend.
    +
    +
    +
    + +
    opt
    +
    opt reads LLVM bytecode, applies a + series of LLVM to LLVM transformations (which are specified on the command + line), and then outputs the resultant bytecode. The 'opt --help' + command is a good way to get a list of the program transformations + available in LLVM.
    +
    +
    + + + +
    + +

    This directory contains utilities for working with LLVM source code, and some + of the utilities are actually required as part of the build process because they + are code generators for parts of LLVM infrastructure.

    + +
    +
    codegen-diff
    codegen-diff is a script + that finds differences between code that LLC generates and code that LLI + generates. This is a useful tool if you are debugging one of them, + assuming that the other generates correct output. For the full user + manual, run `perldoc codegen-diff'.

    + +

    cvsupdate
    cvsupdate is a script that will + update your CVS tree, but produce a much cleaner and more organized output + than simply running `cvs -z3 up -dP' will. For example, it will group + together all the new and updated files and modified files in separate + sections, so you can see at a glance what has changed. If you are at the + top of your LLVM CVS tree, running utils/cvsupdate is the + preferred way of updating the tree.

    + +

    emacs/
    The emacs directory contains + syntax-highlighting files which will work with Emacs and XEmacs editors, + providing syntax highlighting support for LLVM assembly files and TableGen + description files. For information on how to use the syntax files, consult + the README file in that directory.

    + +

    getsrcs.sh
    The getsrcs.sh script finds + and outputs all non-generated source files, which is useful if one wishes + to do a lot of development across directories and does not want to + individually find each file. One way to use it is to run, for example: + xemacs `utils/getsources.sh` from the top of your LLVM source + tree.

    + +

    llvmgrep
    +
    This little tool performs an "egrep -H -n" on each source file in LLVM and + passes to it a regular expression provided on llvmgrep's command + line. This is a very efficient way of searching the source base for a + particular regular expression.
    + +
    makellvm
    The makellvm script compiles all + files in the current directory and then compiles and links the tool that + is the first argument. For example, assuming you are in the directory + llvm/lib/Target/Sparc, if makellvm is in your path, + simply running makellvm llc will make a build of the current + directory, switch to directory llvm/tools/llc and build it, + causing a re-linking of LLC.

    + +

    NightlyTest.pl and + NightlyTestTemplate.html
    These files are used in a + cron script to generate nightly status reports of the functionality of + tools, and the results can be seen by following the appropriate link on + the LLVM homepage.

    + +

    TableGen/
    The TableGen directory contains + the tool used to generate register descriptions, instruction set + descriptions, and even assemblers from common TableGen description + files.

    + +

    vim/
    The vim directory contains + syntax-highlighting files which will work with the VIM editor, providing + syntax highlighting support for LLVM assembly files and TableGen + description files. For information on how to use the syntax files, consult + the README file in that directory.

    + +

    + +
    + + + +
    +

    This directory contains build scripts and project files for use with + Visual C++. This allows developers on Windows to build LLVM without the need + for Cygwin. The contents of this directory should be considered experimental + at this time. +

    +
    + + + + +
    + +
      +
    1. First, create a simple C file, name it 'hello.c': +
      +    #include <stdio.h>
      +    int main() {
      +      printf("hello world\n");
      +      return 0;
      +    }
      +        
    2. + +
    3. Next, compile the C file into a LLVM bytecode file:

      +

      % llvm-gcc hello.c -o hello

      + +

      Note that you should have already built the tools and they have to be + in your path, at least gccas and gccld.

      + +

      This will create two result files: hello and + hello.bc. The hello.bc is the LLVM bytecode that + corresponds the the compiled program and the library facilities that it + required. hello is a simple shell script that runs the bytecode + file with lli, making the result directly executable. Note that + all LLVM optimizations are enabled by default, so there is no need for a + "-O3" switch.

    4. + +
    5. Run the program. To make sure the program ran, execute one of the + following commands:

      + +

      % ./hello

      + +

      or

      + +

      % lli hello.bc

    6. + +
    7. Use the llvm-dis utility to take a look at the LLVM assembly + code:

      + +

      % llvm-dis < hello.bc | less

    8. + +
    9. Compile the program to native assembly using the LLC code + generator:

      + +

      % llc hello.bc -o hello.s

      + +
    10. Assemble the native assembly language file into a program:

      + +

      Solaris:% /opt/SUNWspro/bin/cc -xarch=v9 hello.s -o hello.native

      +

      Others:% gcc hello.s -o hello.native

      + +
    11. Execute the native code program:

      + +

      % ./hello.native

    12. + +
    + +
    + + + + + +
    + +

    If you are having problems building or using LLVM, or if you have any other + general questions about LLVM, please consult the Frequently + Asked Questions page.

    + +
    + + +
    + Links +
    + + +
    + +

    This document is just an introduction to how to use LLVM to do + some simple things... there are many more interesting and complicated things + that you can do that aren't documented here (but we'll gladly accept a patch + if you want to write something up!). For more information about LLVM, check + out:

    + + + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + Reid Spencer
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + Index: llvm-www/releases/1.8/docs/GettingStartedVS.html diff -c /dev/null llvm-www/releases/1.8/docs/GettingStartedVS.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/GettingStartedVS.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,353 ---- + + + + + Getting Started with LLVM System for Microsoft Visual Studio + + + + +
    + Getting Started with the LLVM System using Microsoft Visual Studio +
    + + + +
    +

    Written by: + Jeff Cohen +

    +
    + + + +
    + Overview +
    + + +
    + +

    The Visual Studio port at this time is experimental. It is suitable for + use only if you are writing your own compiler front end or otherwise have a + need to dynamically generate machine code. The JIT and interpreter are + functional, but it is currently not possible to generate assembly code which + is then assembled into an executable. You can indirectly create executables + by using the C back end.

    + +

    To emphasize, there is no C/C++ front end currently available. + llvm-gcc is based on GCC, which cannot be bootstrapped using VC++. + Eventually there should be a llvm-gcc based on Cygwin or MinGW that + is usable. There is also the option of generating bytecode files on Unix and + copying them over to Windows. But be aware the odds of linking C++ code + compiled with llvm-gcc with code compiled with VC++ is essentially + zero.

    + +

    The LLVM test suite cannot be run on the Visual Studio port at this + time.

    + +

    Most of the tools build and work. llvm-db does not build at this + time. bugpoint does build, but does not work. + +

    Additional information about the LLVM directory structure and tool chain + can be found on the main Getting Started + page.

    + +
    + + + + + +
    + +

    Here's the short story for getting up and running quickly with LLVM:

    + +
      +
    1. Read the documentation.
    2. +
    3. Read the documentation.
    4. +
    5. Remember that you were warned twice about reading the documentation.
    6. + +
    7. Get the Source Code +
        +
      • With the distributed files: +
          +
        1. cd where-you-want-llvm-to-live +
        2. gunzip --stdout llvm-version.tar.gz | tar -xvf - +       or use WinZip +
        3. cd llvm
        4. +
      • + +
      • With anonymous CVS access: +
          +
        1. cd where-you-want-llvm-to-live
        2. +
        3. cvs -d + :pserver:anon at llvm-cvs.cs.uiuc.edu:/var/cvs/llvm login
        4. +
        5. Hit the return key when prompted for the password. +
        6. cvs -z3 -d :pserver:anon at llvm-cvs.cs.uiuc.edu:/var/cvs/llvm + co llvm
        7. +
        8. cd llvm
        9. +
        10. cvs up -P -d
        11. +
      • +
    8. + +
    9. Start Visual Studio +
        +
      1. Simply double click on the solution file llvm/win32/llvm.sln. +
      2. +
    10. + +
    11. Build the LLVM Suite: +
        +
      1. Simply build the solution.
      2. +
      3. The Fibonacci project is a sample program that uses the JIT. Modify + the project's debugging properties to provide a numeric command line + argument. The program will print the corresponding fibonacci value.
      4. +
    12. + +
    + +

    It is strongly encouraged that you get the latest version from CVS. Much + progress has been made since the 1.4 release.

    + +
    + + + + + +
    + +

    Before you begin to use the LLVM system, review the requirements given + below. This may save you some trouble by knowing ahead of time what hardware + and software you will need.

    + +
    + + +
    + Hardware +
    + +
    + +

    Any system that can adequately run Visual Studio .NET 2003 is fine. The + LLVM source tree and object files, libraries and executables will consume + approximately 3GB.

    + +
    + + + +
    + +

    You will need Visual Studio .NET 2003. Earlier versions cannot open the + solution/project files. The VS 2005 beta can, but will migrate these files + to its own format in the process. While it should work with the VS 2005 + beta, there are no guarantees and there is no support for it at this time. + It has been reported that VC++ Express also works.

    + +

    If you plan to modify any .y or .l files, you will need to have bison + and/or flex installed where Visual Studio can find them. Otherwise, you do + not need them and the pre-generated files that come with the source tree + will be used.

    + +
    + + + + + +
    + +

    The remainder of this guide is meant to get you up and running with + LLVM using Visual Studio and to give you some basic information about the LLVM + environment.

    + +
    + + + + +
    + +

    Throughout this manual, the following names are used to denote paths + specific to the local system and working environment. These are not + environment variables you need to set but just strings used in the rest + of this document below. In any of the examples below, simply replace + each of these names with the appropriate pathname on your local system. + All these paths are absolute:

    + +
    +
    SRC_ROOT +
    + This is the top level directory of the LLVM source tree. +

    + +

    OBJ_ROOT +
    + This is the top level directory of the LLVM object tree (i.e. the + tree where object files and compiled programs will be placed. It + is fixed at SRC_ROOT/win32). +

    +

    + +
    + + + + +
    + +

    The object files are placed under OBJ_ROOT/Debug for debug builds + and OBJ_ROOT/Release for release (optimized) builds. These include + both executables and libararies that your application can link against. + +

    The files that configure would create when building on Unix are + created by the Configure project and placed in + OBJ_ROOT/llvm. You application must have OBJ_ROOT in its include + search path just before SRC_ROOT/include. + +

    + + + + + +
    + +
      +
    1. First, create a simple C file, name it 'hello.c': +
      +    #include <stdio.h>
      +    int main() {
      +      printf("hello world\n");
      +      return 0;
      +    }
      +        
    2. + +
    3. Next, compile the C file into a LLVM bytecode file:

      +

      % llvm-gcc hello.c -o hello

      + +

      Note that you should have already built the tools and they have to be + in your path, at least gccas and gccld.

      + +

      This will create two result files: hello and + hello.bc. The hello.bc is the LLVM bytecode that + corresponds the the compiled program and the library facilities that it + required. hello is a simple shell script that runs the bytecode + file with lli, making the result directly executable. Note that + all LLVM optimizations are enabled by default, so there is no need for a + "-O3" switch.

      + +

      Note: while you cannot do this step on Windows, you can do it on a + Unix system and transfer hello.bc to Windows.

    4. + +
    5. Run the program using the just-in-time compiler:

      + +

      % lli hello.bc

    6. + +
    7. Use the llvm-dis utility to take a look at the LLVM assembly + code:

      + +

      % llvm-dis < hello.bc | more

    8. + +
    9. Compile the program to C using the LLC code generator:

      + +

      % llc -march=c hello.bc

    10. + +
    11. Compile to binary using Microsoft C:

      + +

      % cl hello.cbe.c

    12. + +
    13. Execute the native code program:

      + +

      % hello.cbe.exe

    14. + +
    + +
    + + + + + +
    + +

    If you are having problems building or using LLVM, or if you have any other + general questions about LLVM, please consult the Frequently + Asked Questions page.

    + +
    + + +
    + Links +
    + + +
    + +

    This document is just an introduction to how to use LLVM to do + some simple things... there are many more interesting and complicated things + that you can do that aren't documented here (but we'll gladly accept a patch + if you want to write something up!). For more information about LLVM, check + out:

    + + + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Jeff Cohen
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + Index: llvm-www/releases/1.8/docs/HowToReleaseLLVM.html diff -c /dev/null llvm-www/releases/1.8/docs/HowToReleaseLLVM.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/HowToReleaseLLVM.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,474 ---- + + + + How To Release LLVM To The Public + + + + +
    How To Release LLVM To The Public
    +

    NOTE: THIS DOCUMENT IS A WORK IN PROGRESS!

    +
      +
    1. Introduction
    2. +
    3. Release Process
    4. +
    5. Distribution Targets
    6. +
    +
    +

    Written by Reid Spencer, + John Criswell

    +
    + + + + + +
    +

    This document collects information about successfully releasing LLVM to the + public. It is the release manager's guide to ensuring that a high quality build + of LLVM is released. Mostly, it's just a bunch of reminders of things to do at + release time so we don't inadvertently ship something that is utility + deficient.

    + +

    + There are three main tasks for building a release of LLVM: +

      +
    1. Create the LLVM source distribution.
    2. +
    3. Create the LLVM GCC source distribtuion.
    4. +
    5. Create a set of LLVM GCC binary distribtuions for each supported + platform. These binary distributions must include compiled versions + of the libraries found in llvm/runtime from the LLVM + source distribution created in Step 1.
    6. +
    +

    +
    + + + + + + + + + + + +
    +

    + Review the documentation and ensure that it is up to date. The Release Notes + must be updated to reflect bug fixes, new known issues, and changes in the + list of supported platforms. The Getting Started Guide should be updated to + reflect the new release version number tag avaiable from CVS and changes in + basic system requirements. +

    +
    + + + +
    +

    + Merge any work done on branches intended for release into mainline. Finish and + commit all new features or bug fixes that are scheduled to go into the release. + Work that is not to be incorporated into the release should not be merged from + branchs or commited from developer's working directories. +

    + +

    + From this point until the release branch is created, developers should + not + commit changes to the llvm and llvm-gcc CVS repositories unless it is a bug + fix for the release. +

    +
    + + + +
    +

    Rebuild the LibDeps.txt target in utils/llvm-config. This + makes sure that the llvm-config utility remains relevant for the + release, reflecting any changes in the library dependencies.

    +
    + + + + +
    +

    + Use the nightly test reports and 'make check' (deja-gnu based tests) to + ensure that recent changes and merged branches have not destabilized LLVM. + Platforms which are used less often should be given special attention as they + are the most likely to break from commits from the previous step. +

    +
    + + + +
    +

    Tag and branch the CVS HEAD using the following procedure:

    +
      +
    1. + Request all developers to refrain from committing. Offenders get commit + rights taken away (temporarily). +
    2. + +
    3. + The Release Manager updates his/her llvm, llvm-test, and llvm-gcc source + trees with the + latest sources from mainline CVS. The Release Manage may want to consider + using a new working directory for this to keep current uncommitted work + separate from release work. +
    4. + +
    5. + The Release Manager tags his/her llvm, llvm-test, and llvm-gcc working + directories with + "ROOT_RELEASE_XX" where XX is the major and minor + release numbers (you can't have . in a cvs tag name). So, for Release 1.2, + XX=12 and for Release 1.10, XX=110. +
    6. + +
    7. + Immediately create cvs branches based on the ROOT_RELEASE_XX tag. The tag + should be "release_XX" (where XX matches that used for the ROOT_RELEASE_XX + tag). This is where the release distribution will be created. +
    8. + +
    9. + Advise developers they can work on CVS HEAD again. +
    10. + +
    11. + The Release Manager and any developers working on the release should switch + to the release branch (as all changes to the release will now be done in + the branch). The easiest way to do this is to grab another working copy + using the following commands: + +

      + cvs -d <CVS Repository> co -r release_XX llvm
      + cvs -d <CVS Repository> co -r release_XX llvm-test
      + cvs -d <CVS Repository> co -r release_XX llvm-gcc
      +

      +
    12. +
    + + + +
    +

    + Build both debug and release (optimized) versions of LLVM on all + platforms. Ensure the build is warning and error free on each platform. +

    + +

    + Build a new version of the LLVM GCC front-end after building the LLVM tools. + Once that is complete, go back to the LLVM source tree and build and install + the llvm/runtime libraries. +

    +
    + + + +
    +

    Run make check and ensure there are no unexpected failures. If + there are, resolve the failures, commit them back into the release branch, + and restart testing by re-building LLVM. +

    + +

    + Ensure that 'make check' passes on all platforms for all targets. If certain + failures cannot be resolved before release time, determine if marking them + XFAIL is appropriate. If not, fix the bug and go back. The test suite must + complete with "0 unexpected failures" for release. +

    +
    + + + +
    +

    Run the llvm-test suite and ensure there are no unacceptable failures. + If there are, resolve the failures and go back to + re-building LLVM. The test suite + should be run in Nightly Test mode. All tests must pass. +

    + + + +
    +

    + Create source distributions for LLVM, LLVM GCC, and the LLVM Test Suite by + exporting the source + from CVS and archiving it. This can be done with the following commands: +

    + +

    + cvs -d <CVS Repository> export -r release_XX llvm
    + cvs -d <CVS Repository> export -r release_XX llvm-test
    + cvs -d <CVS Repository> export -r release_XX llvm-gcc
    + mkdir cfrontend; mv llvm-gcc cfrontend/src
    + tar -cvf - llvm | gzip > llvm-X.X.tar.gz
    + tar -cvf - llvm-test | gzip > llvm-test-X.X.tar.gz
    + tar -cvf - cfrontend/src | gzip > cfrontend-X.X.source.tar.gz
    +

    + + +
    + + + +
    +

    + Creating the LLVM GCC binary distribution requires performing the following + steps for each supported platform: +

    + +
      +
    1. + Build the LLVM GCC front-end. The LLVM GCC front-end must be installed in + a directory named cfrontend/<platform>/llvm-gcc. For + example, the Sparc/Solaris directory is named + cfrontend/sparc/llvm-gcc. +
    2. + +
    3. + Build the libraries in llvm/runtime and install them into the + created LLVM GCC installation directory. +
    4. + +
    5. + For systems with non-distributable header files (e.g. Solaris), manually + remove header files that the GCC build process has "fixed." This process + is admittedly painful, but not as bad as it looks; these header files are + almost always easily identifiable with simple grep expressions and are + installed in only a few directories in the GCC installation directory. +
    6. + +
    7. + Add the copyright files and header file fix script. +
    8. + +
    9. + Archive and compress the installation directory. These can be found in + previous releases of the LLVM-GCC front-end. +
    10. +
    +
    + + + + + + + +
    Overview
    +
    +

    The first thing you need to understand is that there are multiple make + targets to support this feature. Here's an overview, we'll delve into the + details later.

    +
      +
    • distdir - builds the distribution directory from which the + distribution will be packaged
    • +
    • dist - builds each of the distribution tarballs (tar.gz, + tar.bzip2, .zip). These can be built individually as well, with separate + targets.
    • +
    • dist-check - this is identical to dist but includes a + check on the distribution that ensures the tarball can: unpack successfully, + compile correctly, pass 'make check', and pass 'make clean'.
    • +
    • dist-clean- this just does a normal clean but also cleans up the + stuff generated by the other three dist targets (above).
    • +
    +

    Okay, that's the basic functionality. When making a release, we want to + ensure that the tree you build the distribution from passes + dist-check. Beyond fixing the usual bugs, there is generally one + impediment to making the release in this fashion: missing files. The + dist-check process guards against that possibility. It will either + fail and that failure will indicate what's missing, or it will succeed + meaning that it has proved that the tarballs can actually succeed in + building LLVM correctly and that it passes make check.

    + +
    distdir
    +

    This target builds the distribution directory which is the directory from + which the tarballs are generated. The distribution directory has the same + name as the release, e.g. LLVM-1.7). This target goes through the following + process: +

      +
    1. First, if there was an old distribution directory (for the current + release), it is removed in its entirety and you see Removing old + LLVM-1.7
    2. +
    3. Second, it issues a make all ENABLE_OPTIMIZED=3D1 to ensure + that the everything in your tree can be built in release mode. Often times + there are discrepancies in building between debug and release modes so it + enforces release mode first. If that fails, the distdir target + fails too. This is preceded by the message Making 'all' to verify + build.
    4. +
    5. Next, it traverses your source tree and copies it to a new directory + that has the name of the release (LLVM-M.m in our current case). + This is the directory that will get tar'd. It contains all the software + that needs to be in the distribution. During the copying process, it omits + generated files, CVS directories, and any other "cruft" that's in your + build tree. This is done to eliminate the possibility of huge distribution + tarballs that include useless or irrelevant stuff in them. This is the + trickiest part of making the distribution. Done manually you will either + include stuff that shouldn't be in the distribution or exclude stuff that + should. This step is preceded by the message Building Distribution + Directory LLVM-1.7
    6. +
    7. The distribution directory is then traversed and all CVS or + .svn directories are removed. You see: Eliminating CVS/.svn + directories from distribution
    8. +
    9. The recursive dist-hook target is executed. This gives each + directory a chance to modify the distribution in some way (more on this + below).
    10. +
    11. The distribution directory is traversed and the correct file + permissions and modes are set based on the type of file.
    12. +
    +

    To control the process of making the distribution directory correctly, + each Makefile can utilize two features:

    +
      +
    1. EXTRA_DIST - this make variable specifies which files + it should distribute. By default, all source files are automatically + included for distribution as well as certain well known files + (see DistAlways variable in Makefile.rules for details). Each Makefile + specifies, via the EXTRA_DIST variable, which additional files + need to be distributed. Only those files that are needed to build LLVM + should be added to EXTRA_DIST. EXTRA_DIST contains a + list of file or directory names that should be distributed. For example, + the top level Makefile contains + EXTRA_DIST := test llvm.spec include. + This means that in addition to regular things that are distributed at the + top level (CREDITS.txt, LICENSE.txt, etc.) the distribution should + contain the entire test and include directories as well + as the llvm.spec file.
    2. +
    3. dist-hook - this make target can be used to alter the + content of the distribution directory. For example, in the top level + Makefile there is some logic to eliminate files in the include + subtree that are generated by the configure script. These should not be + distributed. Similarly, any dist-hook target found in any + directory can add or remove or modify things just before it gets packaged. + Any transformation is permitted. Generally, not much is needed. +
    +

    You will see various messages if things go wrong:

    +
      +
    1. During the copying process, any files that are missing will be flagged + with: ===== WARNING: Distribution Source 'dir/file' Not Found! + These must be corrected by either adding the file or removing it from + EXTRA_DIST. +
    2. If you build the distribution with VERBOSE=1, then you might + also see: Skipping non-existent 'dir/file' in certain cases where + its okay to skip the file.
    3. +
    4. The target can fail if any of the things it does fail. Error messages + should indicate what went wrong.
    5. +
    + +
    dist
    +

    This target does exactly what distdir target does, but also + includes assembling the tarballs. There are actually four related targets + here:

    +

      +
    • dist-gzip: package the gzipped distribution tar + file. The distribution directory is packaged into a single file ending in + .tar.gz which is gzip compressed.
    • +
    • dist-bzip2: package the bzip2 distribution tar file. + The distribution directory is packaged into a single file ending in + .tar.bzip2 which is bzip2 compressed.
    • +
    • dist-zip: package the zip distribution file. The + distribution directory is packaged into a single file ending in + .zip which is zip compressed.
    • +
    • dist: does all three, dist-gzip, dist-bzip2, + dist-zip
    • +
    + +
    dist-check
    +

    This target checks the distribution. The basic idea is that it unpacks the + distribution tarball and ensures that it can build. It takes the following + actions:

    +
      +
    1. It depends on the dist-gzip target which, if it hasn't already + been built, builds the gzip tar bundle (see dist and distdir above).
    2. +
    3. removes any pre-existing _distcheckdir at the top level.
    4. +
    5. creates a new _distcheckdir directory at the top level.
    6. +
    7. creates a build subdirectory and an install + subdirectory under _distcheckdir.
    8. +
    9. unzips and untars the release tarball into _distcheckdir, + creating LLVM-1.7 directory (from the tarball).
    10. +
    11. in the build subdirectory, it configures with appropriate options to build + from the unpacked source tarball into the build directory with + installation in the install directory.
    12. +
    13. runs make all
    14. +
    15. runs make check
    16. +
    17. runs make install
    18. +
    19. runs make uninstall
    20. +
    21. runs make dist
    22. +
    23. runs make clean
    24. +
    25. runs make dist-clean
    26. +
    +

    If it can pass all that, the distribution will be deemed distribution + worth y and you will see:

    +

    ===== LLVM-1.7.tar.gz Ready For Distribution =====
    +

    This means the tarball should then be tested on other platforms and have the + nightly test run against it. If those all pass, THEN it is ready for + distribution.

    +

    + A note about disk space: using dist-check will easily triple the + amount of disk space your build tree is using. You might want to check + available space before you begin.

    + +
    dist-clean
    +

    dist-clean

    +

    In addition to doing a normal clean, this target will clean up the + files and directories created by the distribution targets. In particular the + distribution directory (LLVM-X.X), check directory + (_distcheckdir), and the various tarballs will be removed. You do + this after the release has shipped and you no longer need this stuff in your + build tree.

    +
    + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Reid Spencer
    + The LLVM Compiler Infrastructure +
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + Index: llvm-www/releases/1.8/docs/HowToSubmitABug.html diff -c /dev/null llvm-www/releases/1.8/docs/HowToSubmitABug.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/HowToSubmitABug.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,359 ---- + + + + How to submit an LLVM bug report + + + + +
    + How to submit an LLVM bug report +
    + + + + + + +
    +
      +
    1. Introduction - Got bugs?
    2. +
    3. Crashing Bugs +
    4. +
    5. Miscompilations
    6. +
    7. Incorrect code generation (JIT and LLC)
    8. +
    +
    +

    Written by Chris Lattner and + Misha Brukman

    +
    +
    + Debugging +
    + + + + + +
    + +

    If you're working with LLVM and run into a bug, we definitely want to know + about it. This document describes what you can do to increase the odds of + getting it fixed quickly.

    + +

    Basically you have to do two things at a minimum. First, decide whether the + bug crashes the compiler (or an LLVM pass), or if the + compiler is miscompiling the program. Based on + what type of bug it is, follow the instructions in the linked section to narrow + down the bug so that the person who fixes it will be able to find the problem + more easily.

    + +

    Once you have a reduced test-case, go to the LLVM Bug Tracking + System, select the category in which the bug falls, and fill out the form + with the necessary details. The bug description should contain the following + information:

    + +
      +
    • All information necessary to reproduce the problem.
    • +
    • The reduced test-case that triggers the bug.
    • +
    • The location where you obtained LLVM (if not from our CVS + repository).
    • +
    + +

    Thanks for helping us make LLVM better!

    + +
    + + + + + +
    + +

    More often than not, bugs in the compiler cause it to crash - often due to an + assertion failure of some sort. If you are running opt or + analyze directly, and something crashes, jump to the section on + bugs in LLVM passes. Otherwise, the most important + piece of the puzzle is to figure out if it is the GCC-based front-end that is + buggy or if it's one of the LLVM tools that has problems.

    + +

    To figure out which program is crashing (the front-end, + gccas, or gccld), run the + llvm-gcc command line as you were when the crash occurred, but + add a -v option to the command line. The compiler will print out a + bunch of stuff, and should end with telling you that one of + cc1/cc1plus, gccas, or + gccld crashed.

    + +
      + +
    • If cc1 or cc1plus crashed, you found a + problem with the front-end. + Jump ahead to the section on front-end bugs.
    • + +
    • If gccas crashed, you found a bug in one + of the passes in gccas.
    • + +
    • If gccld crashed, you found a bug in one + of the passes in gccld.
    • + +
    • Otherwise, something really weird happened. Email the list with what you + have at this point.
    • + +
    + +
    + + + + +
    + +

    If the problem is in the front-end, you should re-run the same + llvm-gcc command that resulted in the crash, but add the + -save-temps option. The compiler will crash again, but it will leave + behind a foo.i file (containing preprocessed C source code) and + possibly foo.s (containing LLVM assembly code), for each + compiled foo.c file. Send us the foo.i file, + along with a brief description of the error it caused. A tool that might help + you reduce a front-end testcase to a more manageable size is + delta. +

    + +
    + + + + +
    + +

    If you find that a bug crashes in the gccas stage of + compilation, compile your test-case to a .s file with the + -save-temps option to llvm-gcc. Then run:

    + +
    +

    gccas -debug-pass=Arguments < /dev/null -o - > /dev/null

    +
    + +

    ... which will print a list of arguments, indicating the list of passes that + gccas runs. Once you have the input file and the list of + passes, go to the section on debugging bugs in LLVM + passes.

    + +
    + + + + +
    + +

    If you find that a bug crashes in the gccld stage of + compilation, gather all of the .o bytecode files and libraries that are + being linked together (the "llvm-gcc -v" output should include + the full list of objects linked). Then run:

    + +
    +

    llvm-as < /dev/null > null.bc
    + gccld -debug-pass=Arguments null.bc
    +

    +
    + +

    ... which will print a list of arguments, indicating the list of passes that + gccld runs. Once you have the input files and the list of + passes, go to the section on debugging bugs in LLVM + passes.

    + +
    + + + + +
    + +

    At this point, you should have some number of LLVM assembly files or bytecode + files and a list of passes which crash when run on the specified input. In + order to reduce the list of passes (which is probably large) and the input to + something tractable, use the bugpoint tool as follows:

    + +
    +

    bugpoint <input files> <list of passes>

    +
    + +

    bugpoint will print a bunch of output as it reduces the + test-case, but it should eventually print something like this:

    + +
    +

    + ...
    + Emitted bytecode to 'bugpoint-reduced-simplified.bc'
    +
    + *** You can reproduce the problem with: opt bugpoint-reduced-simplified.bc -licm
    +

    +
    + +

    Once you complete this, please send the LLVM bytecode file and the command + line to reproduce the problem to the llvmbugs mailing list.

    + +
    + + + + + +
    + +

    A miscompilation occurs when a pass does not correctly transform a program, + thus producing errors that are only noticed during execution. This is different + from producing invalid LLVM code (i.e., code not in SSA form, using values + before defining them, etc.) which the verifier will check for after a pass + finishes its run.

    + +

    If it looks like the LLVM compiler is miscompiling a program, the very first + thing to check is to make sure it is not using undefined behavior. In + particular, check to see if the program valgrinds clean, passes purify, or some + other memory checker tool. Many of the "LLVM bugs" that we have chased down + ended up being bugs in the program being compiled, not LLVM.

    + +

    Once you determine that the program itself is not buggy, you should choose + which code generator you wish to compile the program with (e.g. C backend, the + JIT, or LLC) and optionally a series of LLVM passes to run. For example:

    + +
    +

    + bugpoint -run-cbe [... optzn passes ...] file-to-test.bc --args -- [program arguments]

    +
    + +

    bugpoint will try to narrow down your list of passes to the one pass + that causes an error, and simplify the bytecode file as much as it can to assist + you. It will print a message letting you know how to reproduce the resulting + error.

    + +
    + + + + + +
    + +

    Similarly to debugging incorrect compilation by mis-behaving passes, you can + debug incorrect code generation by either LLC or the JIT, using + bugpoint. The process bugpoint follows in this case is to try + to narrow the code down to a function that is miscompiled by one or the other + method, but since for correctness, the entire program must be run, + bugpoint will compile the code it deems to not be affected with the C + Backend, and then link in the shared object it generates.

    + +

    To debug the JIT:

    + +
    +
    + bugpoint -run-jit -output=[correct output file] [bytecode file]  \
    +          --tool-args -- [arguments to pass to lli]               \
    +          --args -- [program arguments]
    + 
    +
    + +

    Similarly, to debug the LLC, one would run:

    + +
    +
    + bugpoint -run-llc -output=[correct output file] [bytecode file]  \
    +          --tool-args -- [arguments to pass to llc]               \
    +          --args -- [program arguments]
    + 
    +
    + +

    Special note: if you are debugging MultiSource or SPEC tests that + already exist in the llvm/test hierarchy, there is an easier way to + debug the JIT, LLC, and CBE, using the pre-written Makefile targets, which + will pass the program options specified in the Makefiles:

    + +
    +

    + cd llvm/test/../../program
    + make bugpoint-jit +

    +
    + +

    At the end of a successful bugpoint run, you will be presented + with two bytecode files: a safe file which can be compiled with the C + backend and the test file which either LLC or the JIT + mis-codegenerates, and thus causes the error.

    + +

    To reproduce the error that bugpoint found, it is sufficient to do + the following:

    + +
      + +
    1. Regenerate the shared object from the safe bytecode file:

      + +
      +

      + llc -march=c safe.bc -o safe.c
      + gcc -shared safe.c -o safe.so +

      +
    2. + +
    3. If debugging LLC, compile test bytecode native and link with the shared + object:

      + +
      +

      + llc test.bc -o test.s -f
      + gcc test.s safe.so -o test.llc
      + ./test.llc [program options] +

      +
    4. + +
    5. If debugging the JIT, load the shared object and supply the test + bytecode:

      + +
      +

      lli -load=safe.so test.bc [program options]

      +
    6. + +
    + +
    + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + The LLVM Compiler Infrastructure +
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/LangRef.html diff -c /dev/null llvm-www/releases/1.8/docs/LangRef.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/LangRef.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,3846 ---- + + + + LLVM Assembly Language Reference Manual + + + + + + + + +
    LLVM Language Reference Manual
    +
      +
    1. Abstract
    2. +
    3. Introduction
    4. +
    5. Identifiers
    6. +
    7. High Level Structure +
        +
      1. Module Structure
      2. +
      3. Linkage Types
      4. +
      5. Calling Conventions
      6. +
      7. Global Variables
      8. +
      9. Functions
      10. +
      11. Module-Level Inline Assembly
      12. +
      +
    8. +
    9. Type System +
        +
      1. Primitive Types +
          +
        1. Type Classifications
        2. +
        +
      2. +
      3. Derived Types +
          +
        1. Array Type
        2. +
        3. Function Type
        4. +
        5. Pointer Type
        6. +
        7. Structure Type
        8. +
        9. Packed Type
        10. +
        11. Opaque Type
        12. +
        +
      4. +
      +
    10. +
    11. Constants +
        +
      1. Simple Constants +
      2. Aggregate Constants +
      3. Global Variable and Function Addresses +
      4. Undefined Values +
      5. Constant Expressions +
      +
    12. +
    13. Other Values +
        +
      1. Inline Assembler Expressions +
      +
    14. +
    15. Instruction Reference +
        +
      1. Terminator Instructions +
          +
        1. 'ret' Instruction
        2. +
        3. 'br' Instruction
        4. +
        5. 'switch' Instruction
        6. +
        7. 'invoke' Instruction
        8. +
        9. 'unwind' Instruction
        10. +
        11. 'unreachable' Instruction
        12. +
        +
      2. +
      3. Binary Operations +
          +
        1. 'add' Instruction
        2. +
        3. 'sub' Instruction
        4. +
        5. 'mul' Instruction
        6. +
        7. 'div' Instruction
        8. +
        9. 'rem' Instruction
        10. +
        11. 'setcc' Instructions
        12. +
        +
      4. +
      5. Bitwise Binary Operations +
          +
        1. 'and' Instruction
        2. +
        3. 'or' Instruction
        4. +
        5. 'xor' Instruction
        6. +
        7. 'shl' Instruction
        8. +
        9. 'shr' Instruction
        10. +
        +
      6. +
      7. Vector Operations +
          +
        1. 'extractelement' Instruction
        2. +
        3. 'insertelement' Instruction
        4. +
        5. 'shufflevector' Instruction
        6. +
        7. 'vsetint' Instruction
        8. +
        9. 'vsetfp' Instruction
        10. +
        11. 'vselect' Instruction
        12. +
        +
      8. +
      9. Memory Access Operations +
          +
        1. 'malloc' Instruction
        2. +
        3. 'free' Instruction
        4. +
        5. 'alloca' Instruction
        6. +
        7. 'load' Instruction
        8. +
        9. 'store' Instruction
        10. +
        11. 'getelementptr' Instruction
        12. +
        +
      10. +
      11. Other Operations +
          +
        1. 'phi' Instruction
        2. +
        3. 'cast .. to' Instruction
        4. +
        5. 'select' Instruction
        6. +
        7. 'call' Instruction
        8. +
        9. 'va_arg' Instruction
        10. +
        +
      12. +
      +
    16. +
    17. Intrinsic Functions +
        +
      1. Variable Argument Handling Intrinsics +
          +
        1. 'llvm.va_start' Intrinsic
        2. +
        3. 'llvm.va_end' Intrinsic
        4. +
        5. 'llvm.va_copy' Intrinsic
        6. +
        +
      2. +
      3. Accurate Garbage Collection Intrinsics +
          +
        1. 'llvm.gcroot' Intrinsic
        2. +
        3. 'llvm.gcread' Intrinsic
        4. +
        5. 'llvm.gcwrite' Intrinsic
        6. +
        +
      4. +
      5. Code Generator Intrinsics +
          +
        1. 'llvm.returnaddress' Intrinsic
        2. +
        3. 'llvm.frameaddress' Intrinsic
        4. +
        5. 'llvm.stacksave' Intrinsic
        6. +
        7. 'llvm.stackrestore' Intrinsic
        8. +
        9. 'llvm.prefetch' Intrinsic
        10. +
        11. 'llvm.pcmarker' Intrinsic
        12. +
        13. llvm.readcyclecounter' Intrinsic
        14. +
        +
      6. +
      7. Standard C Library Intrinsics +
          +
        1. 'llvm.memcpy.*' Intrinsic
        2. +
        3. 'llvm.memmove.*' Intrinsic
        4. +
        5. 'llvm.memset.*' Intrinsic
        6. +
        7. 'llvm.isunordered.*' Intrinsic
        8. +
        9. 'llvm.sqrt.*' Intrinsic
        10. + +
        +
      8. +
      9. Bit Manipulation Intrinsics +
          +
        1. 'llvm.bswap.*' Intrinsics
        2. +
        3. 'llvm.ctpop.*' Intrinsic
        4. +
        5. 'llvm.ctlz.*' Intrinsic
        6. +
        7. 'llvm.cttz.*' Intrinsic
        8. +
        +
      10. +
      11. Debugger intrinsics
      12. +
      +
    18. +
    + +
    +

    Written by Chris Lattner + and Vikram Adve

    +
    + + + + + +
    +

    This document is a reference manual for the LLVM assembly language. + LLVM is an SSA based representation that provides type safety, + low-level operations, flexibility, and the capability of representing + 'all' high-level languages cleanly. It is the common code + representation used throughout all phases of the LLVM compilation + strategy.

    +
    + + + + + +
    + +

    The LLVM code representation is designed to be used in three + different forms: as an in-memory compiler IR, as an on-disk bytecode + representation (suitable for fast loading by a Just-In-Time compiler), + and as a human readable assembly language representation. This allows + LLVM to provide a powerful intermediate representation for efficient + compiler transformations and analysis, while providing a natural means + to debug and visualize the transformations. The three different forms + of LLVM are all equivalent. This document describes the human readable + representation and notation.

    + +

    The LLVM representation aims to be light-weight and low-level + while being expressive, typed, and extensible at the same time. It + aims to be a "universal IR" of sorts, by being at a low enough level + that high-level ideas may be cleanly mapped to it (similar to how + microprocessors are "universal IR's", allowing many source languages to + be mapped to them). By providing type information, LLVM can be used as + the target of optimizations: for example, through pointer analysis, it + can be proven that a C automatic variable is never accessed outside of + the current function... allowing it to be promoted to a simple SSA + value instead of a memory location.

    + +
    + + + + +
    + +

    It is important to note that this document describes 'well formed' + LLVM assembly language. There is a difference between what the parser + accepts and what is considered 'well formed'. For example, the + following instruction is syntactically okay, but not well formed:

    + +
    +   %x = add int 1, %x
    + 
    + +

    ...because the definition of %x does not dominate all of + its uses. The LLVM infrastructure provides a verification pass that may + be used to verify that an LLVM module is well formed. This pass is + automatically run by the parser after parsing input assembly and by + the optimizer before it outputs bytecode. The violations pointed out + by the verifier pass indicate bugs in transformation passes or input to + the parser.

    + +
    + + + + + +
    + +

    LLVM uses three different forms of identifiers, for different + purposes:

    + +
      +
    1. Named values are represented as a string of characters with a '%' prefix. + For example, %foo, %DivisionByZero, %a.really.long.identifier. The actual + regular expression used is '%[a-zA-Z$._][a-zA-Z$._0-9]*'. + Identifiers which require other characters in their names can be surrounded + with quotes. In this way, anything except a " character can be used + in a name.
    2. + +
    3. Unnamed values are represented as an unsigned numeric value with a '%' + prefix. For example, %12, %2, %44.
    4. + +
    5. Constants, which are described in a section about + constants, below.
    6. +
    + +

    LLVM requires that values start with a '%' sign for two reasons: Compilers + don't need to worry about name clashes with reserved words, and the set of + reserved words may be expanded in the future without penalty. Additionally, + unnamed identifiers allow a compiler to quickly come up with a temporary + variable without having to avoid symbol table conflicts.

    + +

    Reserved words in LLVM are very similar to reserved words in other + languages. There are keywords for different opcodes ('add', 'cast', 'ret', etc...), for primitive type names ('void', 'uint', etc...), + and others. These reserved words cannot conflict with variable names, because + none of them start with a '%' character.

    + +

    Here is an example of LLVM code to multiply the integer variable + '%X' by 8:

    + +

    The easy way:

    + +
    +   %result = mul uint %X, 8
    + 
    + +

    After strength reduction:

    + +
    +   %result = shl uint %X, ubyte 3
    + 
    + +

    And the hard way:

    + +
    +   add uint %X, %X           ; yields {uint}:%0
    +   add uint %0, %0           ; yields {uint}:%1
    +   %result = add uint %1, %1
    + 
    + +

    This last way of multiplying %X by 8 illustrates several + important lexical features of LLVM:

    + +
      + +
    1. Comments are delimited with a ';' and go until the end of + line.
    2. + +
    3. Unnamed temporaries are created when the result of a computation is not + assigned to a named value.
    4. + +
    5. Unnamed temporaries are numbered sequentially
    6. + +
    + +

    ...and it also shows a convention that we follow in this document. When + demonstrating instructions, we will follow an instruction with a comment that + defines the type and name of value produced. Comments are shown in italic + text.

    + +
    + + + + + + + + +
    + +

    LLVM programs are composed of "Module"s, each of which is a + translation unit of the input programs. Each module consists of + functions, global variables, and symbol table entries. Modules may be + combined together with the LLVM linker, which merges function (and + global variable) definitions, resolves forward declarations, and merges + symbol table entries. Here is an example of the "hello world" module:

    + +
    ; Declare the string constant as a global constant...
    + %.LC0 = internal constant [13 x sbyte] c"hello world\0A\00"          ; [13 x sbyte]*
    + 
    + ; External declaration of the puts function
    + declare int %puts(sbyte*)                                            ; int(sbyte*)* 
    + 
    + ; Global variable / Function body section separator
    + implementation
    + 
    + ; Definition of main function
    + int %main() {                                                        ; int()* 
    +         ; Convert [13x sbyte]* to sbyte *...
    +         %cast210 = getelementptr [13 x sbyte]* %.LC0, long 0, long 0 ; sbyte*
    + 
    +         ; Call puts function to write out the string to stdout...
    +         call int %puts(sbyte* %cast210)                              ; int
    +         ret int 0
    }
    + +

    This example is made up of a global variable + named ".LC0", an external declaration of the "puts" + function, and a function definition + for "main".

    + +

    In general, a module is made up of a list of global values, + where both functions and global variables are global values. Global values are + represented by a pointer to a memory location (in this case, a pointer to an + array of char, and a pointer to a function), and have one of the following linkage types.

    + +

    Due to a limitation in the current LLVM assembly parser (it is limited by + one-token lookahead), modules are split into two pieces by the "implementation" + keyword. Global variable prototypes and definitions must occur before the + keyword, and function definitions must occur after it. Function prototypes may + occur either before or after it. In the future, the implementation keyword may + become a noop, if the parser gets smarter.

    + +
    + + + + +
    + +

    + All Global Variables and Functions have one of the following types of linkage: +

    + +
    + +
    internal
    + +
    Global values with internal linkage are only directly accessible by + objects in the current module. In particular, linking code into a module with + an internal global value may cause the internal to be renamed as necessary to + avoid collisions. Because the symbol is internal to the module, all + references can be updated. This corresponds to the notion of the + 'static' keyword in C, or the idea of "anonymous namespaces" in C++. +
    + +
    linkonce:
    + +
    "linkonce" linkage is similar to internal linkage, with + the twist that linking together two modules defining the same + linkonce globals will cause one of the globals to be discarded. This + is typically used to implement inline functions. Unreferenced + linkonce globals are allowed to be discarded. +
    + +
    weak:
    + +
    "weak" linkage is exactly the same as linkonce linkage, + except that unreferenced weak globals may not be discarded. This is + used to implement constructs in C such as "int X;" at global scope. +
    + +
    appending:
    + +
    "appending" linkage may only be applied to global variables of + pointer to array type. When two global variables with appending linkage are + linked together, the two global arrays are appended together. This is the + LLVM, typesafe, equivalent of having the system linker append together + "sections" with identical names when .o files are linked. +
    + +
    externally visible:
    + +
    If none of the above identifiers are used, the global is externally + visible, meaning that it participates in linkage and can be used to resolve + external symbol references. +
    +
    + +

    For example, since the ".LC0" + variable is defined to be internal, if another module defined a ".LC0" + variable and was linked with this one, one of the two would be renamed, + preventing a collision. Since "main" and "puts" are + external (i.e., lacking any linkage declarations), they are accessible + outside of the current module. It is illegal for a function declaration + to have any linkage type other than "externally visible".

    + +
    + + + + +
    + +

    LLVM functions, calls + and invokes can all have an optional calling convention + specified for the call. The calling convention of any pair of dynamic + caller/callee must match, or the behavior of the program is undefined. The + following calling conventions are supported by LLVM, and more may be added in + the future:

    + +
    +
    "ccc" - The C calling convention:
    + +
    This calling convention (the default if no other calling convention is + specified) matches the target C calling conventions. This calling convention + supports varargs function calls and tolerates some mismatch in the declared + prototype and implemented declaration of the function (as does normal C). +
    + +
    "csretcc" - The C struct return calling convention:
    + +
    This calling convention matches the target C calling conventions, except + that functions with this convention are required to take a pointer as their + first argument, and the return type of the function must be void. This is + used for C functions that return aggregates by-value. In this case, the + function has been transformed to take a pointer to the struct as the first + argument to the function. For targets where the ABI specifies specific + behavior for structure-return calls, the calling convention can be used to + distinguish between struct return functions and other functions that take a + pointer to a struct as the first argument. +
    + +
    "fastcc" - The fast calling convention:
    + +
    This calling convention attempts to make calls as fast as possible + (e.g. by passing things in registers). This calling convention allows the + target to use whatever tricks it wants to produce fast code for the target, + without having to conform to an externally specified ABI. Implementations of + this convention should allow arbitrary tail call optimization to be supported. + This calling convention does not support varargs and requires the prototype of + all callees to exactly match the prototype of the function definition. +
    + +
    "coldcc" - The cold calling convention:
    + +
    This calling convention attempts to make code in the caller as efficient + as possible under the assumption that the call is not commonly executed. As + such, these calls often preserve all registers so that the call does not break + any live ranges in the caller side. This calling convention does not support + varargs and requires the prototype of all callees to exactly match the + prototype of the function definition. +
    + +
    "cc <n>" - Numbered convention:
    + +
    Any calling convention may be specified by number, allowing + target-specific calling conventions to be used. Target specific calling + conventions start at 64. +
    +
    + +

    More calling conventions can be added/defined on an as-needed basis, to + support pascal conventions or any other well-known target-independent + convention.

    + +
    + + + + +
    + +

    Global variables define regions of memory allocated at compilation time + instead of run-time. Global variables may optionally be initialized, may have + an explicit section to be placed in, and may + have an optional explicit alignment specified. A + variable may be defined as a global "constant," which indicates that the + contents of the variable will never be modified (enabling better + optimization, allowing the global data to be placed in the read-only section of + an executable, etc). Note that variables that need runtime initialization + cannot be marked "constant" as there is a store to the variable.

    + +

    + LLVM explicitly allows declarations of global variables to be marked + constant, even if the final definition of the global is not. This capability + can be used to enable slightly better optimization of the program, but requires + the language definition to guarantee that optimizations based on the + 'constantness' are valid for the translation units that do not include the + definition. +

    + +

    As SSA values, global variables define pointer values that are in + scope (i.e. they dominate) all basic blocks in the program. Global + variables always define a pointer to their "content" type because they + describe a region of memory, and all memory objects in LLVM are + accessed through pointers.

    + +

    LLVM allows an explicit section to be specified for globals. If the target + supports it, it will emit globals to the section specified.

    + +

    An explicit alignment may be specified for a global. If not present, or if + the alignment is set to zero, the alignment of the global is set by the target + to whatever it feels convenient. If an explicit alignment is specified, the + global is forced to have at least that much alignment. All alignments must be + a power of 2.

    + +
    + + + +
    + Functions +
    + +
    + +

    LLVM function definitions consist of an optional linkage + type, an optional calling convention, a return + type, a function name, a (possibly empty) argument list, an optional section, + an optional alignment, an opening curly brace, + a list of basic blocks, and a closing curly brace. LLVM function declarations + are defined with the "declare" keyword, an optional calling convention, a return type, a function name, + a possibly empty list of arguments, and an optional alignment.

    + +

    A function definition contains a list of basic blocks, forming the CFG for + the function. Each basic block may optionally start with a label (giving the + basic block a symbol table entry), contains a list of instructions, and ends + with a terminator instruction (such as a branch or + function return).

    + +

    The first basic block in a program is special in two ways: it is immediately + executed on entrance to the function, and it is not allowed to have predecessor + basic blocks (i.e. there can not be any branches to the entry block of a + function). Because the block can have no predecessors, it also cannot have any + PHI nodes.

    + +

    LLVM functions are identified by their name and type signature. Hence, two + functions with the same name but different parameter lists or return values are + considered different functions, and LLVM will resolve references to each + appropriately.

    + +

    LLVM allows an explicit section to be specified for functions. If the target + supports it, it will emit functions to the section specified.

    + +

    An explicit alignment may be specified for a function. If not present, or if + the alignment is set to zero, the alignment of the function is set by the target + to whatever it feels convenient. If an explicit alignment is specified, the + function is forced to have at least that much alignment. All alignments must be + a power of 2.

    + +
    + + + + +
    +

    + Modules may contain "module-level inline asm" blocks, which corresponds to the + GCC "file scope inline asm" blocks. These blocks are internally concatenated by + LLVM and treated as a single unit, but may be separated in the .ll file if + desired. The syntax is very simple: +

    + +
    +   module asm "inline asm code goes here"
    +   module asm "more can go here"
    + 
    + +

    The strings can contain any character by escaping non-printable characters. + The escape sequence used is simply "\xx" where "xx" is the two digit hex code + for the number. +

    + +

    + The inline asm code is simply printed to the machine code .s file when + assembly code is generated. +

    +
    + + + + + + +
    + +

    The LLVM type system is one of the most important features of the + intermediate representation. Being typed enables a number of + optimizations to be performed on the IR directly, without having to do + extra analyses on the side before the transformation. A strong type + system makes it easier to read the generated code and enables novel + analyses and transformations that are not feasible to perform on normal + three address code representations.

    + +
    + + + +
    +

    The primitive types are the fundamental building blocks of the LLVM + system. The current set of primitive types is as follows:

    + + + + + + +
    + + + + + + + + + + + +
    TypeDescription
    voidNo value
    ubyteUnsigned 8-bit value
    ushortUnsigned 16-bit value
    uintUnsigned 32-bit value
    ulongUnsigned 64-bit value
    float32-bit floating point value
    labelBranch destination
    +
    + + + + + + + + + + +
    TypeDescription
    boolTrue or False value
    sbyteSigned 8-bit value
    shortSigned 16-bit value
    intSigned 32-bit value
    longSigned 64-bit value
    double64-bit floating point value
    +
    +
    + + + +
    +

    These different primitive types fall into a few useful + classifications:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ClassificationTypes
    signedsbyte, short, int, long, float, double
    unsignedubyte, ushort, uint, ulong
    integerubyte, sbyte, ushort, short, uint, int, ulong, long
    integralbool, ubyte, sbyte, ushort, short, uint, int, ulong, long +
    floating pointfloat, double
    first classbool, ubyte, sbyte, ushort, short, uint, int, ulong, long,
    + float, double, pointer, + packed
    + +

    The first class types are perhaps the + most important. Values of these types are the only ones which can be + produced by instructions, passed as arguments, or used as operands to + instructions. This means that all structures and arrays must be + manipulated either by pointer or by component.

    +
    + + + + +
    + +

    The real power in LLVM comes from the derived types in the system. + This is what allows a programmer to represent arrays, functions, + pointers, and other useful types. Note that these derived types may be + recursive: For example, it is possible to have a two dimensional array.

    + +
    + + + + +
    + +
    Overview:
    + +

    The array type is a very simple derived type that arranges elements + sequentially in memory. The array type requires a size (number of + elements) and an underlying data type.

    + +
    Syntax:
    + +
    +   [<# elements> x <elementtype>]
    + 
    + +

    The number of elements is a constant integer value; elementtype may + be any type with a size.

    + +
    Examples:
    + + + + + +
    + [40 x int ]
    + [41 x int ]
    + [40 x uint]
    +
    + Array of 40 integer values.
    + Array of 41 integer values.
    + Array of 40 unsigned integer values.
    +
    +

    Here are some examples of multidimensional arrays:

    + + + + + +
    + [3 x [4 x int]]
    + [12 x [10 x float]]
    + [2 x [3 x [4 x uint]]]
    +
    + 3x4 array of integer values.
    + 12x10 array of single precision floating point values.
    + 2x3x4 array of unsigned integer values.
    +
    + +

    Note that 'variable sized arrays' can be implemented in LLVM with a zero + length array. Normally, accesses past the end of an array are undefined in + LLVM (e.g. it is illegal to access the 5th element of a 3 element array). + As a special case, however, zero length arrays are recognized to be variable + length. This allows implementation of 'pascal style arrays' with the LLVM + type "{ int, [0 x float]}", for example.

    + +
    + + + +
    +
    Overview:
    +

    The function type can be thought of as a function signature. It + consists of a return type and a list of formal parameter types. + Function types are usually used to build virtual function tables + (which are structures of pointers to functions), for indirect function + calls, and when defining a function.

    +

    + The return type of a function type cannot be an aggregate type. +

    +
    Syntax:
    +
      <returntype> (<parameter list>)
    +

    ...where '<parameter list>' is a comma-separated list of type + specifiers. Optionally, the parameter list may include a type ..., + which indicates that the function takes a variable number of arguments. + Variable argument functions can access their arguments with the variable argument handling intrinsic functions.

    +
    Examples:
    + + + + + +
    + int (int)
    + float (int, int *) *
    + int (sbyte *, ...)
    +
    + function taking an int, returning an int
    + Pointer to a function that takes an + int and a pointer to int, + returning float.
    + A vararg function that takes at least one pointer + to sbyte (signed char in C), which returns an integer. This is + the signature for printf in LLVM.
    +
    + +
    + + +
    +
    Overview:
    +

    The structure type is used to represent a collection of data members + together in memory. The packing of the field types is defined to match + the ABI of the underlying processor. The elements of a structure may + be any type that has a size.

    +

    Structures are accessed using 'load + and 'store' by getting a pointer to a + field with the 'getelementptr' + instruction.

    +
    Syntax:
    +
      { <type list> }
    +
    Examples:
    + + + + + +
    + { int, int, int }
    + { float, int (int) * }
    +
    + a triple of three int values
    + A pair, where the first element is a float and the second element + is a pointer to a function + that takes an int, returning an int.
    +
    +
    + + + +
    +
    Overview:
    +

    As in many languages, the pointer type represents a pointer or + reference to another object, which must live in memory.

    +
    Syntax:
    +
      <type> *
    +
    Examples:
    + + + + + +
    + [4x int]*
    + int (int *) *
    +
    + A pointer to array of + four int values
    + A pointer to a function that takes an int*, returning an + int.
    +
    +
    + + + +
    + +
    Overview:
    + +

    A packed type is a simple derived type that represents a vector + of elements. Packed types are used when multiple primitive data + are operated in parallel using a single instruction (SIMD). + A packed type requires a size (number of + elements) and an underlying primitive data type. Vectors must have a power + of two length (1, 2, 4, 8, 16 ...). Packed types are + considered first class.

    + +
    Syntax:
    + +
    +   < <# elements> x <elementtype> >
    + 
    + +

    The number of elements is a constant integer value; elementtype may + be any integral or floating point type.

    + +
    Examples:
    + + + + + + +
    + <4 x int>
    + <8 x float>
    + <2 x uint>
    +
    + Packed vector of 4 integer values.
    + Packed vector of 8 floating-point values.
    + Packed vector of 2 unsigned integer values.
    +
    +
    + + + +
    + +
    Overview:
    + +

    Opaque types are used to represent unknown types in the system. This + corresponds (for example) to the C notion of a foward declared structure type. + In LLVM, opaque types can eventually be resolved to any type (not just a + structure type).

    + +
    Syntax:
    + +
    +   opaque
    + 
    + +
    Examples:
    + + + + + + +
    + opaque + + An opaque type.
    +
    +
    + + + + + + +
    + +

    LLVM has several different basic types of constants. This section describes + them all and their syntax.

    + +
    + + + + +
    + +
    +
    Boolean constants
    + +
    The two strings 'true' and 'false' are both valid + constants of the bool type. +
    + +
    Integer constants
    + +
    Standard integers (such as '4') are constants of the integer type. Negative numbers may be used with signed + integer types. +
    + +
    Floating point constants
    + +
    Floating point constants use standard decimal notation (e.g. 123.421), + exponential notation (e.g. 1.23421e+2), or a more precise hexadecimal + notation (see below). Floating point constants must have a floating point type.
    + +
    Null pointer constants
    + +
    The identifier 'null' is recognized as a null pointer constant + and must be of pointer type.
    + +
    + +

    The one non-intuitive notation for constants is the optional hexadecimal form + of floating point constants. For example, the form 'double + 0x432ff973cafa8000' is equivalent to (but harder to read than) 'double + 4.5e+15'. The only time hexadecimal floating point constants are required + (and the only time that they are generated by the disassembler) is when a + floating point constant must be emitted but it cannot be represented as a + decimal floating point number. For example, NaN's, infinities, and other + special values are represented in their IEEE hexadecimal format so that + assembly and disassembly do not cause any bits to change in the constants.

    + +
    + + + + +
    +

    Aggregate constants arise from aggregation of simple constants + and smaller aggregate constants.

    + +
    +
    Structure constants
    + +
    Structure constants are represented with notation similar to structure + type definitions (a comma separated list of elements, surrounded by braces + ({})). For example: "{ int 4, float 17.0, int* %G }", + where "%G" is declared as "%G = external global int". Structure constants + must have structure type, and the number and + types of elements must match those specified by the type. +
    + +
    Array constants
    + +
    Array constants are represented with notation similar to array type + definitions (a comma separated list of elements, surrounded by square brackets + ([])). For example: "[ int 42, int 11, int 74 ]". Array + constants must have array type, and the number and + types of elements must match those specified by the type. +
    + +
    Packed constants
    + +
    Packed constants are represented with notation similar to packed type + definitions (a comma separated list of elements, surrounded by + less-than/greater-than's (<>)). For example: "< int 42, + int 11, int 74, int 100 >". Packed constants must have packed type, and the number and types of elements must + match those specified by the type. +
    + +
    Zero initialization
    + +
    The string 'zeroinitializer' can be used to zero initialize a + value to zero of any type, including scalar and aggregate types. + This is often used to avoid having to print large zero initializers (e.g. for + large arrays) and is always exactly equivalent to using explicit zero + initializers. +
    +
    + +
    + + + + +
    + +

    The addresses of global variables and functions are always implicitly valid (link-time) + constants. These constants are explicitly referenced when the identifier for the global is used and always have pointer type. For example, the following is a legal LLVM + file:

    + +
    +   %X = global int 17
    +   %Y = global int 42
    +   %Z = global [2 x int*] [ int* %X, int* %Y ]
    + 
    + +
    + + + +
    +

    The string 'undef' is recognized as a type-less constant that has + no specific value. Undefined values may be of any type and be used anywhere + a constant is permitted.

    + +

    Undefined values indicate to the compiler that the program is well defined + no matter what value is used, giving the compiler more freedom to optimize. +

    +
    + + + + +
    + +

    Constant expressions are used to allow expressions involving other constants + to be used as constants. Constant expressions may be of any first class type and may involve any LLVM operation + that does not have side effects (e.g. load and call are not supported). The + following is the syntax for constant expressions:

    + +
    +
    cast ( CST to TYPE )
    + +
    Cast a constant to another type.
    + +
    getelementptr ( CSTPTR, IDX0, IDX1, ... )
    + +
    Perform the getelementptr operation on + constants. As with the getelementptr + instruction, the index list may have zero or more indexes, which are required + to make sense for the type of "CSTPTR".
    + +
    select ( COND, VAL1, VAL2 )
    + +
    Perform the select operation on + constants. + +
    extractelement ( VAL, IDX )
    + +
    Perform the extractelement + operation on constants. + +
    insertelement ( VAL, ELT, IDX )
    + +
    Perform the insertelement + operation on constants. + + +
    shufflevector ( VEC1, VEC2, IDXMASK )
    + +
    Perform the shufflevector + operation on constants. + +
    OPCODE ( LHS, RHS )
    + +
    Perform the specified operation of the LHS and RHS constants. OPCODE may + be any of the binary or bitwise + binary operations. The constraints on operands are the same as those for + the corresponding instruction (e.g. no bitwise operations on floating point + values are allowed).
    +
    +
    + + + + + + + + +
    + +

    + LLVM supports inline assembler expressions (as opposed to + Module-Level Inline Assembly) through the use of a special value. This + value represents the inline assembler as a string (containing the instructions + to emit), a list of operand constraints (stored as a string), and a flag that + indicates whether or not the inline asm expression has side effects. An example + inline assembler expression is: +

    + +
    +   int(int) asm "bswap $0", "=r,r"
    + 
    + +

    + Inline assembler expressions may only be used as the callee operand of + a call instruction. Thus, typically we have: +

    + +
    +   %X = call int asm "bswap $0", "=r,r"(int %Y)
    + 
    + +

    + Inline asms with side effects not visible in the constraint list must be marked + as having side effects. This is done through the use of the + 'sideeffect' keyword, like so: +

    + +
    +   call void asm sideeffect "eieio", ""()
    + 
    + +

    TODO: The format of the asm and constraints string still need to be + documented here. Constraints on what can be done (e.g. duplication, moving, etc + need to be documented). +

    + +
    + + + + + +
    + +

    The LLVM instruction set consists of several different + classifications of instructions: terminator + instructions, binary instructions, + bitwise binary instructions, memory instructions, and other + instructions.

    + +
    + + + + +
    + +

    As mentioned previously, every + basic block in a program ends with a "Terminator" instruction, which + indicates which block should be executed after the current block is + finished. These terminator instructions typically yield a 'void' + value: they produce control flow, not values (the one exception being + the 'invoke' instruction).

    +

    There are six different terminator instructions: the 'ret' instruction, the 'br' + instruction, the 'switch' instruction, + the 'invoke' instruction, the 'unwind' instruction, and the 'unreachable' instruction.

    + +
    + + + +
    +
    Syntax:
    +
      ret <type> <value>       ; Return a value from a non-void function
    +   ret void                 ; Return from void function
    + 
    +
    Overview:
    +

    The 'ret' instruction is used to return control flow (and a + value) from a function back to the caller.

    +

    There are two forms of the 'ret' instruction: one that + returns a value and then causes control flow, and one that just causes + control flow to occur.

    +
    Arguments:
    +

    The 'ret' instruction may return any 'first class' type. Notice that a function is + not well formed if there exists a 'ret' + instruction inside of the function that returns a value that does not + match the return type of the function.

    +
    Semantics:
    +

    When the 'ret' instruction is executed, control flow + returns back to the calling function's context. If the caller is a "call" instruction, execution continues at + the instruction after the call. If the caller was an "invoke" instruction, execution continues + at the beginning of the "normal" destination block. If the instruction + returns a value, that value shall set the call or invoke instruction's + return value.

    +
    Example:
    +
      ret int 5                       ; Return an integer value of 5
    +   ret void                        ; Return from a void function
    + 
    +
    + + +
    +
    Syntax:
    +
      br bool <cond>, label <iftrue>, label <iffalse>
    br label <dest> ; Unconditional branch +
    +
    Overview:
    +

    The 'br' instruction is used to cause control flow to + transfer to a different basic block in the current function. There are + two forms of this instruction, corresponding to a conditional branch + and an unconditional branch.

    +
    Arguments:
    +

    The conditional branch form of the 'br' instruction takes a + single 'bool' value and two 'label' values. The + unconditional form of the 'br' instruction takes a single 'label' + value as a target.

    +
    Semantics:
    +

    Upon execution of a conditional 'br' instruction, the 'bool' + argument is evaluated. If the value is true, control flows + to the 'iftrue' label argument. If "cond" is false, + control flows to the 'iffalse' label argument.

    +
    Example:
    +
    Test:
    %cond = seteq int %a, %b
    br bool %cond, label %IfEqual, label %IfUnequal
    IfEqual:
    ret int 1
    IfUnequal:
    ret int 0
    +
    + + + +
    +
    Syntax:
    + +
    +   switch <intty> <value>, label <defaultdest> [ <intty> <val>, label <dest> ... ]
    + 
    + +
    Overview:
    + +

    The 'switch' instruction is used to transfer control flow to one of + several different places. It is a generalization of the 'br' + instruction, allowing a branch to occur to one of many possible + destinations.

    + + +
    Arguments:
    + +

    The 'switch' instruction uses three parameters: an integer + comparison value 'value', a default 'label' destination, and + an array of pairs of comparison value constants and 'label's. The + table is not allowed to contain duplicate constant entries.

    + +
    Semantics:
    + +

    The switch instruction specifies a table of values and + destinations. When the 'switch' instruction is executed, this + table is searched for the given value. If the value is found, control flow is + transfered to the corresponding destination; otherwise, control flow is + transfered to the default destination.

    + +
    Implementation:
    + +

    Depending on properties of the target machine and the particular + switch instruction, this instruction may be code generated in different + ways. For example, it could be generated as a series of chained conditional + branches or with a lookup table.

    + +
    Example:
    + +
    +  ; Emulate a conditional br instruction
    +  %Val = cast bool %value to int
    +  switch int %Val, label %truedest [int 0, label %falsedest ]
    + 
    +  ; Emulate an unconditional br instruction
    +  switch uint 0, label %dest [ ]
    + 
    +  ; Implement a jump table:
    +  switch uint %val, label %otherwise [ uint 0, label %onzero 
    +                                       uint 1, label %onone 
    +                                       uint 2, label %ontwo ]
    + 
    +
    + + + + +
    + +
    Syntax:
    + +
    +   <result> = invoke [cconv] <ptr to function ty> %<function ptr val>(<function args>) 
    +                 to label <normal label> unwind label <exception label>
    + 
    + +
    Overview:
    + +

    The 'invoke' instruction causes control to transfer to a specified + function, with the possibility of control flow transfer to either the + 'normal' label or the + 'exception' label. If the callee function returns with the + "ret" instruction, control flow will return to the + "normal" label. If the callee (or any indirect callees) returns with the "unwind" instruction, control is interrupted and + continued at the dynamically nearest "exception" label.

    + +
    Arguments:
    + +

    This instruction requires several arguments:

    + +
      +
    1. + The optional "cconv" marker indicates which calling + convention the call should use. If none is specified, the call defaults + to using C calling conventions. +
    2. +
    3. 'ptr to function ty': shall be the signature of the pointer to + function value being invoked. In most cases, this is a direct function + invocation, but indirect invokes are just as possible, branching off + an arbitrary pointer to function value. +
    4. + +
    5. 'function ptr val': An LLVM value containing a pointer to a + function to be invoked.
    6. + +
    7. 'function args': argument list whose types match the function + signature argument types. If the function signature indicates the function + accepts a variable number of arguments, the extra arguments can be + specified.
    8. + +
    9. 'normal label': the label reached when the called function + executes a 'ret' instruction.
    10. + +
    11. 'exception label': the label reached when a callee returns with + the unwind instruction.
    12. + +
    + +
    Semantics:
    + +

    This instruction is designed to operate as a standard 'call' instruction in most regards. The primary + difference is that it establishes an association with a label, which is used by + the runtime library to unwind the stack.

    + +

    This instruction is used in languages with destructors to ensure that proper + cleanup is performed in the case of either a longjmp or a thrown + exception. Additionally, this is important for implementation of + 'catch' clauses in high-level languages that support them.

    + +
    Example:
    +
    +   %retval = invoke int %Test(int 15)             to label %Continue
    +               unwind label %TestCleanup     ; {int}:retval set
    +   %retval = invoke coldcc int %Test(int 15)             to label %Continue
    +               unwind label %TestCleanup     ; {int}:retval set
    + 
    +
    + + + + + + +
    + +
    Syntax:
    +
    +   unwind
    + 
    + +
    Overview:
    + +

    The 'unwind' instruction unwinds the stack, continuing control flow + at the first callee in the dynamic call stack which used an invoke instruction to perform the call. This is + primarily used to implement exception handling.

    + +
    Semantics:
    + +

    The 'unwind' intrinsic causes execution of the current function to + immediately halt. The dynamic call stack is then searched for the first invoke instruction on the call stack. Once found, + execution continues at the "exceptional" destination block specified by the + invoke instruction. If there is no invoke instruction in the + dynamic call chain, undefined behavior results.

    +
    + + + + + +
    + +
    Syntax:
    +
    +   unreachable
    + 
    + +
    Overview:
    + +

    The 'unreachable' instruction has no defined semantics. This + instruction is used to inform the optimizer that a particular portion of the + code is not reachable. This can be used to indicate that the code after a + no-return function cannot be reached, and other facts.

    + +
    Semantics:
    + +

    The 'unreachable' instruction has no defined semantics.

    +
    + + + + + +
    +

    Binary operators are used to do most of the computation in a + program. They require two operands, execute an operation on them, and + produce a single value. The operands might represent + multiple data, as is the case with the packed data type. + The result value of a binary operator is not + necessarily the same type as its operands.

    +

    There are several different binary operators:

    +
    + + +
    +
    Syntax:
    +
      <result> = add <ty> <var1>, <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'add' instruction returns the sum of its two operands.

    +
    Arguments:
    +

    The two arguments to the 'add' instruction must be either integer or floating point values. + This instruction can also take packed versions of the values. + Both arguments must have identical types.

    +
    Semantics:
    +

    The value produced is the integer or floating point sum of the two + operands.

    +
    Example:
    +
      <result> = add int 4, %var          ; yields {int}:result = 4 + %var
    + 
    +
    + + +
    +
    Syntax:
    +
      <result> = sub <ty> <var1>, <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'sub' instruction returns the difference of its two + operands.

    +

    Note that the 'sub' instruction is used to represent the 'neg' + instruction present in most other intermediate representations.

    +
    Arguments:
    +

    The two arguments to the 'sub' instruction must be either integer or floating point + values. + This instruction can also take packed versions of the values. + Both arguments must have identical types.

    +
    Semantics:
    +

    The value produced is the integer or floating point difference of + the two operands.

    +
    Example:
    +
      <result> = sub int 4, %var          ; yields {int}:result = 4 - %var
    +   <result> = sub int 0, %val          ; yields {int}:result = -%var
    + 
    +
    + + +
    +
    Syntax:
    +
      <result> = mul <ty> <var1>, <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'mul' instruction returns the product of its two + operands.

    +
    Arguments:
    +

    The two arguments to the 'mul' instruction must be either integer or floating point + values. + This instruction can also take packed versions of the values. + Both arguments must have identical types.

    +
    Semantics:
    +

    The value produced is the integer or floating point product of the + two operands.

    +

    There is no signed vs unsigned multiplication. The appropriate + action is taken based on the type of the operand.

    +
    Example:
    +
      <result> = mul int 4, %var          ; yields {int}:result = 4 * %var
    + 
    +
    + + +
    +
    Syntax:
    +
      <result> = div <ty> <var1>, <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'div' instruction returns the quotient of its two + operands.

    +
    Arguments:
    +

    The two arguments to the 'div' instruction must be either integer or floating point + values. + This instruction can also take packed versions of the values. + Both arguments must have identical types.

    +
    Semantics:
    +

    The value produced is the integer or floating point quotient of the + two operands.

    +
    Example:
    +
      <result> = div int 4, %var          ; yields {int}:result = 4 / %var
    + 
    +
    + + +
    +
    Syntax:
    +
      <result> = rem <ty> <var1>, <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'rem' instruction returns the remainder from the + division of its two operands.

    +
    Arguments:
    +

    The two arguments to the 'rem' instruction must be either integer or floating point + values. + This instruction can also take packed versions of the values. + Both arguments must have identical types.

    +
    Semantics:
    +

    This returns the remainder of a division (where the result + has the same sign as the divisor), not the modulus (where the + result has the same sign as the dividend) of a value. For more + information about the difference, see The + Math Forum.

    +
    Example:
    +
      <result> = rem int 4, %var          ; yields {int}:result = 4 % %var
    + 
    + +
    + + +
    +
    Syntax:
    +
      <result> = seteq <ty> <var1>, <var2>   ; yields {bool}:result
    +   <result> = setne <ty> <var1>, <var2>   ; yields {bool}:result
    +   <result> = setlt <ty> <var1>, <var2>   ; yields {bool}:result
    +   <result> = setgt <ty> <var1>, <var2>   ; yields {bool}:result
    +   <result> = setle <ty> <var1>, <var2>   ; yields {bool}:result
    +   <result> = setge <ty> <var1>, <var2>   ; yields {bool}:result
    + 
    +
    Overview:
    +

    The 'setcc' family of instructions returns a boolean + value based on a comparison of their two operands.

    +
    Arguments:
    +

    The two arguments to the 'setcc' instructions must + be of first class type (it is not possible + to compare 'label's, 'array's, 'structure' + or 'void' values, etc...). Both arguments must have identical + types.

    +
    Semantics:
    +

    The 'seteq' instruction yields a true 'bool' + value if both operands are equal.
    + The 'setne' instruction yields a true 'bool' + value if both operands are unequal.
    + The 'setlt' instruction yields a true 'bool' + value if the first operand is less than the second operand.
    + The 'setgt' instruction yields a true 'bool' + value if the first operand is greater than the second operand.
    + The 'setle' instruction yields a true 'bool' + value if the first operand is less than or equal to the second operand.
    + The 'setge' instruction yields a true 'bool' + value if the first operand is greater than or equal to the second + operand.

    +
    Example:
    +
      <result> = seteq int   4, 5        ; yields {bool}:result = false
    +   <result> = setne float 4, 5        ; yields {bool}:result = true
    +   <result> = setlt uint  4, 5        ; yields {bool}:result = true
    +   <result> = setgt sbyte 4, 5        ; yields {bool}:result = false
    +   <result> = setle sbyte 4, 5        ; yields {bool}:result = true
    +   <result> = setge sbyte 4, 5        ; yields {bool}:result = false
    + 
    +
    + + + +
    +

    Bitwise binary operators are used to do various forms of + bit-twiddling in a program. They are generally very efficient + instructions and can commonly be strength reduced from other + instructions. They require two operands, execute an operation on them, + and produce a single value. The resulting value of the bitwise binary + operators is always the same type as its first operand.

    +
    + + +
    +
    Syntax:
    +
      <result> = and <ty> <var1>, <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'and' instruction returns the bitwise logical and of + its two operands.

    +
    Arguments:
    +

    The two arguments to the 'and' instruction must be integral values. Both arguments must have + identical types.

    +
    Semantics:
    +

    The truth table used for the 'and' instruction is:

    +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    In0In1Out
    000
    010
    100
    111
    +
    +
    Example:
    +
      <result> = and int 4, %var         ; yields {int}:result = 4 & %var
    +   <result> = and int 15, 40          ; yields {int}:result = 8
    +   <result> = and int 4, 8            ; yields {int}:result = 0
    + 
    +
    + + +
    +
    Syntax:
    +
      <result> = or <ty> <var1>, <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'or' instruction returns the bitwise logical inclusive + or of its two operands.

    +
    Arguments:
    +

    The two arguments to the 'or' instruction must be integral values. Both arguments must have + identical types.

    +
    Semantics:
    +

    The truth table used for the 'or' instruction is:

    +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    In0In1Out
    000
    011
    101
    111
    +
    +
    Example:
    +
      <result> = or int 4, %var         ; yields {int}:result = 4 | %var
    +   <result> = or int 15, 40          ; yields {int}:result = 47
    +   <result> = or int 4, 8            ; yields {int}:result = 12
    + 
    +
    + + +
    +
    Syntax:
    +
      <result> = xor <ty> <var1>, <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'xor' instruction returns the bitwise logical exclusive + or of its two operands. The xor is used to implement the + "one's complement" operation, which is the "~" operator in C.

    +
    Arguments:
    +

    The two arguments to the 'xor' instruction must be integral values. Both arguments must have + identical types.

    +
    Semantics:
    +

    The truth table used for the 'xor' instruction is:

    +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    In0In1Out
    000
    011
    101
    110
    +
    +

    +
    Example:
    +
      <result> = xor int 4, %var         ; yields {int}:result = 4 ^ %var
    +   <result> = xor int 15, 40          ; yields {int}:result = 39
    +   <result> = xor int 4, 8            ; yields {int}:result = 12
    +   <result> = xor int %V, -1          ; yields {int}:result = ~%V
    + 
    +
    + + +
    +
    Syntax:
    +
      <result> = shl <ty> <var1>, ubyte <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'shl' instruction returns the first operand shifted to + the left a specified number of bits.

    +
    Arguments:
    +

    The first argument to the 'shl' instruction must be an integer type. The second argument must be an 'ubyte' + type.

    +
    Semantics:
    +

    The value produced is var1 * 2var2.

    +
    Example:
    +
      <result> = shl int 4, ubyte %var   ; yields {int}:result = 4 << %var
    +   <result> = shl int 4, ubyte 2      ; yields {int}:result = 16
    +   <result> = shl int 1, ubyte 10     ; yields {int}:result = 1024
    + 
    +
    + + +
    +
    Syntax:
    +
      <result> = shr <ty> <var1>, ubyte <var2>   ; yields {ty}:result
    + 
    +
    Overview:
    +

    The 'shr' instruction returns the first operand shifted to + the right a specified number of bits.

    +
    Arguments:
    +

    The first argument to the 'shr' instruction must be an integer type. The second argument must be an 'ubyte' + type.

    +
    Semantics:
    +

    If the first argument is a signed type, the + most significant bit is duplicated in the newly free'd bit positions. + If the first argument is unsigned, zero bits shall fill the empty + positions.

    +
    Example:
    +
      <result> = shr int 4, ubyte %var   ; yields {int}:result = 4 >> %var
    +   <result> = shr uint 4, ubyte 1     ; yields {uint}:result = 2
    +   <result> = shr int 4, ubyte 2      ; yields {int}:result = 1
    +   <result> = shr sbyte 4, ubyte 3    ; yields {sbyte}:result = 0
    +   <result> = shr sbyte -2, ubyte 1   ; yields {sbyte}:result = -1
    + 
    +
    + + + + +
    + +

    LLVM supports several instructions to represent vector operations in a + target-independent manner. This instructions cover the element-access and + vector-specific operations needed to process vectors effectively. While LLVM + does directly support these vector operations, many sophisticated algorithms + will want to use target-specific intrinsics to take full advantage of a specific + target.

    + +
    + + + + +
    + +
    Syntax:
    + +
    +   <result> = extractelement <n x <ty>> <val>, uint <idx>    ; yields <ty>
    + 
    + +
    Overview:
    + +

    + The 'extractelement' instruction extracts a single scalar + element from a packed vector at a specified index. +

    + + +
    Arguments:
    + +

    + The first operand of an 'extractelement' instruction is a + value of packed type. The second operand is + an index indicating the position from which to extract the element. + The index may be a variable.

    + +
    Semantics:
    + +

    + The result is a scalar of the same type as the element type of + val. Its value is the value at position idx of + val. If idx exceeds the length of val, the + results are undefined. +

    + +
    Example:
    + +
    +   %result = extractelement <4 x int> %vec, uint 0    ; yields int
    + 
    +
    + + + + + +
    + +
    Syntax:
    + +
    +   <result> = insertelement <n x <ty>> <val>, <ty> <elt>, uint <idx>    ; yields <n x <ty>>
    + 
    + +
    Overview:
    + +

    + The 'insertelement' instruction inserts a scalar + element into a packed vector at a specified index. +

    + + +
    Arguments:
    + +

    + The first operand of an 'insertelement' instruction is a + value of packed type. The second operand is a + scalar value whose type must equal the element type of the first + operand. The third operand is an index indicating the position at + which to insert the value. The index may be a variable.

    + +
    Semantics:
    + +

    + The result is a packed vector of the same type as val. Its + element values are those of val except at position + idx, where it gets the value elt. If idx + exceeds the length of val, the results are undefined. +

    + +
    Example:
    + +
    +   %result = insertelement <4 x int> %vec, int 1, uint 0    ; yields <4 x int>
    + 
    +
    + + + + +
    + +
    Syntax:
    + +
    +   <result> = shufflevector <n x <ty>> <v1>, <n x <ty>> <v2>, <n x uint> <mask>    ; yields <n x <ty>>
    + 
    + +
    Overview:
    + +

    + The 'shufflevector' instruction constructs a permutation of elements + from two input vectors, returning a vector of the same type. +

    + +
    Arguments:
    + +

    + The first two operands of a 'shufflevector' instruction are vectors + with types that match each other and types that match the result of the + instruction. The third argument is a shuffle mask, which has the same number + of elements as the other vector type, but whose element type is always 'uint'. +

    + +

    + The shuffle mask operand is required to be a constant vector with either + constant integer or undef values. +

    + +
    Semantics:
    + +

    + The elements of the two input vectors are numbered from left to right across + both of the vectors. The shuffle mask operand specifies, for each element of + the result vector, which element of the two input registers the result element + gets. The element selector may be undef (meaning "don't care") and the second + operand may be undef if performing a shuffle from only one vector. +

    + +
    Example:
    + +
    +   %result = shufflevector <4 x int> %v1, <4 x int> %v2, 
    +                           <4 x uint> <uint 0, uint 4, uint 1, uint 5>    ; yields <4 x int>
    +   %result = shufflevector <4 x int> %v1, <4 x int> undef, 
    +                           <4 x uint> <uint 0, uint 1, uint 2, uint 3>  ; yields <4 x int> - Identity shuffle.
    + 
    +
    + + + + +
    +
    Syntax:
    +
    <result> = vsetint <op>, <n x <ty>> <var1>, <var2>   ; yields <n x bool>
    + 
    + +
    Overview:
    + +

    The 'vsetint' instruction takes two integer vectors and + returns a vector of boolean values representing, at each position, the + result of the comparison between the values at that position in the + two operands.

    + +
    Arguments:
    + +

    The arguments to a 'vsetint' instruction are a comparison + operation and two value arguments. The value arguments must be of integral packed type, + and they must have identical types. The operation argument must be + one of eq, ne, slt, sgt, + sle, sge, ult, ugt, ule, + uge, true, and false. The result is a + packed bool value with the same length as each operand.

    + +
    Semantics:
    + +

    The following table shows the semantics of 'vsetint'. For + each position of the result, the comparison is done on the + corresponding positions of the two value arguments. Note that the + signedness of the comparison depends on the comparison opcode and + not on the signedness of the value operands. E.g., vsetint + slt <4 x unsigned> %x, %y does an elementwise signed + comparison of %x and %y.

    + + + + + + + + + + + + + + + + + +
    OperationResult is true iffComparison is
    eqvar1 == var2--
    nevar1 != var2--
    sltvar1 < var2signed
    sgtvar1 > var2signed
    slevar1 <= var2signed
    sgevar1 >= var2signed
    ultvar1 < var2unsigned
    ugtvar1 > var2unsigned
    ulevar1 <= var2unsigned
    ugevar1 >= var2unsigned
    truealways--
    falsenever--
    + +
    Example:
    +
      <result> = vsetint eq <2 x int> <int 0, int 1>, <int 1, int 0>      ; yields {<2 x bool>}:result = false, false
    +   <result> = vsetint ne <2 x int> <int 0, int 1>, <int 1, int 0>      ; yields {<2 x bool>}:result = true, true
    +   <result> = vsetint slt <2 x int> <int 0, int 1>, <int 1, int 0>      ; yields {<2 x bool>}:result = true, false
    +   <result> = vsetint sgt <2 x int> <int 0, int 1>, <int 1, int 0>      ; yields {<2 x bool>}:result = false, true
    +   <result> = vsetint sle <2 x int> <int 0, int 1>, <int 1, int 0>      ; yields {<2 x bool>}:result = true, false
    +   <result> = vsetint sge <2 x int> <int 0, int 1>, <int 1, int 0>      ; yields {<2 x bool>}:result = false, true
    + 
    +
    + + + +
    +
    Syntax:
    +
    <result> = vsetfp <op>, <n x <ty>> <var1>, <var2>   ; yields <n x bool>
    + 
    + +
    Overview:
    + +

    The 'vsetfp' instruction takes two floating point vector + arguments and returns a vector of boolean values representing, at each + position, the result of the comparison between the values at that + position in the two operands.

    + +
    Arguments:
    + +

    The arguments to a 'vsetfp' instruction are a comparison + operation and two value arguments. The value arguments must be of floating point packed + type, and they must have identical types. The operation argument must + be one of eq, ne, lt, gt, + le, ge, oeq, one, olt, + ogt, ole, oge, ueq, une, + ult, ugt, ule, uge, o, + u, true, and false. The result is a packed + bool value with the same length as each operand.

    + +
    Semantics:
    + +

    The following table shows the semantics of 'vsetfp' for + floating point types. If either operand is a floating point Not a + Number (NaN) value, the operation is unordered, and the value in the + first column below is produced at that position. Otherwise, the + operation is ordered, and the value in the second column is + produced.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    OperationIf unorderedOtherwise true iff
    equndefinedvar1 == var2
    neundefinedvar1 != var2
    ltundefinedvar1 < var2
    gtundefinedvar1 > var2
    leundefinedvar1 <= var2
    geundefinedvar1 >= var2
    oeqfalsevar1 == var2
    onefalsevar1 != var2
    oltfalsevar1 < var2
    ogtfalsevar1 > var2
    olefalsevar1 <= var2
    ogefalsevar1 >= var2
    ueqtruevar1 == var2
    unetruevar1 != var2
    ulttruevar1 < var2
    ugttruevar1 > var2
    uletruevar1 <= var2
    ugetruevar1 >= var2
    ofalsealways
    utruenever
    truetruealways
    falsefalsenever
    + +
    Example:
    +
      <result> = vsetfp eq <2 x float> <float 0.0, float 1.0>, <float 1.0, float 0.0>      ; yields {<2 x bool>}:result = false, false
    +   <result> = vsetfp ne <2 x float> <float 0.0, float 1.0>, <float 1.0, float 0.0>      ; yields {<2 x bool>}:result = true, true
    +   <result> = vsetfp lt <2 x float> <float 0.0, float 1.0>, <float 1.0, float 0.0>      ; yields {<2 x bool>}:result = true, false
    +   <result> = vsetfp gt <2 x float> <float 0.0, float 1.0>, <float 1.0, float 0.0>      ; yields {<2 x bool>}:result = false, true
    +   <result> = vsetfp le <2 x float> <float 0.0, float 1.0>, <float 1.0, float 0.0>      ; yields {<2 x bool>}:result = true, false
    +   <result> = vsetfp ge <2 x float> <float 0.0, float 1.0>, <float 1.0, float 0.0>      ; yields {<2 x bool>}:result = false, true
    + 
    +
    + + + + +
    + +
    Syntax:
    + +
    +   <result> = vselect <n x bool> <cond>, <n x <ty>> <val1>, <n x <ty>> <val2> ; yields <n x <ty>>
    + 
    + +
    Overview:
    + +

    + The 'vselect' instruction chooses one value at each position + of a vector based on a condition. +

    + + +
    Arguments:
    + +

    + The 'vselect' instruction requires a packed bool value indicating the + condition at each vector position, and two values of the same packed + type. All three operands must have the same length. The type of the + result is the same as the type of the two value operands.

    + +
    Semantics:
    + +

    + At each position where the bool vector is true, that position + of the result gets its value from the first value argument; otherwise, + it gets its value from the second value argument. +

    + +
    Example:
    + +
    +   %X = vselect bool <2 x bool> <bool true, bool false>, <2 x ubyte> <ubyte 17, ubyte 17>, 
    +     <2 x ubyte> <ubyte 42, ubyte 42>      ; yields <2 x ubyte>:17, 42
    + 
    +
    + + + + + + +
    + +

    A key design point of an SSA-based representation is how it + represents memory. In LLVM, no memory locations are in SSA form, which + makes things very simple. This section describes how to read, write, + allocate, and free memory in LLVM.

    + +
    + + + + +
    + +
    Syntax:
    + +
    +   <result> = malloc <type>[, uint <NumElements>][, align <alignment>]     ; yields {type*}:result
    + 
    + +
    Overview:
    + +

    The 'malloc' instruction allocates memory from the system + heap and returns a pointer to it.

    + +
    Arguments:
    + +

    The 'malloc' instruction allocates + sizeof(<type>)*NumElements + bytes of memory from the operating system and returns a pointer of the + appropriate type to the program. If "NumElements" is specified, it is the + number of elements allocated. If an alignment is specified, the value result + of the allocation is guaranteed to be aligned to at least that boundary. If + not specified, or if zero, the target can choose to align the allocation on any + convenient boundary.

    + +

    'type' must be a sized type.

    + +
    Semantics:
    + +

    Memory is allocated using the system "malloc" function, and + a pointer is returned.

    + +
    Example:
    + +
    +   %array  = malloc [4 x ubyte ]                    ; yields {[%4 x ubyte]*}:array
    + 
    +   %size   = add uint 2, 2                          ; yields {uint}:size = uint 4
    +   %array1 = malloc ubyte, uint 4                   ; yields {ubyte*}:array1
    +   %array2 = malloc [12 x ubyte], uint %size        ; yields {[12 x ubyte]*}:array2
    +   %array3 = malloc int, uint 4, align 1024         ; yields {int*}:array3
    +   %array4 = malloc int, align 1024                 ; yields {int*}:array4
    + 
    +
    + + + + +
    + +
    Syntax:
    + +
    +   free <type> <value>                              ; yields {void}
    + 
    + +
    Overview:
    + +

    The 'free' instruction returns memory back to the unused + memory heap to be reallocated in the future.

    + +
    Arguments:
    + +

    'value' shall be a pointer value that points to a value + that was allocated with the 'malloc' + instruction.

    + +
    Semantics:
    + +

    Access to the memory pointed to by the pointer is no longer defined + after this instruction executes.

    + +
    Example:
    + +
    +   %array  = malloc [4 x ubyte]                    ; yields {[4 x ubyte]*}:array
    +             free   [4 x ubyte]* %array
    + 
    +
    + + + + +
    + +
    Syntax:
    + +
    +   <result> = alloca <type>[, uint <NumElements>][, align <alignment>]     ; yields {type*}:result
    + 
    + +
    Overview:
    + +

    The 'alloca' instruction allocates memory on the current + stack frame of the procedure that is live until the current function + returns to its caller.

    + +
    Arguments:
    + +

    The 'alloca' instruction allocates sizeof(<type>)*NumElements + bytes of memory on the runtime stack, returning a pointer of the + appropriate type to the program. If "NumElements" is specified, it is the + number of elements allocated. If an alignment is specified, the value result + of the allocation is guaranteed to be aligned to at least that boundary. If + not specified, or if zero, the target can choose to align the allocation on any + convenient boundary.

    + +

    'type' may be any sized type.

    + +
    Semantics:
    + +

    Memory is allocated; a pointer is returned. 'alloca'd + memory is automatically released when the function returns. The 'alloca' + instruction is commonly used to represent automatic variables that must + have an address available. When the function returns (either with the ret or unwind + instructions), the memory is reclaimed.

    + +
    Example:
    + +
    +   %ptr = alloca int                              ; yields {int*}:ptr
    +   %ptr = alloca int, uint 4                      ; yields {int*}:ptr
    +   %ptr = alloca int, uint 4, align 1024          ; yields {int*}:ptr
    +   %ptr = alloca int, align 1024                  ; yields {int*}:ptr
    + 
    +
    + + + +
    +
    Syntax:
    +
      <result> = load <ty>* <pointer>
    <result> = volatile load <ty>* <pointer>
    +
    Overview:
    +

    The 'load' instruction is used to read from memory.

    +
    Arguments:
    +

    The argument to the 'load' instruction specifies the memory + address from which to load. The pointer must point to a first class type. If the load is + marked as volatile, then the optimizer is not allowed to modify + the number or order of execution of this load with other + volatile load and store + instructions.

    +
    Semantics:
    +

    The location of memory pointed to is loaded.

    +
    Examples:
    +
      %ptr = alloca int                               ; yields {int*}:ptr
    +   store int 3, int* %ptr                          ; yields {void}
    +   %val = load int* %ptr                           ; yields {int}:val = int 3
    + 
    +
    + + +
    Syntax:
    +
      store <ty> <value>, <ty>* <pointer>                   ; yields {void}
    +   volatile store <ty> <value>, <ty>* <pointer>                   ; yields {void}
    + 
    +
    Overview:
    +

    The 'store' instruction is used to write to memory.

    +
    Arguments:
    +

    There are two arguments to the 'store' instruction: a value + to store and an address in which to store it. The type of the '<pointer>' + operand must be a pointer to the type of the '<value>' + operand. If the store is marked as volatile, then the + optimizer is not allowed to modify the number or order of execution of + this store with other volatile load and store instructions.

    +
    Semantics:
    +

    The contents of memory are updated to contain '<value>' + at the location specified by the '<pointer>' operand.

    +
    Example:
    +
      %ptr = alloca int                               ; yields {int*}:ptr
    +   store int 3, int* %ptr                          ; yields {void}
    +   %val = load int* %ptr                           ; yields {int}:val = int 3
    + 
    + + + +
    +
    Syntax:
    +
    +   <result> = getelementptr <ty>* <ptrval>{, <ty> <idx>}*
    + 
    + +
    Overview:
    + +

    + The 'getelementptr' instruction is used to get the address of a + subelement of an aggregate data structure.

    + +
    Arguments:
    + +

    This instruction takes a list of integer constants that indicate what + elements of the aggregate object to index to. The actual types of the arguments + provided depend on the type of the first pointer argument. The + 'getelementptr' instruction is used to index down through the type + levels of a structure or to a specific index in an array. When indexing into a + structure, only uint + integer constants are allowed. When indexing into an array or pointer, + int and long indexes are allowed of any sign.

    + +

    For example, let's consider a C code fragment and how it gets + compiled to LLVM:

    + +
    +   struct RT {
    +     char A;
    +     int B[10][20];
    +     char C;
    +   };
    +   struct ST {
    +     int X;
    +     double Y;
    +     struct RT Z;
    +   };
    + 
    +   int *foo(struct ST *s) {
    +     return &s[1].Z.B[5][13];
    +   }
    + 
    + +

    The LLVM code generated by the GCC frontend is:

    + +
    +   %RT = type { sbyte, [10 x [20 x int]], sbyte }
    +   %ST = type { int, double, %RT }
    + 
    +   implementation
    + 
    +   int* %foo(%ST* %s) {
    +   entry:
    +     %reg = getelementptr %ST* %s, int 1, uint 2, uint 1, int 5, int 13
    +     ret int* %reg
    +   }
    + 
    + +
    Semantics:
    + +

    The index types specified for the 'getelementptr' instruction depend + on the pointer type that is being indexed into. Pointer + and array types require uint, int, + ulong, or long values, and structure + types require uint constants.

    + +

    In the example above, the first index is indexing into the '%ST*' + type, which is a pointer, yielding a '%ST' = '{ int, double, %RT + }' type, a structure. The second index indexes into the third element of + the structure, yielding a '%RT' = '{ sbyte, [10 x [20 x int]], + sbyte }' type, another structure. The third index indexes into the second + element of the structure, yielding a '[10 x [20 x int]]' type, an + array. The two dimensions of the array are subscripted into, yielding an + 'int' type. The 'getelementptr' instruction returns a pointer + to this element, thus computing a value of 'int*' type.

    + +

    Note that it is perfectly legal to index partially through a + structure, returning a pointer to an inner element. Because of this, + the LLVM code for the given testcase is equivalent to:

    + +
    +   int* %foo(%ST* %s) {
    +     %t1 = getelementptr %ST* %s, int 1                        ; yields %ST*:%t1
    +     %t2 = getelementptr %ST* %t1, int 0, uint 2               ; yields %RT*:%t2
    +     %t3 = getelementptr %RT* %t2, int 0, uint 1               ; yields [10 x [20 x int]]*:%t3
    +     %t4 = getelementptr [10 x [20 x int]]* %t3, int 0, int 5  ; yields [20 x int]*:%t4
    +     %t5 = getelementptr [20 x int]* %t4, int 0, int 13        ; yields int*:%t5
    +     ret int* %t5
    +   }
    + 
    + +

    Note that it is undefined to access an array out of bounds: array and + pointer indexes must always be within the defined bounds of the array type. + The one exception for this rules is zero length arrays. These arrays are + defined to be accessible as variable length arrays, which requires access + beyond the zero'th element.

    + +
    Example:
    + +
    +     ; yields [12 x ubyte]*:aptr
    +     %aptr = getelementptr {int, [12 x ubyte]}* %sptr, long 0, uint 1
    + 
    + +
    + + +
    +

    The instructions in this category are the "miscellaneous" + instructions, which defy better classification.

    +
    + + +
    +
    Syntax:
    +
      <result> = phi <ty> [ <val0>, <label0>], ...
    +
    Overview:
    +

    The 'phi' instruction is used to implement the φ node in + the SSA graph representing the function.

    +
    Arguments:
    +

    The type of the incoming values are specified with the first type + field. After this, the 'phi' instruction takes a list of pairs + as arguments, with one pair for each predecessor basic block of the + current block. Only values of first class + type may be used as the value arguments to the PHI node. Only labels + may be used as the label arguments.

    +

    There must be no non-phi instructions between the start of a basic + block and the PHI instructions: i.e. PHI instructions must be first in + a basic block.

    +
    Semantics:
    +

    At runtime, the 'phi' instruction logically takes on the + value specified by the parameter, depending on which basic block we + came from in the last terminator instruction.

    +
    Example:
    +
    Loop:       ; Infinite loop that counts from 0 on up...
    %indvar = phi uint [ 0, %LoopHeader ], [ %nextindvar, %Loop ]
    %nextindvar = add uint %indvar, 1
    br label %Loop
    +
    + + + + +
    + +
    Syntax:
    + +
    +   <result> = cast <ty> <value> to <ty2>             ; yields ty2
    + 
    + +
    Overview:
    + +

    + The 'cast' instruction is used as the primitive means to convert + integers to floating point, change data type sizes, and break type safety (by + casting pointers). +

    + + +
    Arguments:
    + +

    + The 'cast' instruction takes a value to cast, which must be a first + class value, and a type to cast it to, which must also be a first class type. +

    + +
    Semantics:
    + +

    + This instruction follows the C rules for explicit casts when determining how the + data being cast must change to fit in its new container. +

    + +

    + When casting to bool, any value that would be considered true in the context of + a C 'if' condition is converted to the boolean 'true' values, + all else are 'false'. +

    + +

    + When extending an integral value from a type of one signness to another (for + example 'sbyte' to 'ulong'), the value is sign-extended if the + source value is signed, and zero-extended if the source value is + unsigned. bool values are always zero extended into either zero or + one. +

    + +
    Example:
    + +
    +   %X = cast int 257 to ubyte              ; yields ubyte:1
    +   %Y = cast int 123 to bool               ; yields bool:true
    + 
    +
    + + + + +
    + +
    Syntax:
    + +
    +   <result> = select bool <cond>, <ty> <val1>, <ty> <val2>             ; yields ty
    + 
    + +
    Overview:
    + +

    + The 'select' instruction is used to choose one value based on a + condition, without branching. +

    + + +
    Arguments:
    + +

    + The 'select' instruction requires a boolean value indicating the condition, and two values of the same first class type. +

    + +
    Semantics:
    + +

    + If the boolean condition evaluates to true, the instruction returns the first + value argument; otherwise, it returns the second value argument. +

    + +
    Example:
    + +
    +   %X = select bool true, ubyte 17, ubyte 42          ; yields ubyte:17
    + 
    +
    + + + + + +
    + +
    Syntax:
    +
    +   <result> = [tail] call [cconv] <ty>* <fnptrval>(<param list>)
    + 
    + +
    Overview:
    + +

    The 'call' instruction represents a simple function call.

    + +
    Arguments:
    + +

    This instruction requires several arguments:

    + +
      +
    1. +

      The optional "tail" marker indicates whether the callee function accesses + any allocas or varargs in the caller. If the "tail" marker is present, the + function call is eligible for tail call optimization. Note that calls may + be marked "tail" even if they do not occur before a ret instruction. +

    2. +
    3. +

      The optional "cconv" marker indicates which calling + convention the call should use. If none is specified, the call defaults + to using C calling conventions. +

    4. +
    5. +

      'ty': shall be the signature of the pointer to function value + being invoked. The argument types must match the types implied by this + signature. This type can be omitted if the function is not varargs and + if the function type does not return a pointer to a function.

      +
    6. +
    7. +

      'fnptrval': An LLVM value containing a pointer to a function to + be invoked. In most cases, this is a direct function invocation, but + indirect calls are just as possible, calling an arbitrary pointer + to function value.

      +
    8. +
    9. +

      'function args': argument list whose types match the + function signature argument types. All arguments must be of + first class type. If the function signature + indicates the function accepts a variable number of arguments, the extra + arguments can be specified.

      +
    10. +
    + +
    Semantics:
    + +

    The 'call' instruction is used to cause control flow to + transfer to a specified function, with its incoming arguments bound to + the specified values. Upon a 'ret' + instruction in the called function, control flow continues with the + instruction after the function call, and the return value of the + function is bound to the result argument. This is a simpler case of + the invoke instruction.

    + +
    Example:
    + +
    +   %retval = call int %test(int %argc)
    +   call int(sbyte*, ...) *%printf(sbyte* %msg, int 12, sbyte 42);
    +   %X = tail call int %foo()
    +   %Y = tail call fastcc int %foo()
    + 
    + +
    + + + + +
    + +
    Syntax:
    + +
    +   <resultval> = va_arg <va_list*> <arglist>, <argty>
    + 
    + +
    Overview:
    + +

    The 'va_arg' instruction is used to access arguments passed through + the "variable argument" area of a function call. It is used to implement the + va_arg macro in C.

    + +
    Arguments:
    + +

    This instruction takes a va_list* value and the type of + the argument. It returns a value of the specified argument type and + increments the va_list to point to the next argument. Again, the + actual type of va_list is target specific.

    + +
    Semantics:
    + +

    The 'va_arg' instruction loads an argument of the specified + type from the specified va_list and causes the + va_list to point to the next argument. For more information, + see the variable argument handling Intrinsic + Functions.

    + +

    It is legal for this instruction to be called in a function which does not + take a variable number of arguments, for example, the vfprintf + function.

    + +

    va_arg is an LLVM instruction instead of an intrinsic function because it takes a type as an + argument.

    + +
    Example:
    + +

    See the variable argument processing section.

    + +
    + + + + + +
    + +

    LLVM supports the notion of an "intrinsic function". These functions have + well known names and semantics and are required to follow certain + restrictions. Overall, these instructions represent an extension mechanism for + the LLVM language that does not require changing all of the transformations in + LLVM to add to the language (or the bytecode reader/writer, the parser, + etc...).

    + +

    Intrinsic function names must all start with an "llvm." prefix. This + prefix is reserved in LLVM for intrinsic names; thus, functions may not be named + this. Intrinsic functions must always be external functions: you cannot define + the body of intrinsic functions. Intrinsic functions may only be used in call + or invoke instructions: it is illegal to take the address of an intrinsic + function. Additionally, because intrinsic functions are part of the LLVM + language, it is required that they all be documented here if any are added.

    + + +

    To learn how to add an intrinsic function, please see the Extending LLVM Guide. +

    + +
    + + + + +
    + +

    Variable argument support is defined in LLVM with the va_arg instruction and these three + intrinsic functions. These functions are related to the similarly + named macros defined in the <stdarg.h> header file.

    + +

    All of these functions operate on arguments that use a + target-specific value type "va_list". The LLVM assembly + language reference manual does not define what this type is, so all + transformations should be prepared to handle intrinsics with any type + used.

    + +

    This example shows how the va_arg + instruction and the variable argument handling intrinsic functions are + used.

    + +
    + int %test(int %X, ...) {
    +   ; Initialize variable argument processing
    +   %ap = alloca sbyte*
    +   call void %llvm.va_start(sbyte** %ap)
    + 
    +   ; Read a single integer argument
    +   %tmp = va_arg sbyte** %ap, int
    + 
    +   ; Demonstrate usage of llvm.va_copy and llvm.va_end
    +   %aq = alloca sbyte*
    +   call void %llvm.va_copy(sbyte** %aq, sbyte** %ap)
    +   call void %llvm.va_end(sbyte** %aq)
    + 
    +   ; Stop processing of arguments.
    +   call void %llvm.va_end(sbyte** %ap)
    +   ret int %tmp
    + }
    + 
    +
    + + + + + +
    +
    Syntax:
    +
      declare void %llvm.va_start(<va_list>* <arglist>)
    +
    Overview:
    +

    The 'llvm.va_start' intrinsic initializes + *<arglist> for subsequent use by va_arg.

    + +
    Arguments:
    + +

    The argument is a pointer to a va_list element to initialize.

    + +
    Semantics:
    + +

    The 'llvm.va_start' intrinsic works just like the va_start + macro available in C. In a target-dependent way, it initializes the + va_list element the argument points to, so that the next call to + va_arg will produce the first variable argument passed to the function. + Unlike the C va_start macro, this intrinsic does not need to know the + last argument of the function, the compiler can figure that out.

    + +
    + + + + +
    +
    Syntax:
    +
      declare void %llvm.va_end(<va_list*> <arglist>)
    +
    Overview:
    +

    The 'llvm.va_end' intrinsic destroys <arglist> + which has been initialized previously with llvm.va_start + or llvm.va_copy.

    +
    Arguments:
    +

    The argument is a va_list to destroy.

    +
    Semantics:
    +

    The 'llvm.va_end' intrinsic works just like the va_end + macro available in C. In a target-dependent way, it destroys the va_list. + Calls to llvm.va_start and llvm.va_copy must be matched exactly + with calls to llvm.va_end.

    +
    + + + + +
    + +
    Syntax:
    + +
    +   declare void %llvm.va_copy(<va_list>* <destarglist>,
    +                                           <va_list>* <srcarglist>)
    + 
    + +
    Overview:
    + +

    The 'llvm.va_copy' intrinsic copies the current argument position from + the source argument list to the destination argument list.

    + +
    Arguments:
    + +

    The first argument is a pointer to a va_list element to initialize. + The second argument is a pointer to a va_list element to copy from.

    + + +
    Semantics:
    + +

    The 'llvm.va_copy' intrinsic works just like the va_copy macro + available in C. In a target-dependent way, it copies the source + va_list element into the destination list. This intrinsic is necessary + because the llvm.va_begin intrinsic may be + arbitrarily complex and require memory allocation, for example.

    + +
    + + + + +
    + +

    + LLVM support for Accurate Garbage + Collection requires the implementation and generation of these intrinsics. + These intrinsics allow identification of GC roots on the + stack, as well as garbage collector implementations that require read and write barriers. + Front-ends for type-safe garbage collected languages should generate these + intrinsics to make use of the LLVM garbage collectors. For more details, see Accurate Garbage Collection with LLVM. +

    +
    + + + + +
    + +
    Syntax:
    + +
    +   declare void %llvm.gcroot(<ty>** %ptrloc, <ty2>* %metadata)
    + 
    + +
    Overview:
    + +

    The 'llvm.gcroot' intrinsic declares the existence of a GC root to + the code generator, and allows some metadata to be associated with it.

    + +
    Arguments:
    + +

    The first argument specifies the address of a stack object that contains the + root pointer. The second pointer (which must be either a constant or a global + value address) contains the meta-data to be associated with the root.

    + +
    Semantics:
    + +

    At runtime, a call to this intrinsics stores a null pointer into the "ptrloc" + location. At compile-time, the code generator generates information to allow + the runtime to find the pointer at GC safe points. +

    + +
    + + + + + +
    + +
    Syntax:
    + +
    +   declare sbyte* %llvm.gcread(sbyte* %ObjPtr, sbyte** %Ptr)
    + 
    + +
    Overview:
    + +

    The 'llvm.gcread' intrinsic identifies reads of references from heap + locations, allowing garbage collector implementations that require read + barriers.

    + +
    Arguments:
    + +

    The second argument is the address to read from, which should be an address + allocated from the garbage collector. The first object is a pointer to the + start of the referenced object, if needed by the language runtime (otherwise + null).

    + +
    Semantics:
    + +

    The 'llvm.gcread' intrinsic has the same semantics as a load + instruction, but may be replaced with substantially more complex code by the + garbage collector runtime, as needed.

    + +
    + + + + + +
    + +
    Syntax:
    + +
    +   declare void %llvm.gcwrite(sbyte* %P1, sbyte* %Obj, sbyte** %P2)
    + 
    + +
    Overview:
    + +

    The 'llvm.gcwrite' intrinsic identifies writes of references to heap + locations, allowing garbage collector implementations that require write + barriers (such as generational or reference counting collectors).

    + +
    Arguments:
    + +

    The first argument is the reference to store, the second is the start of the + object to store it to, and the third is the address of the field of Obj to + store to. If the runtime does not require a pointer to the object, Obj may be + null.

    + +
    Semantics:
    + +

    The 'llvm.gcwrite' intrinsic has the same semantics as a store + instruction, but may be replaced with substantially more complex code by the + garbage collector runtime, as needed.

    + +
    + + + + + + +
    +

    + These intrinsics are provided by LLVM to expose special features that may only + be implemented with code generator support. +

    + +
    + + + + +
    + +
    Syntax:
    +
    +   declare sbyte *%llvm.returnaddress(uint <level>)
    + 
    + +
    Overview:
    + +

    + The 'llvm.returnaddress' intrinsic returns a target-specific value + indicating the return address of the current function or one of its callers. +

    + +
    Arguments:
    + +

    + The argument to this intrinsic indicates which function to return the address + for. Zero indicates the calling function, one indicates its caller, etc. The + argument is required to be a constant integer value. +

    + +
    Semantics:
    + +

    + The 'llvm.returnaddress' intrinsic either returns a pointer indicating + the return address of the specified call frame, or zero if it cannot be + identified. The value returned by this intrinsic is likely to be incorrect or 0 + for arguments other than zero, so it should only be used for debugging purposes. +

    + +

    + Note that calling this intrinsic does not prevent function inlining or other + aggressive transformations, so the value returned may not be that of the obvious + source-language caller. +

    +
    + + + + + +
    + +
    Syntax:
    +
    +   declare sbyte *%llvm.frameaddress(uint <level>)
    + 
    + +
    Overview:
    + +

    + The 'llvm.frameaddress' intrinsic returns the target-specific frame + pointer value for the specified stack frame. +

    + +
    Arguments:
    + +

    + The argument to this intrinsic indicates which function to return the frame + pointer for. Zero indicates the calling function, one indicates its caller, + etc. The argument is required to be a constant integer value. +

    + +
    Semantics:
    + +

    + The 'llvm.frameaddress' intrinsic either returns a pointer indicating + the frame address of the specified call frame, or zero if it cannot be + identified. The value returned by this intrinsic is likely to be incorrect or 0 + for arguments other than zero, so it should only be used for debugging purposes. +

    + +

    + Note that calling this intrinsic does not prevent function inlining or other + aggressive transformations, so the value returned may not be that of the obvious + source-language caller. +

    +
    + + + + +
    + +
    Syntax:
    +
    +   declare sbyte *%llvm.stacksave()
    + 
    + +
    Overview:
    + +

    + The 'llvm.stacksave' intrinsic is used to remember the current state of + the function stack, for use with + llvm.stackrestore. This is useful for implementing language + features like scoped automatic variable sized arrays in C99. +

    + +
    Semantics:
    + +

    + This intrinsic returns a opaque pointer value that can be passed to llvm.stackrestore. When an + llvm.stackrestore intrinsic is executed with a value saved from + llvm.stacksave, it effectively restores the state of the stack to the + state it was in when the llvm.stacksave intrinsic executed. In + practice, this pops any alloca blocks from the stack + that were allocated after the llvm.stacksave was executed. +

    + +
    + + + + +
    + +
    Syntax:
    +
    +   declare void %llvm.stackrestore(sbyte* %ptr)
    + 
    + +
    Overview:
    + +

    + The 'llvm.stackrestore' intrinsic is used to restore the state of + the function stack to the state it was in when the corresponding llvm.stacksave intrinsic executed. This is + useful for implementing language features like scoped automatic variable sized + arrays in C99. +

    + +
    Semantics:
    + +

    + See the description for llvm.stacksave. +

    + +
    + + + + + +
    + +
    Syntax:
    +
    +   declare void %llvm.prefetch(sbyte * <address>,
    +                                 uint <rw>, uint <locality>)
    + 
    + +
    Overview:
    + + +

    + The 'llvm.prefetch' intrinsic is a hint to the code generator to insert + a prefetch instruction if supported; otherwise, it is a noop. Prefetches have + no + effect on the behavior of the program but can change its performance + characteristics. +

    + +
    Arguments:
    + +

    + address is the address to be prefetched, rw is the specifier + determining if the fetch should be for a read (0) or write (1), and + locality is a temporal locality specifier ranging from (0) - no + locality, to (3) - extremely local keep in cache. The rw and + locality arguments must be constant integers. +

    + +
    Semantics:
    + +

    + This intrinsic does not modify the behavior of the program. In particular, + prefetches cannot trap and do not produce a value. On targets that support this + intrinsic, the prefetch can provide hints to the processor cache for better + performance. +

    + +
    + + + + +
    + +
    Syntax:
    +
    +   declare void %llvm.pcmarker( uint <id> )
    + 
    + +
    Overview:
    + + +

    + The 'llvm.pcmarker' intrinsic is a method to export a Program Counter + (PC) in a region of + code to simulators and other tools. The method is target specific, but it is + expected that the marker will use exported symbols to transmit the PC of the marker. + The marker makes no guarantees that it will remain with any specific instruction + after optimizations. It is possible that the presence of a marker will inhibit + optimizations. The intended use is to be inserted after optimizations to allow + correlations of simulation runs. +

    + +
    Arguments:
    + +

    + id is a numerical id identifying the marker. +

    + +
    Semantics:
    + +

    + This intrinsic does not modify the behavior of the program. Backends that do not + support this intrinisic may ignore it. +

    + +
    + + + + +
    + +
    Syntax:
    +
    +   declare ulong %llvm.readcyclecounter( )
    + 
    + +
    Overview:
    + + +

    + The 'llvm.readcyclecounter' intrinsic provides access to the cycle + counter register (or similar low latency, high accuracy clocks) on those targets + that support it. On X86, it should map to RDTSC. On Alpha, it should map to RPCC. + As the backing counters overflow quickly (on the order of 9 seconds on alpha), this + should only be used for small timings. +

    + +
    Semantics:
    + +

    + When directly supported, reading the cycle counter should not modify any memory. + Implementations are allowed to either return a application specific value or a + system wide value. On backends without support, this is lowered to a constant 0. +

    + +
    + + + + +
    +

    + LLVM provides intrinsics for a few important standard C library functions. + These intrinsics allow source-language front-ends to pass information about the + alignment of the pointer arguments to the code generator, providing opportunity + for more efficient code generation. +

    + +
    + + + + +
    + +
    Syntax:
    +
    +   declare void %llvm.memcpy.i32(sbyte* <dest>, sbyte* <src>,
    +                                 uint <len>, uint <align>)
    +   declare void %llvm.memcpy.i64(sbyte* <dest>, sbyte* <src>,
    +                                 ulong <len>, uint <align>)
    + 
    + +
    Overview:
    + +

    + The 'llvm.memcpy.*' intrinsics copy a block of memory from the source + location to the destination location. +

    + +

    + Note that, unlike the standard libc function, the llvm.memcpy.* + intrinsics do not return a value, and takes an extra alignment argument. +

    + +
    Arguments:
    + +

    + The first argument is a pointer to the destination, the second is a pointer to + the source. The third argument is an integer argument + specifying the number of bytes to copy, and the fourth argument is the alignment + of the source and destination locations. +

    + +

    + If the call to this intrinisic has an alignment value that is not 0 or 1, then + the caller guarantees that both the source and destination pointers are aligned + to that boundary. +

    + +
    Semantics:
    + +

    + The 'llvm.memcpy.*' intrinsics copy a block of memory from the source + location to the destination location, which are not allowed to overlap. It + copies "len" bytes of memory over. If the argument is known to be aligned to + some boundary, this can be specified as the fourth argument, otherwise it should + be set to 0 or 1. +

    +
    + + + + + +
    + +
    Syntax:
    +
    +   declare void %llvm.memmove.i32(sbyte* <dest>, sbyte* <src>,
    +                                  uint <len>, uint <align>)
    +   declare void %llvm.memmove.i64(sbyte* <dest>, sbyte* <src>,
    +                                  ulong <len>, uint <align>)
    + 
    + +
    Overview:
    + +

    + The 'llvm.memmove.*' intrinsics move a block of memory from the source + location to the destination location. It is similar to the + 'llvm.memcmp' intrinsic but allows the two memory locations to overlap. +

    + +

    + Note that, unlike the standard libc function, the llvm.memmove.* + intrinsics do not return a value, and takes an extra alignment argument. +

    + +
    Arguments:
    + +

    + The first argument is a pointer to the destination, the second is a pointer to + the source. The third argument is an integer argument + specifying the number of bytes to copy, and the fourth argument is the alignment + of the source and destination locations. +

    + +

    + If the call to this intrinisic has an alignment value that is not 0 or 1, then + the caller guarantees that the source and destination pointers are aligned to + that boundary. +

    + +
    Semantics:
    + +

    + The 'llvm.memmove.*' intrinsics copy a block of memory from the source + location to the destination location, which may overlap. It + copies "len" bytes of memory over. If the argument is known to be aligned to + some boundary, this can be specified as the fourth argument, otherwise it should + be set to 0 or 1. +

    +
    + + + + + +
    + +
    Syntax:
    +
    +   declare void %llvm.memset.i32(sbyte* <dest>, ubyte <val>,
    +                                 uint <len>, uint <align>)
    +   declare void %llvm.memset.i64(sbyte* <dest>, ubyte <val>,
    +                                 ulong <len>, uint <align>)
    + 
    + +
    Overview:
    + +

    + The 'llvm.memset.*' intrinsics fill a block of memory with a particular + byte value. +

    + +

    + Note that, unlike the standard libc function, the llvm.memset intrinsic + does not return a value, and takes an extra alignment argument. +

    + +
    Arguments:
    + +

    + The first argument is a pointer to the destination to fill, the second is the + byte value to fill it with, the third argument is an integer + argument specifying the number of bytes to fill, and the fourth argument is the + known alignment of destination location. +

    + +

    + If the call to this intrinisic has an alignment value that is not 0 or 1, then + the caller guarantees that the destination pointer is aligned to that boundary. +

    + +
    Semantics:
    + +

    + The 'llvm.memset.*' intrinsics fill "len" bytes of memory starting at + the + destination location. If the argument is known to be aligned to some boundary, + this can be specified as the fourth argument, otherwise it should be set to 0 or + 1. +

    +
    + + + + + +
    + +
    Syntax:
    +
    +   declare bool %llvm.isunordered.f32(float Val1, float  Val2)
    +   declare bool %llvm.isunordered.f64(double Val1, double Val2)
    + 
    + +
    Overview:
    + +

    + The 'llvm.isunordered' intrinsics return true if either or both of the + specified floating point values is a NAN. +

    + +
    Arguments:
    + +

    + The arguments are floating point numbers of the same type. +

    + +
    Semantics:
    + +

    + If either or both of the arguments is a SNAN or QNAN, it returns true, otherwise + false. +

    +
    + + + + + +
    + +
    Syntax:
    +
    +   declare double %llvm.sqrt.f32(float Val)
    +   declare double %llvm.sqrt.f64(double Val)
    + 
    + +
    Overview:
    + +

    + The 'llvm.sqrt' intrinsics return the sqrt of the specified operand, + returning the same value as the libm 'sqrt' function would. Unlike + sqrt in libm, however, llvm.sqrt has undefined behavior for + negative numbers (which allows for better optimization). +

    + +
    Arguments:
    + +

    + The argument and return value are floating point numbers of the same type. +

    + +
    Semantics:
    + +

    + This function returns the sqrt of the specified operand if it is a positive + floating point number. +

    +
    + + + + +
    +

    + LLVM provides intrinsics for a few important bit manipulation operations. + These allow efficient code generation for some algorithms. +

    + +
    + + + + +
    + +
    Syntax:
    +
    +   declare ushort %llvm.bswap.i16(ushort <id>)
    +   declare uint   %llvm.bswap.i32(uint <id>)
    +   declare ulong  %llvm.bswap.i64(ulong <id>)
    + 
    + +
    Overview:
    + +

    + The 'llvm.bwsap' family of intrinsics is used to byteswap a 16, 32 or + 64 bit quantity. These are useful for performing operations on data that is not + in the target's native byte order. +

    + +
    Semantics:
    + +

    + The llvm.bswap.16 intrinsic returns a ushort value that has the high and low + byte of the input ushort swapped. Similarly, the llvm.bswap.i32 intrinsic + returns a uint value that has the four bytes of the input uint swapped, so that + if the input bytes are numbered 0, 1, 2, 3 then the returned uint will have its + bytes in 3, 2, 1, 0 order. The llvm.bswap.i64 intrinsic extends this concept + to 64 bits. +

    + +
    + + + + +
    + +
    Syntax:
    +
    +   declare ubyte  %llvm.ctpop.i8 (ubyte <src>)
    +   declare ushort %llvm.ctpop.i16(ushort <src>)
    +   declare uint   %llvm.ctpop.i32(uint <src>)
    +   declare ulong  %llvm.ctpop.i64(ulong <src>)
    + 
    + +
    Overview:
    + +

    + The 'llvm.ctpop' family of intrinsics counts the number of bits set in a + value. +

    + +
    Arguments:
    + +

    + The only argument is the value to be counted. The argument may be of any + unsigned integer type. The return type must match the argument type. +

    + +
    Semantics:
    + +

    + The 'llvm.ctpop' intrinsic counts the 1's in a variable. +

    +
    + + + + +
    + +
    Syntax:
    +
    +   declare ubyte  %llvm.ctlz.i8 (ubyte <src>)
    +   declare ushort %llvm.ctlz.i16(ushort <src>)
    +   declare uint   %llvm.ctlz.i32(uint <src>)
    +   declare ulong  %llvm.ctlz.i64(ulong <src>)
    + 
    + +
    Overview:
    + +

    + The 'llvm.ctlz' family of intrinsic functions counts the number of + leading zeros in a variable. +

    + +
    Arguments:
    + +

    + The only argument is the value to be counted. The argument may be of any + unsigned integer type. The return type must match the argument type. +

    + +
    Semantics:
    + +

    + The 'llvm.ctlz' intrinsic counts the leading (most significant) zeros + in a variable. If the src == 0 then the result is the size in bits of the type + of src. For example, llvm.ctlz(int 2) = 30. +

    +
    + + + + + + +
    + +
    Syntax:
    +
    +   declare ubyte  %llvm.cttz.i8 (ubyte <src>)
    +   declare ushort %llvm.cttz.i16(ushort <src>)
    +   declare uint   %llvm.cttz.i32(uint <src>)
    +   declare ulong  %llvm.cttz.i64(ulong <src>)
    + 
    + +
    Overview:
    + +

    + The 'llvm.cttz' family of intrinsic functions counts the number of + trailing zeros. +

    + +
    Arguments:
    + +

    + The only argument is the value to be counted. The argument may be of any + unsigned integer type. The return type must match the argument type. +

    + +
    Semantics:
    + +

    + The 'llvm.cttz' intrinsic counts the trailing (least significant) zeros + in a variable. If the src == 0 then the result is the size in bits of the type + of src. For example, llvm.cttz(2) = 1. +

    +
    + + + + +
    +

    + The LLVM debugger intrinsics (which all start with llvm.dbg. prefix), + are described in the LLVM Source Level + Debugging document. +

    +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + Index: llvm-www/releases/1.8/docs/Lexicon.html diff -c /dev/null llvm-www/releases/1.8/docs/Lexicon.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/Lexicon.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,178 ---- + + + + + The LLVM Lexicon + + + + + +
    The LLVM Lexicon
    +

    NOTE: This document is a work in progress!

    + +
    Table Of Contents
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    - A -
    ADCE
    - B -
    BURS
    - C -
    CSE
    - D -
    DSADSE
    - I -
    IPAIPO
    - L -
    LICMLoad-VN
    - P -
    PRE
    - R -
    Reassociation
    - S -
    SCCSCCPSRoASSA
    +
    + + +
    Definitions
    + + + +
    +
    +
    ADCE
    +
    Aggressive Dead Code Elimination
    +
    +
    + + +
    +
    +
    BURS
    +
    Bottom Up Rewriting System - A method of instruction selection for + code generation. An example is the BURG tool.
    +
    +
    + + +
    +
    +
    CSE
    +
    Common Subexpression Elimination. An optimization that removes common + subexpression compuation. For example (a+b)*(a+b) has two + subexpressions that are the same: (a+b). This optimization would + perform the addition only once and then perform the multiply (but only if + its compulationally correct/safe). +
    +
    + + +
    +
    +
    DSA
    +
    Data Structure Analysis
    +
    DSE
    +
    Dead Store Elimination
    +
    +
    + + +
    +
    +
    IPA
    +
    Inter-Procedural Analysis. Refers to any variety of code analysis that + occurs between procedures, functions or compilation units (modules).
    +
    IPO
    +
    Inter-Procedural Optimization. Refers to any variety of code + optimization that occurs between procedures, functions or compilation units + (modules).
    +
    +
    + + +
    +
    +
    LICM
    +
    Loop Invariant Code Motion
    +
    Load-VN
    +
    Load Value Numbering
    +
    +
    + + + +
    +
    +
    PRE
    +
    Partial Redundancy Elimination
    +
    +
    + + + +
    +
    +
    Reassociation
    Rearranging + associative expressions to promote better redundancy elimination and other + optimization. For example, changing (A+B-A) into (B+A-A), permitting it to + be optimized into (B+0) then (B). +
    +
    + + + +
    +
    +
    SCC
    +
    Strongly Connected Component
    +
    SCCP
    +
    Sparse Conditional Constant Propagation
    +
    SRoA
    +
    Scalar Replacement of Aggregates
    +
    SSA
    +
    Static Single Assignment
    +
    +
    + +
    +
    Valid CSS!Valid HTML 4.01!The LLVM Team
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/Makefile diff -c /dev/null llvm-www/releases/1.8/docs/Makefile:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/Makefile Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,83 ---- + ##===- docs/Makefile ---------------------------------------*- Makefile -*-===## + # + # The LLVM Compiler Infrastructure + # + # This file was developed by the LLVM research group and is distributed under + # the University of Illinois Open Source License. See LICENSE.TXT for details. + # + ##===----------------------------------------------------------------------===## + + LEVEL := .. + DIRS := CommandGuide + + ifdef BUILD_FOR_WEBSITE + PROJ_OBJ_DIR = . + DOXYGEN = doxygen + + doxygen.cfg: doxygen.cfg.in + cat $< | sed 's/@abs_top_srcdir@/../g' | sed 's/@DOT@/dot/g' | \ + sed 's/@PACKAGE_VERSION@/CVS/g' | sed 's/@abs_top_builddir@/../g' > $@ + endif + + include $(LEVEL)/Makefile.common + + HTML := $(wildcard $(PROJ_SRC_DIR)/*.html) \ + $(wildcard $(PROJ_SRC_DIR)/*.css) + IMAGES := $(wildcard $(PROJ_SRC_DIR)/img/*.*) + DOXYFILES := doxygen.cfg.in doxygen.css doxygen.footer doxygen.header \ + doxygen.intro + EXTRA_DIST := $(HTML) $(DOXYFILES) llvm.css CommandGuide img + + .PHONY: install-html install-doxygen doxygen + + ifeq ($(ENABLE_DOXYGEN),1) + install-local:: install-html install-doxygen + else + install-local:: install-html + endif + + install-html: $(PROJ_OBJ_DIR)/html.tar.gz + $(Echo) Installing HTML documentation + $(Verb) $(MKDIR) $(PROJ_docsdir)/html + $(Verb) $(MKDIR) $(PROJ_docsdir)/html/img + $(Verb) $(DataInstall) $(HTML) $(PROJ_docsdir)/html + $(Verb) $(DataInstall) $(IMAGES) $(PROJ_docsdir)/html/img + $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/html.tar.gz $(PROJ_docsdir) + + $(PROJ_OBJ_DIR)/html.tar.gz: $(HTML) + $(Echo) Packaging HTML documentation + $(Verb) $(RM) -rf $@ $(PROJ_OBJ_DIR)/html.tar + $(Verb) cd $(PROJ_SRC_DIR) && \ + $(TAR) cf $(PROJ_OBJ_DIR)/html.tar *.html + $(Verb) $(GZIP) $(PROJ_OBJ_DIR)/html.tar + + install-doxygen: doxygen + $(Echo) Installing doxygen documentation + $(Echo) Installing doxygen documentation + $(Verb) $(MKDIR) $(PROJ_docsdir)/html/doxygen + $(Verb) $(DataInstall) $(PROJ_OBJ_DIR)/doxygen.tar.gz $(PROJ_docsdir) + $(Verb) cd $(PROJ_OBJ_DIR)/doxygen && \ + $(FIND) . -type f -exec \ + $(DataInstall) {} $(PROJ_docsdir)/html/doxygen \; + + doxygen: $(PROJ_OBJ_DIR)/doxygen.tar.gz + + $(PROJ_OBJ_DIR)/doxygen.tar.gz: $(DOXYFILES) $(PROJ_OBJ_DIR)/doxygen.cfg + $(Echo) Building doxygen documentation + $(Verb) if test -e $(PROJ_OBJ_DIR)/doxygen ; then \ + $(RM) -rf $(PROJ_OBJ_DIR)/doxygen ; \ + fi + $(Verb) $(DOXYGEN) $(PROJ_OBJ_DIR)/doxygen.cfg + $(Echo) Packaging doxygen documentation + $(Verb) $(RM) -rf $@ $(PROJ_OBJ_DIR)/doxygen.tar + $(Verb) $(TAR) cf $(PROJ_OBJ_DIR)/doxygen.tar doxygen + $(Verb) $(GZIP) $(PROJ_OBJ_DIR)/doxygen.tar + $(Verb) $(CP) $(PROJ_OBJ_DIR)/doxygen.tar.gz $(PROJ_OBJ_DIR)/doxygen/html/ + + userloc: $(LLVM_SRC_ROOT)/docs/userloc.html + + $(LLVM_SRC_ROOT)/docs/userloc.html: + $(Echo) Making User LOC Table + $(Verb) cd $(LLVM_SRC_ROOT) ; ./utils/userloc.pl -details -recurse \ + -html lib include tools runtime utils examples autoconf test > docs/userloc.html + Index: llvm-www/releases/1.8/docs/MakefileGuide.html diff -c /dev/null llvm-www/releases/1.8/docs/MakefileGuide.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/MakefileGuide.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,1010 ---- + + + + + LLVM Makefile Guide + + + + +
    LLVM Makefile Guide
    + +
      +
    1. Introduction
    2. +
    3. General Concepts +
        +
      1. Projects
      2. +
      3. Variable Values
      4. +
      5. Including Makefiles +
          +
        1. Makefile
        2. +
        3. Makefile.common
        4. +
        5. Makefile.config
        6. +
        7. Makefile.rules
        8. +
        +
      6. +
      7. Comments
      8. +
      +
    4. +
    5. Tutorial +
        +
      1. Libraries +
          +
        1. Bytecode Modules
        2. +
        +
      2. +
      3. Tools +
          +
        1. JIT Tools
        2. +
        +
      4. +
      5. Projects
      6. +
      +
    6. +
    7. Targets Supported +
        +
      1. all
      2. +
      3. all-local
      4. +
      5. check
      6. +
      7. check-local
      8. +
      9. clean
      10. +
      11. clean-local
      12. +
      13. dist
      14. +
      15. dist-check
      16. +
      17. dist-clean
      18. +
      19. install
      20. +
      21. preconditions
      22. +
      23. printvars
      24. +
      25. reconfigure
      26. +
      27. spotless
      28. +
      29. tags
      30. +
      31. uninstall
      32. +
      +
    8. +
    9. Using Variables +
        +
      1. Control Variables
      2. +
      3. Override Variables
      4. +
      5. Readable Variables
      6. +
      7. Internal Variables
      8. +
      +
    10. +
    + +
    +

    Written by Reid Spencer

    +
    + + + + + +
    +

    This document provides usage information about the LLVM makefile + system. While loosely patterned after the BSD makefile system, LLVM has taken + a departure from BSD in order to implement additional features needed by LLVM. + Although makefile systems such as automake were attempted at one point, it + has become clear that the features needed by LLVM and the Makefile norm are + too great to use a more limited tool. Consequently, LLVM requires simply GNU + Make 3.79, a widely portable makefile processor. LLVM unabashedly makes heavy + use of the features of GNU Make so the dependency on GNU Make is firm. If + you're not familiar with make, it is recommended that you read the + GNU Makefile + Manual.

    +

    While this document is rightly part of the + LLVM Programmer's Manual, it is treated + separately here because of the volume of content and because it is often an + early source of bewilderment for new developers.

    +
    + + + + + +
    +

    The LLVM Makefile System is the component of LLVM that is responsible for + building the software, testing it, generating distributions, checking those + distributions, installing and uninstalling, etc. It consists of a several + files throughout the source tree. These files and other general concepts are + described in this section.

    +
    + + + +
    +

    The LLVM Makefile System is quite generous. It not only builds its own + software, but it can build yours too. Built into the system is knowledge of + the llvm/projects directory. Any directory under projects + that has both a configure script and a Makefile is assumed + to be a project that uses the LLVM Makefile system. Building software that + uses LLVM does not require the LLVM Makefile System nor even placement in the + llvm/projects directory. However, doing so will allow your project + to get up and running quickly by utilizing the built-in features that are used + to compile LLVM. LLVM compiles itself using the same features of the makefile + system as used for projects.

    +

    For complete details on setting up your projects configuration, simply + mimic the llvm/projects/sample project or for further details, + consult the Projects.html page.

    +
    + + + +
    +

    To use the makefile system, you simply create a file named + Makefile in your directory and declare values for certain variables. + The variables and values that you select determine what the makefile system + will do. These variables enable rules and processing in the makefile system + that automatically Do The Right Thing™. +

    + + + +
    +

    Setting variables alone is not enough. You must include into your Makefile + additional files that provide the rules of the LLVM Makefile system. The + various files involved are described in the sections that follow.

    +
    + + + +
    +

    Each directory to participate in the build needs to have a file named + Makefile. This is the file first read by make. It has three + sections:

    +
      +
    1. Settable Variables - Required that must be set + first.
    2. +
    3. include $(LEVEL)/Makefile.common + - include the LLVM Makefile system. +
    4. Override Variables - Override variables set by + the LLVM Makefile system. +
    +
    + + + +
    +

    Every project must have a Makefile.common file at its top source + directory. This file serves three purposes:

    +
      +
    1. It includes the project's configuration makefile to obtain values + determined by the configure script. This is done by including the + $(LEVEL)/Makefile.config file.
    2. +
    3. It specifies any other (static) values that are needed throughout the + project. Only values that are used in all or a large proportion of the + project's directories should be placed here.
    4. +
    5. It includes the standard rules for the LLVM Makefile system, + $(LLVM_SRC_ROOT)/Makefile.rules. + This file is the "guts" of the LLVM Makefile system.
    6. +
    +
    + + + +
    +

    Every project must have a Makefile.config at the top of its + build directory. This file is generated by the + configure script from the pattern provided by the + Makefile.config.in file located at the top of the project's + source directory. The contents of this file depend largely on what + configuration items the project uses, however most projects can get what they + need by just relying on LLVM's configuration found in + $(LLVM_OBJ_ROOT)/Makefile.config. +

    + + + +
    +

    This file, located at $(LLVM_SRC_ROOT)/Makefile.rules is the heart + of the LLVM Makefile System. It provides all the logic, dependencies, and + rules for building the targets supported by the system. What it does largely + depends on the values of make variables that + have been set before Makefile.rules is included. +

    + + + +
    +

    User Makefiles need not have comments in them unless the construction is + unusual or it does not strictly follow the rules and patterns of the LLVM + makefile system. Makefile comments are invoked with the pound (#) character. + The # character and any text following it, to the end of the line, are ignored + by make.

    +
    + + + + +
    +

    This section provides some examples of the different kinds of modules you + can build with the LLVM makefile system. In general, each directory you + provide will build a single object although that object may be composed of + additionally compiled components.

    +
    + + + +
    +

    Only a few variable definitions are needed to build a regular library. + Normally, the makefile system will build all the software into a single + libname.o (pre-linked) object. This means the library is not + searchable and that the distinction between compilation units has been + dissolved. Optionally, you can ask for a shared library (.so), archive library + (.a) or to not have the default (relinked) library built. For example:

    +
    
    +       LIBRARYNAME = mylib
    +       SHARED_LIBRARY = 1
    +       ARCHIVE_LIBRARY = 1
    +       DONT_BUILD_RELINKED = 1
    +   
    +

    says to build a library named "mylib" with both a shared library + (mylib.so) and an archive library (mylib.a) version but + not to build the relinked object (mylib.o). The contents of all the + libraries produced will be the same, they are just constructed differently. + Note that you normally do not need to specify the sources involved. The LLVM + Makefile system will infer the source files from the contents of the source + directory.

    +

    The LOADABLE_MODULE=1 directive can be used in conjunction with + SHARED_LIBRARY=1 to indicate that the resulting shared library should + be openable with the dlopen function and searchable with the + dlsym function (or your operating system's equivalents). While this + isn't strictly necessary on Linux and a few other platforms, it is required + on systems like HP-UX and Darwin. You should use LOADABLE_MODULE for + any shared library that you intend to be loaded into an tool via the + -load option. See the + WritingAnLLVMPass.html document + for an example of why you might want to do this. +

    + + + +
    +

    In some situations, it is desireable to build a single bytecode module from + a variety of sources, instead of an archive, shared library, or bytecode + library. Bytecode modules can be specified in addition to any of the other + types of libraries by defining the MODULE_NAME + variable. For example:

    +
    
    +       LIBRARYNAME = mylib
    +       BYTECODE_LIBRARY = 1
    +       MODULE_NAME = mymod
    +   
    +

    will build a module named mymod.bc from the sources in the + directory. This module will be an aggregation of all the bytecode modules + derived from the sources. The example will also build a bytecode archive + containing a bytecode module for each compiled source file. The difference is + subtle, but important depending on how the module or library is to be linked. +

    +
    + + + +
    +

    For building executable programs (tools), you must provide the name of the + tool and the names of the libraries you wish to link with the tool. For + example:

    +
    
    +       TOOLNAME = mytool
    +       USEDLIBS = mylib
    +       LLVMLIBS = LLVMSupport.a LLVMSystem.a
    +   
    +

    says that we are to build a tool name mytool and that it requires + three libraries: mylib, LLVMSupport.a and + LLVMSystem.a.

    +

    Note that two different variables are use to indicate which libraries are + linked: USEDLIBS and LLVMLIBS. This distinction is necessary + to support projects. LLVMLIBS refers to the LLVM libraries found in + the LLVM object directory. USEDLIBS refers to the libraries built by + your project. In the case of building LLVM tools, USEDLIBS and + LLVMLIBS can be used interchangeably since the "project" is LLVM + itself and USEDLIBS refers to the same place as LLVMLIBS. +

    +

    Also note that there are two different ways of specifying a library: with a + .a suffix and without. Without the suffix, the entry refers to the + re-linked (.o) file which will include all symbols of the library. + This is useful, for example, to include all passes from a library of passes. + If the .a suffix is used then the library is linked as a searchable + library (with the -l option). In this case, only the symbols that are + unresolved at that point will be resolved from the library, if they + exist. Other (unreferenced) symbols will not be included when the .a + syntax is used. Note that in order to use the .a suffix, the library + in question must have been built with the ARCHIVE_LIBRARY option set. +

    +
    + + + +
    +

    Many tools will want to use the JIT features of LLVM. However, getting the + right set of libraries to link with is tedious, platform specific, and error + prone. Additionally, the JIT has special linker switch options that it needs. + Consequently, to make it easier to build tools that use the JIT, you can + use a special value for the LLVMLIBS variable:

    +
    
    +       TOOLNAME = my_jit_tool
    +       USEDLIBS = mylib
    +       LLVMLIBS = JIT
    +   
    +

    Using a value of JIT for LLVMLIBS tells the makefile + system to construct a special value for LLVMLIBS that gives the program all + the LLVM libraries needed to run the JIT. Any additional libraries needed can + still be specified with USEDLIBS. To get a full understanding of how + this changes the linker command, it is recommended that you:

    +
    
    +       cd examples/Fibonacci
    +       make VERBOSE=1
    +   
    +

    By default, using LLVMLIBS=JIT will link in enough to support JIT + code generation for the architecture on which the tool is linked. If you need + additional target architectures linked in, you may specify them on the command + line or in your Makefile. For example:

    +
    
    +       ENABLE_X86_JIT=1
    +       ENABLE_SPARCV9_JIT=1
    +       ENALBE_PPC_JIT=1
    +   
    +

    will cause the tool to be able to generate code for all three platforms. +

    +
    + + + + + +
    +

    This section describes each of the targets that can be built using the LLVM + Makefile system. Any target can be invoked from any directory but not all are + applicable to a given directory (e.g. "check", "dist" and "install" will + always operate as if invoked from the top level directory).

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Target NameImplied TargetsTarget Description
    allCompile the software recursively. Default target. +
    all-localCompile the software in the local directory only. +
    checkChange to the test directory in a project and run the + test suite there. +
    check-localRun a local test suite. Generally this is only defined in the + Makefile of the project's test directory. +
    cleanRemove built objects recursively. +
    clean-localRemove built objects from the local directory only. +
    distallPrepare a source distribution tarball. +
    dist-checkallPrepare a source distribution tarball and check that it builds. +
    dist-cleancleanClean source distribution tarball temporary files. +
    installallCopy built objects to installation directory. +
    preconditionsallCheck to make sure configuration and makefiles are up to date. +
    printvarsallPrints variables defined by the makefile system (for debugging). +
    tagsMake C and C++ tags files for emacs and vi. +
    uninstallRemove built objects from installation directory. +
    +
    + + + +
    +

    When you invoke make with no arguments, you are implicitly + instructing it to seek the "all" target (goal). This target is used for + building the software recursively and will do different things in different + directories. For example, in a lib directory, the "all" target will + compile source files and generate libraries. But, in a tools + directory, it will link libraries and generate executables.

    +
    + + + +
    +

    This target is the same as all but it operates only on + the current directory instead of recursively.

    +
    + + + +
    +

    This target can be invoked from anywhere within a project's directories + but always invokes the check-local target + in the project's test directory, if it exists and has a + Makefile. A warning is produced otherwise. If + TESTSUITE is defined on the make + command line, it will be passed down to the invocation of + make check-local in the test directory. The intended usage + for this is to assist in running specific suites of tests. If + TESTSUITE is not set, the implementation of check-local + should run all normal tests. It is up to the project to define what + different values for TESTSUTE will do. See the + TestingGuide for further details.

    +
    + + + +
    +

    This target should be implemented by the Makefile in the project's + test directory. It is invoked by the check target elsewhere. + Each project is free to define the actions of check-local as + appropriate for that project. The LLVM project itself uses dejagnu to run a + suite of feature and regresson tests. Other projects may choose to use + dejagnu or any other testing mechanism.

    +
    + + + +
    +

    This target cleans the build directory, recursively removing all things + that the Makefile builds. The cleaning rules have been made guarded so they + shouldn't go awry (via rm -f $(UNSET_VARIABLE)/* which will attempt + to erase the entire directory structure.

    +
    + + + +
    +

    This target does the same thing as clean but only for the current + (local) directory.

    +
    + + + +
    +

    This target builds a distribution tarball. It first builds the entire + project using the all target and then tars up the necessary files and + compresses it. The generated tarball is sufficient for a casual source + distribution, but probably not for a release (see dist-check).

    +
    + + + +
    +

    This target does the same thing as the dist target but also checks + the distribution tarball. The check is made by unpacking the tarball to a new + directory, configuring it, building it, installing it, and then verifying that + the installation results are correct (by comparing to the original build). + This target can take a long time to run but should be done before a release + goes out to make sure that the distributed tarball can actually be built into + a working release.

    +
    + + + +
    +

    This is a special form of the clean clean target. It performs a + normal clean but also removes things pertaining to building the + distribution.

    +
    + + + +
    +

    This target finalizes shared objects and executables and copies all + libraries, headers, executables and documentation to the directory given + with the --prefix option to configure. When completed, + the prefix directory will have everything needed to use LLVM.

    +

    The LLVM makefiles can generate complete internal documentation + for all the classes by using doxygen. By default, this feature is + not enabled because it takes a long time and generates a massive + amount of data (>100MB). If you want this feature, you must configure LLVM + with the --enable-doxygen switch and ensure that a modern version of doxygen + (1.3.7 or later) is available in your PATH. You can download + doxygen from + + here. +

    + + + +
    +

    This utility target checks to see if the Makefile in the object + directory is older than the Makefile in the source directory and + copies it if so. It also reruns the configure script if that needs to + be done and rebuilds the Makefile.config file similarly. Users may + overload this target to ensure that sanity checks are run before any + building of targets as all the targets depend on preconditions.

    +
    + + + +
    +

    This utility target just causes the LLVM makefiles to print out some of + the makefile variables so that you can double check how things are set.

    +
    + + + +
    +

    This utility target will force a reconfigure of LLVM or your project. It + simply runs $(PROJ_OBJ_ROOT)/config.status --recheck to rerun the + configuration tests and rebuild the configured files. This isn't generally + useful as the makefiles will reconfigure themselves whenever its necessary. +

    +
    + + + +
    +

    This utility target, only available when $(PROJ_OBJ_ROOT) is not + the same as $(PROJ_SRC_ROOT), will completely clean the + $(PROJ_OBJ_ROOT) directory by removing its content entirely and + reconfiguring the directory. This returns the $(PROJ_OBJ_ROOT) + directory to a completely fresh state. All content in the directory except + configured files and top-level makefiles will be lost.

    +

    Use with caution.

    +
    + + + +
    +

    This target will generate a TAGS file in the top-level source + directory. It is meant for use with emacs, XEmacs, or ViM. The TAGS file + provides an index of symbol definitions so that the editor can jump you to the + definition quickly.

    +
    + + + +
    +

    This target is the opposite of the install target. It removes the + header, library and executable files from the installation directories. Note + that the directories themselves are not removed because it is not guaranteed + that LLVM is the only thing installing there (e.g. --prefix=/usr).

    +
    + + + + +
    +

    Variables are used to tell the LLVM Makefile System what to do and to + obtain information from it. Variables are also used internally by the LLVM + Makefile System. Variable names that contain only the upper case alphabetic + letters and underscore are intended for use by the end user. All other + variables are internal to the LLVM Makefile System and should not be relied + upon nor modified. The sections below describe how to use the LLVM Makefile + variables.

    +
    + + + +
    +

    Variables listed in the table below should be set before the + inclusion of $(LEVEL)/Makefile.common. + These variables provide input to the LLVM make system that tell it what to do + for the current directory.

    +
    +
    BUILD_ARCHIVE
    +
    If set to any value, causes an archive (.a) library to be built.
    +
    BUILT_SOURCES
    +
    Specifies a set of source files that are generated from other source + files. These sources will be built before any other target processing to + ensure they are present.
    +
    BYTECODE_LIBRARY
    +
    If set to any value, causes a bytecode library (.bc) to be built.
    +
    CONFIG_FILES
    +
    Specifies a set of configuration files to be installed.
    +
    DIRS
    +
    Specifies a set of directories, usually children of the current + directory, that should also be made using the same goal. These directories + will be built serially.
    +
    DISABLE_AUTO_DEPENDENCIES
    +
    If set to any value, causes the makefiles to not automatically + generate dependencies when running the compiler. Use of this feature is + discouraged and it may be removed at a later date.
    +
    DONT_BUILD_RELINKED
    +
    If set to any value, causes a relinked library (.o) not to be built. By + default, libraries are built as re-linked since most LLVM libraries are + needed in their entirety and re-linked libraries will be linked more quickly + than equivalent archive libraries.
    +
    ENABLE_OPTIMIZED
    +
    If set to any value, causes the build to generate optimized objects, + libraries and executables. This alters the flags specified to the compilers + and linkers. Generally debugging won't be a fun experience with an optimized + build.
    +
    ENABLE_PROFILING
    +
    If set to any value, causes the build to generate both optimized and + profiled objects, libraries and executables. This alters the flags specified + to the compilers and linkers to ensure that profile data can be collected + from the tools built. Use the gprof tool to analyze the output from + the profiled tools (gmon.out).
    +
    DISABLE_ASSERTIONS
    +
    If set to any value, causes the build to disable assertions, even if + building a release or profile build. This will exclude all assertion check + code from the build. LLVM will execute faster, but with little help when + things go wrong.
    +
    EXPERIMENTAL_DIRS
    +
    Specify a set of directories that should be built, but if they fail, it + should not cause the build to fail. Note that this should only be used + temporarily while code is being written.
    +
    EXPORTED_SYMBOL_FILE
    +
    Specifies the name of a single file that contains a list of the + symbols to be exported by the linker. One symbol per line.
    +
    EXPORTED_SYMBOL_LIST
    +
    Specifies a set of symbols to be exported by the linker.
    +
    EXTRA_DIST
    +
    Specifies additional files that should be distributed with LLVM. All + source files, all built sources, all Makefiles, and most documentation files + will be automatically distributed. Use this variable to distribute any + files that are not automatically distributed.
    +
    KEEP_SYMBOLS
    +
    If set to any value, specifies that when linking executables the + makefiles should retain debug symbols in the executable. Normally, symbols + are stripped from the executable.
    +
    LEVEL(required)
    +
    Specify the level of nesting from the top level. This variable must be + set in each makefile as it is used to find the top level and thus the other + makefiles.
    +
    LIBRARYNAME
    +
    Specify the name of the library to be built. (Required For + Libraries)
    +
    LINK_LIBS_IN_SHARED
    +
    By default, shared library linking will ignore any libraries specified + with the LLVMLIBS or USEDLIBS. + This prevents shared libs from including things that will be in the LLVM + tool the shared library will be loaded into. However, sometimes it is useful + to link certain libraries into your shared library and this option enables + that feature.
    +
    LLVMLIBS
    +
    Specifies the set of libraries from the LLVM $(ObjDir) that will be + linked into the tool or library.
    +
    LOADABLE_MODULE
    +
    If set to any value, causes the shared library being built to also be + a loadable module. Loadable modules can be opened with the dlopen() function + and searched with dlsym (or the operating system's equivalent). Note that + setting this variable without also setting SHARED_LIBRARY will have + no effect.
    +
    MODULE_NAME
    +
    Specifies the name of a bytecode module to be created. A bytecode + module can be specified in conjunction with other kinds of library builds + or by itself. It constructs from the sources a single linked bytecode + file.
    +
    OPTIONAL_DIRS
    +
    Specify a set of directories that may be built, if they exist, but its + not an error for them not to exist.
    +
    PARALLEL_DIRS
    +
    Specify a set of directories to build recursively and in parallel if + the -j option was used with make.
    +
    SHARED_LIBRARY
    +
    If set to any value, causes a shared library (.so) to be built in + addition to any other kinds of libraries. Note that this option will cause + all source files to be built twice: once with options for position + independent code and once without. Use it only where you really need a + shared library.
    +
    SOURCES(optional)
    +
    Specifies the list of source files in the current directory to be + built. Source files of any type may be specified (programs, documentation, + config files, etc.). If not specified, the makefile system will infer the + set of source files from the files present in the current directory.
    +
    SUFFIXES
    +
    Specifies a set of filename suffixes that occur in suffix match rules. + Only set this if your local Makefile specifies additional suffix + match rules.
    +
    TARGET
    +
    Specifies the name of the LLVM code generation target that the + current directory builds. Setting this variable enables additional rules to + build .inc files from .td files.
    +
    TESTSUITE
    +
    Specifies the directory of tests to run in llvm/test.
    +
    TOOLNAME
    +
    Specifies the name of the tool that the current directory should + build.
    +
    TOOL_VERBOSE
    +
    Implies VERBOSE and also tells each tool invoked to be verbose. This is + handy when you're trying to see the sub-tools invoked by each tool invoked + by the makefile. For example, this will pass -v to the GCC + compilers which causes it to print out the command lines it uses to invoke + sub-tools (compiler, assembler, linker).
    +
    USEDLIBS
    +
    Specifies the list of project libraries that will be linked into the + tool or library.
    +
    VERBOSE
    +
    Tells the Makefile system to produce detailed output of what it is doing + instead of just summary comments. This will generate a LOT of output.
    +
    +
    + + + +
    +

    Override variables can be used to override the default + values provided by the LLVM makefile system. These variables can be set in + several ways:

    +
      +
    • In the environment (e.g. setenv, export) -- not recommended.
    • +
    • On the make command line -- recommended.
    • +
    • On the configure command line
    • +
    • In the Makefile (only after the inclusion of $(LEVEL)/Makefile.common).
    • +
    +

    The override variables are given below:

    +
    +
    AR (defaulted)
    +
    Specifies the path to the ar tool.
    +
    BISON(configured)
    +
    Specifies the path to the bison tool.
    +
    PROJ_OBJ_DIR
    +
    The directory into which the products of build rules will be placed. + This might be the same as + PROJ_SRC_DIR but typically is + not.
    +
    PROJ_SRC_DIR
    +
    The directory which contains the source files to be built.
    +
    BZIP2(configured)
    +
    The path to the bzip2 tool.
    +
    CC(configured)
    +
    The path to the 'C' compiler.
    +
    CFLAGS
    +
    Additional flags to be passed to the 'C' compiler.
    +
    CXX
    +
    Specifies the path to the C++ compiler.
    +
    CXXFLAGS
    +
    Additional flags to be passed to the C++ compiler.
    +
    DATE(configured)
    +
    Specifies the path to the date program or any program that can + generate the current date and time on its standard output
    +
    DOT(configured)
    +
    Specifies the path to the dot tool or false if there + isn't one.
    +
    ECHO(configured)
    +
    Specifies the path to the echo tool for printing output.
    +
    ETAGS(configured)
    +
    Specifies the path to the etags tool.
    +
    ETAGSFLAGS(configured) +
    +
    Provides flags to be passed to the etags tool.
    +
    EXEEXT(configured)
    +
    Provides the extension to be used on executables built by the makefiles. + The value may be empty on platforms that do not use file extensions for + executables (e.g. Unix).
    +
    FLEX(configured)
    +
    Specifies the path to the flex tool.
    +
    GCCLD(defaulted)
    +
    Specifies the path to the gccld tool.
    +
    INSTALL(configured)
    +
    Specifies the path to the install tool.
    +
    LDFLAGS(configured)
    +
    Allows users to specify additional flags to pass to the linker.
    +
    LIBS(configured)
    +
    The list of libraries that should be linked with each tool.
    +
    LIBTOOL(configured)
    +
    Specifies the path to the libtool tool. This tool is renamed + mklib by the configure script and always located in the +
    LLVMAS(defaulted)
    +
    Specifies the path to the llvm-as tool.
    +
    LLVMGCC(defaulted)
    +
    Specifies the path to the LLVM version of the GCC 'C' Compiler
    +
    LLVMGXX(defaulted)
    +
    Specifies the path to the LLVM version of the GCC C++ Compiler
    +
    LLVM_OBJ_ROOT(configured) +
    +
    Specifies the top directory into which the output of the build is + placed.
    +
    LLVM_SRC_ROOT(configured) +
    +
    Specifies the top directory in which the sources are found.
    +
    LLVM_TARBALL_NAME + (configured)
    +
    Specifies the name of the distribution tarball to create. This is + configured from the name of the project and its version number.
    +
    MKDIR(defaulted)
    +
    Specifies the path to the mkdir tool that creates + directories.
    +
    PLATFORMSTRIPOPTS
    +
    The options to provide to the linker to specify that a stripped (no + symbols) executable should be built.
    +
    RANLIB(defaulted)
    +
    Specifies the path to the ranlib tool.
    +
    RM(defaulted)
    +
    Specifies the path to the rm tool.
    +
    SED(defaulted)
    +
    Specifies the path to the sed tool.
    +
    SHLIBEXT(configured)
    +
    Provides the filename extension to use for shared libraries.
    +
    TBLGEN(defaulted)
    +
    Specifies the path to the tblgen tool.
    +
    TAR(defaulted)
    +
    Specifies the path to the tar tool.
    +
    ZIP(defaulted)
    +
    Specifies the path to the zip tool.
    +
    +
    + + + +
    +

    Variables listed in the table below can be used by the user's Makefile but + should not be changed. Changing the value will generally cause the build to go + wrong, so don't do it.

    +
    +
    bindir
    +
    The directory into which executables will ultimately be installed. This + value is derived from the --prefix option given to + configure.
    +
    BuildMode
    +
    The name of the type of build being performed: Debug, Release, or + Profile
    +
    bytecode_libdir
    +
    The directory into which bytecode libraries will ultimately be + installed. This value is derived from the --prefix option given to + configure.
    +
    ConfigureScriptFLAGS
    +
    Additional flags given to the configure script when + reconfiguring.
    +
    DistDir
    +
    The current directory for which a distribution copy is being + made.
    +
    Echo
    +
    The LLVM Makefile System output command. This provides the + llvm[n] prefix and starts with @ so the command itself is not + printed by make.
    +
    EchoCmd
    +
    Same as Echo but without the leading @. +
    +
    includedir
    +
    The directory into which include files will ultimately be installed. + This value is derived from the --prefix option given to + configure.
    +
    libdir
    +
    The directory into which native libraries will ultimately be installed. + This value is derived from the --prefix option given to + configure.
    +
    LibDir
    +
    The configuration specific directory into which libraries are placed + before installation.
    +
    MakefileConfig
    +
    Full path of the Makefile.config file.
    +
    MakefileConfigIn
    +
    Full path of the Makefile.config.in file.
    +
    ObjDir
    +
    The configuration and directory specific directory where build objects + (compilation results) are placed.
    +
    SubDirs
    +
    The complete list of sub-directories of the current directory as + specified by other variables.
    +
    Sources
    +
    The complete list of source files.
    +
    sysconfdir
    +
    The directory into which configuration files will ultimately be + installed. This value is derived from the --prefix option given to + configure.
    +
    ToolDir
    +
    The configuration specific directory into which executables are placed + before they are installed.
    +
    TopDistDir
    +
    The top most directory into which the distribution files are copied. +
    +
    Verb
    +
    Use this as the first thing on your build script lines to enable or + disable verbose mode. It expands to either an @ (quiet mode) or nothing + (verbose mode).
    +
    +
    + + + +
    +

    Variables listed below are used by the LLVM Makefile System + and considered internal. You should not use these variables under any + circumstances.

    +

    + Archive + AR.Flags + BaseNameSources + BCCompile.C + BCCompile.CXX + BCLinkLib + C.Flags + Compile.C + CompileCommonOpts + Compile.CXX + ConfigStatusScript + ConfigureScript + CPP.Flags + CPP.Flags + CXX.Flags + DependFiles + DestArchiveLib + DestBytecodeLib + DestModule + DestRelinkedLib + DestSharedLib + DestTool + DistAlways + DistCheckDir + DistCheckTop + DistFiles + DistName + DistOther + DistSources + DistSubDirs + DistTarBZ2 + DistTarGZip + DistZip + ExtraLibs + FakeSources + INCFiles + InternalTargets + LD.Flags + LexFiles + LexOutput + LibName.A + LibName.BC + LibName.LA + LibName.O + LibTool.Flags + Link + LinkModule + LLVMLibDir + LLVMLibsOptions + LLVMLibsPaths + LLVMToolDir + LLVMUsedLibs + LocalTargets + LTCompile.C + LTCompile.CXX + LTInstall + Module + ObjectsBC + ObjectsLO + ObjectsO + ObjMakefiles + ParallelTargets + PreConditions + ProjLibsOptions + ProjLibsPaths + ProjUsedLibs + Ranlib + RecursiveTargets + Relink + SrcMakefiles + Strip + StripWarnMsg + TableGen + TDFiles + ToolBuildPath + TopLevelTargets + UserTargets + YaccFiles + YaccOutput +

    +
    + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Reid Spencer
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + Index: llvm-www/releases/1.8/docs/ProgrammersManual.html diff -c /dev/null llvm-www/releases/1.8/docs/ProgrammersManual.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/ProgrammersManual.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,2288 ---- + + + + LLVM Programmer's Manual + + + + +
    + LLVM Programmer's Manual +
    + +
      +
    1. Introduction
    2. +
    3. General Information + +
    4. +
    5. Important and useful LLVM APIs + +
    6. +
    7. Helpful Hints for Common Operations + +
    8. + +
    9. Advanced Topics +
    10. + +
    11. The Core LLVM Class Hierarchy Reference + +
    12. +
    + + + + + + + +
    + +

    This document is meant to highlight some of the important classes and + interfaces available in the LLVM source-base. This manual is not + intended to explain what LLVM is, how it works, and what LLVM code looks + like. It assumes that you know the basics of LLVM and are interested + in writing transformations or otherwise analyzing or manipulating the + code.

    + +

    This document should get you oriented so that you can find your + way in the continuously growing source code that makes up the LLVM + infrastructure. Note that this manual is not intended to serve as a + replacement for reading the source code, so if you think there should be + a method in one of these classes to do something, but it's not listed, + check the source. Links to the doxygen sources + are provided to make this as easy as possible.

    + +

    The first section of this document describes general information that is + useful to know when working in the LLVM infrastructure, and the second describes + the Core LLVM classes. In the future this manual will be extended with + information describing how to use extension libraries, such as dominator + information, CFG traversal routines, and useful utilities like the InstVisitor template.

    + +
    + + + + + +
    + +

    This section contains general information that is useful if you are working + in the LLVM source-base, but that isn't specific to any particular API.

    + +
    + + + + +
    + +

    LLVM makes heavy use of the C++ Standard Template Library (STL), + perhaps much more than you are used to, or have seen before. Because of + this, you might want to do a little background reading in the + techniques used and capabilities of the library. There are many good + pages that discuss the STL, and several books on the subject that you + can get, so it will not be discussed in this document.

    + +

    Here are some useful links:

    + +
      + +
    1. Dinkumware C++ Library + reference - an excellent reference for the STL and other parts of the + standard C++ library.
    2. + +
    3. C++ In a Nutshell - This is an + O'Reilly book in the making. It has a decent + Standard Library + Reference that rivals Dinkumware's, and is unfortunately no longer free since the book has been + published.
    4. + +
    5. C++ Frequently Asked + Questions
    6. + +
    7. SGI's STL Programmer's Guide - + Contains a useful Introduction to the + STL.
    8. + +
    9. Bjarne Stroustrup's C++ + Page
    10. + +
    11. + Bruce Eckel's Thinking in C++, 2nd ed. Volume 2 Revision 4.0 (even better, get + the book).
    12. + +
    + +

    You are also encouraged to take a look at the LLVM Coding Standards guide which focuses on how + to write maintainable code more than where to put your curly braces.

    + +
    + + + + + + + + + + +
    + +

    Here we highlight some LLVM APIs that are generally useful and good to + know about when writing transformations.

    + +
    + + + + +
    + +

    The LLVM source-base makes extensive use of a custom form of RTTI. + These templates have many similarities to the C++ dynamic_cast<> + operator, but they don't have some drawbacks (primarily stemming from + the fact that dynamic_cast<> only works on classes that + have a v-table). Because they are used so often, you must know what they + do and how they work. All of these templates are defined in the llvm/Support/Casting.h + file (note that you very rarely have to include this file directly).

    + +
    +
    isa<>:
    + +
    The isa<> operator works exactly like the Java + "instanceof" operator. It returns true or false depending on whether + a reference or pointer points to an instance of the specified class. This can + be very useful for constraint checking of various sorts (example below).
    + +
    cast<>:
    + +
    The cast<> operator is a "checked cast" operation. It + converts a pointer or reference from a base class to a derived cast, causing + an assertion failure if it is not really an instance of the right type. This + should be used in cases where you have some information that makes you believe + that something is of the right type. An example of the isa<> + and cast<> template is: + +
    +   static bool isLoopInvariant(const Value *V, const Loop *L) {
    +     if (isa<Constant>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
    +       return true;
    + 
    +     // Otherwise, it must be an instruction...
    +     return !L->contains(cast<Instruction>(V)->getParent());
    +   }
    +   
    + +

    Note that you should not use an isa<> test followed + by a cast<>, for that use the dyn_cast<> + operator.

    + +
    + +
    dyn_cast<>:
    + +
    The dyn_cast<> operator is a "checking cast" operation. It + checks to see if the operand is of the specified type, and if so, returns a + pointer to it (this operator does not work with references). If the operand is + not of the correct type, a null pointer is returned. Thus, this works very + much like the dynamic_cast<> operator in C++, and should be + used in the same circumstances. Typically, the dyn_cast<> + operator is used in an if statement or some other flow control + statement like this: + +
    +      if (AllocationInst *AI = dyn_cast<AllocationInst>(Val)) {
    +        ...
    +      }
    +   
    + +

    This form of the if statement effectively combines together a call + to isa<> and a call to cast<> into one + statement, which is very convenient.

    + +

    Note that the dyn_cast<> operator, like C++'s + dynamic_cast<> or Java's instanceof operator, can be + abused. In particular, you should not use big chained if/then/else + blocks to check for lots of different variants of classes. If you find + yourself wanting to do this, it is much cleaner and more efficient to use the + InstVisitor class to dispatch over the instruction type directly.

    + +
    + +
    cast_or_null<>:
    + +
    The cast_or_null<> operator works just like the + cast<> operator, except that it allows for a null pointer as an + argument (which it then propagates). This can sometimes be useful, allowing + you to combine several null checks into one.
    + +
    dyn_cast_or_null<>:
    + +
    The dyn_cast_or_null<> operator works just like the + dyn_cast<> operator, except that it allows for a null pointer + as an argument (which it then propagates). This can sometimes be useful, + allowing you to combine several null checks into one.
    + +
    + +

    These five templates can be used with any classes, whether they have a + v-table or not. To add support for these templates, you simply need to add + classof static methods to the class you are interested casting + to. Describing this is currently outside the scope of this document, but there + are lots of examples in the LLVM source base.

    + +
    + + + + +
    + +

    Often when working on your pass you will put a bunch of debugging printouts + and other code into your pass. After you get it working, you want to remove + it... but you may need it again in the future (to work out new bugs that you run + across).

    + +

    Naturally, because of this, you don't want to delete the debug printouts, + but you don't want them to always be noisy. A standard compromise is to comment + them out, allowing you to enable them if you need them in the future.

    + +

    The "llvm/Support/Debug.h" + file provides a macro named DEBUG() that is a much nicer solution to + this problem. Basically, you can put arbitrary code into the argument of the + DEBUG macro, and it is only executed if 'opt' (or any other + tool) is run with the '-debug' command line argument:

    + +
         ... 
    DEBUG(std::cerr << "I am here!\n");
    ...
    + +

    Then you can run your pass like this:

    + +
      $ opt < a.bc > /dev/null -mypass
    <no output>
    $ opt < a.bc > /dev/null -mypass -debug
    I am here!
    $
    + +

    Using the DEBUG() macro instead of a home-brewed solution allows you + to not have to create "yet another" command line option for the debug output for + your pass. Note that DEBUG() macros are disabled for optimized builds, + so they do not cause a performance impact at all (for the same reason, they + should also not contain side-effects!).

    + +

    One additional nice thing about the DEBUG() macro is that you can + enable or disable it directly in gdb. Just use "set DebugFlag=0" or + "set DebugFlag=1" from the gdb if the program is running. If the + program hasn't been started yet, you can always just run it with + -debug.

    + +
    + + + + +
    + +

    Sometimes you may find yourself in a situation where enabling -debug + just turns on too much information (such as when working on the code + generator). If you want to enable debug information with more fine-grained + control, you define the DEBUG_TYPE macro and the -debug only + option as follows:

    + +
         ...
    DEBUG(std::cerr << "No debug type\n");
    #undef DEBUG_TYPE
    #define DEBUG_TYPE "foo"
    DEBUG(std::cerr << "'foo' debug type\n");
    #undef DEBUG_TYPE
    #define DEBUG_TYPE "bar"
    DEBUG(std::cerr << "'bar' debug type\n");
    #undef DEBUG_TYPE
    #define DEBUG_TYPE ""
    DEBUG(std::cerr << "No debug type (2)\n");
    ...
    + +

    Then you can run your pass like this:

    + +
      $ opt < a.bc > /dev/null -mypass
    <no output>
    $ opt < a.bc > /dev/null -mypass -debug
    No debug type
    'foo' debug type
    'bar' debug type
    No debug type (2)
    $ opt < a.bc > /dev/null -mypass -debug-only=foo
    'foo' debug type
    $ opt < a.bc > /dev/null -mypass -debug-only=bar
    'bar' debug type
    $
    + +

    Of course, in practice, you should only set DEBUG_TYPE at the top of + a file, to specify the debug type for the entire module (if you do this before + you #include "llvm/Support/Debug.h", you don't have to insert the ugly + #undef's). Also, you should use names more meaningful than "foo" and + "bar", because there is no system in place to ensure that names do not + conflict. If two different modules use the same string, they will all be turned + on when the name is specified. This allows, for example, all debug information + for instruction scheduling to be enabled with -debug-type=InstrSched, + even if the source lives in multiple files.

    + +
    + + + + +
    + +

    The "llvm/ADT/Statistic.h" file + provides a template named Statistic that is used as a unified way to + keep track of what the LLVM compiler is doing and how effective various + optimizations are. It is useful to see what optimizations are contributing to + making a particular program run faster.

    + +

    Often you may run your pass on some big program, and you're interested to see + how many times it makes a certain transformation. Although you can do this with + hand inspection, or some ad-hoc method, this is a real pain and not very useful + for big programs. Using the Statistic template makes it very easy to + keep track of this information, and the calculated information is presented in a + uniform manner with the rest of the passes being executed.

    + +

    There are many examples of Statistic uses, but the basics of using + it are as follows:

    + +
      +
    1. Define your statistic like this: +
      static Statistic<> NumXForms("mypassname", "The # of times I did stuff");
      + +

      The Statistic template can emulate just about any data-type, + but if you do not specify a template argument, it defaults to acting like + an unsigned int counter (this is usually what you want).

    2. + +
    3. Whenever you make a transformation, bump the counter: +
         ++NumXForms;   // I did stuff
      +
    4. +
    + +

    That's all you have to do. To get 'opt' to print out the + statistics gathered, use the '-stats' option:

    + +
       $ opt -stats -mypassname < program.bc > /dev/null
    ... statistic output ...
    + +

    When running gccas on a C file from the SPEC benchmark + suite, it gives a report that looks like this:

    + +
       7646 bytecodewriter  - Number of normal instructions
    725 bytecodewriter - Number of oversized instructions
    129996 bytecodewriter - Number of bytecode bytes written
    2817 raise - Number of insts DCEd or constprop'd
    3213 raise - Number of cast-of-self removed
    5046 raise - Number of expression trees converted
    75 raise - Number of other getelementptr's formed
    138 raise - Number of load/store peepholes
    42 deadtypeelim - Number of unused typenames removed from symtab
    392 funcresolve - Number of varargs functions resolved
    27 globaldce - Number of global variables removed
    2 adce - Number of basic blocks removed
    134 cee - Number of branches revectored
    49 cee - Number of setcc instruction eliminated
    532 gcse - Number of loads removed
    2919 gcse - Number! of instructions removed
    86 indvars - Number of canonical indvars added
    87 indvars - Number of aux indvars removed
    25 instcombine - Number of dead inst eliminate
    434 instcombine - Number of insts combined
    248 licm - Number of load insts hoisted
    1298 licm - Number of insts hoisted to a loop pre-header
    3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
    75 mem2reg - Number of alloca's promoted
    1444 cfgsimplify - Number of blocks simplified
    + +

    Obviously, with so many optimizations, having a unified framework for this + stuff is very nice. Making your pass fit well into the framework makes it more + maintainable and useful.

    + +
    + + + + +
    + +

    Several of the important data structures in LLVM are graphs: for example + CFGs made out of LLVM BasicBlocks, CFGs made out of + LLVM MachineBasicBlocks, and + Instruction Selection + DAGs. In many cases, while debugging various parts of the compiler, it is + nice to instantly visualize these graphs.

    + +

    LLVM provides several callbacks that are available in a debug build to do + exactly that. If you call the Function::viewCFG() method, for example, + the current LLVM tool will pop up a window containing the CFG for the function + where each basic block is a node in the graph, and each node contains the + instructions in the block. Similarly, there also exists + Function::viewCFGOnly() (does not include the instructions), the + MachineFunction::viewCFG() and MachineFunction::viewCFGOnly(), + and the SelectionDAG::viewGraph() methods. Within GDB, for example, + you can usually use something like "call DAG.viewGraph()" to pop + up a window. Alternatively, you can sprinkle calls to these functions in your + code in places you want to debug.

    + +

    Getting this to work requires a small amount of configuration. On Unix + systems with X11, install the graphviz + toolkit, and make sure 'dot' and 'gv' are in your path. If you are running on + Mac OS/X, download and install the Mac OS/X Graphviz program, and add + /Applications/Graphviz.app/Contents/MacOS/ (or whereever you install + it) to your path. Once in your system and path are set up, rerun the LLVM + configure script and rebuild LLVM to enable this functionality.

    + +
    + + + + + + +
    + +

    This section describes how to perform some very simple transformations of + LLVM code. This is meant to give examples of common idioms used, showing the + practical side of LLVM transformations.

    Because this is a "how-to" section, + you should also read about the main classes that you will be working with. The + Core LLVM Class Hierarchy Reference contains details + and descriptions of the main classes that you should know about.

    + +
    + + + + + +
    + +

    The LLVM compiler infrastructure have many different data structures that may + be traversed. Following the example of the C++ standard template library, the + techniques used to traverse these various data structures are all basically the + same. For a enumerable sequence of values, the XXXbegin() function (or + method) returns an iterator to the start of the sequence, the XXXend() + function returns an iterator pointing to one past the last valid element of the + sequence, and there is some XXXiterator data type that is common + between the two operations.

    + +

    Because the pattern for iteration is common across many different aspects of + the program representation, the standard template library algorithms may be used + on them, and it is easier to remember how to iterate. First we show a few common + examples of the data structures that need to be traversed. Other data + structures are traversed in very similar ways.

    + +
    + + + + +
    + +

    It's quite common to have a Function instance that you'd like to + transform in some way; in particular, you'd like to manipulate its + BasicBlocks. To facilitate this, you'll need to iterate over all of + the BasicBlocks that constitute the Function. The following is + an example that prints the name of a BasicBlock and the number of + Instructions it contains:

    + +
      // func is a pointer to a Function instance
    for (Function::iterator i = func->begin(), e = func->end(); i != e; ++i) {

    // print out the name of the basic block if it has one, and then the
    // number of instructions that it contains

    std::cerr << "Basic block (name=" << i->getName() << ") has "
    << i->size() << " instructions.\n";
    }
    + +

    Note that i can be used as if it were a pointer for the purposes of + invoking member functions of the Instruction class. This is + because the indirection operator is overloaded for the iterator + classes. In the above code, the expression i->size() is + exactly equivalent to (*i).size() just like you'd expect.

    + +
    + + + + +
    + +

    Just like when dealing with BasicBlocks in Functions, it's + easy to iterate over the individual instructions that make up + BasicBlocks. Here's a code snippet that prints out each instruction in + a BasicBlock:

    + +
    +   // blk is a pointer to a BasicBlock instance
    +   for (BasicBlock::iterator i = blk->begin(), e = blk->end(); i != e; ++i)
    +      // the next statement works since operator<<(ostream&,...)
    +      // is overloaded for Instruction&
    +      std::cerr << *i << "\n";
    + 
    + +

    However, this isn't really the best way to print out the contents of a + BasicBlock! Since the ostream operators are overloaded for virtually + anything you'll care about, you could have just invoked the print routine on the + basic block itself: std::cerr << *blk << "\n";.

    + +
    + + + + +
    + +

    If you're finding that you commonly iterate over a Function's + BasicBlocks and then that BasicBlock's Instructions, + InstIterator should be used instead. You'll need to include llvm/Support/InstIterator.h, + and then instantiate InstIterators explicitly in your code. Here's a + small example that shows how to dump all instructions in a function to the standard error stream:

    + +

    #include "llvm/Support/InstIterator.h"
    ...
    // Suppose F is a ptr to a function
    for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
    std::cerr << *i << "\n";
    + Easy, isn't it? You can also use InstIterators to fill a + worklist with its initial contents. For example, if you wanted to + initialize a worklist to contain all instructions in a Function + F, all you would need to do is something like: +
    std::set<Instruction*> worklist;
    worklist.insert(inst_begin(F), inst_end(F));
    + +

    The STL set worklist would now contain all instructions in the + Function pointed to by F.

    + +
    + + + + +
    + +

    Sometimes, it'll be useful to grab a reference (or pointer) to a class + instance when all you've got at hand is an iterator. Well, extracting + a reference or a pointer from an iterator is very straight-forward. + Assuming that i is a BasicBlock::iterator and j + is a BasicBlock::const_iterator:

    + +
        Instruction& inst = *i;   // grab reference to instruction reference
    Instruction* pinst = &*i; // grab pointer to instruction reference
    const Instruction& inst = *j;
    + +

    However, the iterators you'll be working with in the LLVM framework are + special: they will automatically convert to a ptr-to-instance type whenever they + need to. Instead of dereferencing the iterator and then taking the address of + the result, you can simply assign the iterator to the proper pointer type and + you get the dereference and address-of operation as a result of the assignment + (behind the scenes, this is a result of overloading casting mechanisms). Thus + the last line of the last example,

    + +
    Instruction* pinst = &*i;
    + +

    is semantically equivalent to

    + +
    Instruction* pinst = i;
    + +

    It's also possible to turn a class pointer into the corresponding iterator, + and this is a constant time operation (very efficient). The following code + snippet illustrates use of the conversion constructors provided by LLVM + iterators. By using these, you can explicitly grab the iterator of something + without actually obtaining it via iteration over some structure:

    + +
    void printNextInstruction(Instruction* inst) {
    BasicBlock::iterator it(inst);
    ++it; // after this line, it refers to the instruction after *inst.
    if (it != inst->getParent()->end()) std::cerr << *it << "\n";
    }
    + +
    + + + + +
    + +

    Say that you're writing a FunctionPass and would like to count all the + locations in the entire module (that is, across every Function) where a + certain function (i.e., some Function*) is already in scope. As you'll + learn later, you may want to use an InstVisitor to accomplish this in a + much more straight-forward manner, but this example will allow us to explore how + you'd do it if you didn't have InstVisitor around. In pseudocode, this + is what we want to do:

    + +
    initialize callCounter to zero
    for each Function f in the Module
    for each BasicBlock b in f
    for each Instruction i in b
    if (i is a CallInst and calls the given function)
    increment callCounter
    + +

    And the actual code is (remember, since we're writing a + FunctionPass, our FunctionPass-derived class simply has to + override the runOnFunction method...):

    + +
    Function* targetFunc = ...;

    class OurFunctionPass : public FunctionPass {
    public:
    OurFunctionPass(): callCounter(0) { }

    virtual runOnFunction(Function& F) {
    for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {
    for (BasicBlock::iterator i = b->begin(); ie = b->end(); i != ie; ++i) {
    if (CallInst* callInst = dyn_cast<CallInst>(&*i)) {
    // we know we've encountered a call instruction, so we
    // need to determine if it's a call to the
    // function pointed to by m_func or not.

    if (callInst->getCalledFunction() == targetFunc)
    ++callCounter;
    }
    }
    }

    private:
    unsigned callCounter;
    };
    + +
    + + + + +
    + +

    You may have noticed that the previous example was a bit oversimplified in + that it did not deal with call sites generated by 'invoke' instructions. In + this, and in other situations, you may find that you want to treat + CallInsts and InvokeInsts the same way, even though their + most-specific common base class is Instruction, which includes lots of + less closely-related things. For these cases, LLVM provides a handy wrapper + class called CallSite. + It is essentially a wrapper around an Instruction pointer, with some + methods that provide functionality common to CallInsts and + InvokeInsts.

    + +

    This class has "value semantics": it should be passed by value, not by + reference and it should not be dynamically allocated or deallocated using + operator new or operator delete. It is efficiently copyable, + assignable and constructable, with costs equivalents to that of a bare pointer. + If you look at its definition, it has only a single pointer member.

    + +
    + + + + +
    + +

    Frequently, we might have an instance of the Value Class and we want to + determine which Users use the Value. The list of all + Users of a particular Value is called a def-use chain. + For example, let's say we have a Function* named F to a + particular function foo. Finding all of the instructions that + use foo is as simple as iterating over the def-use chain + of F:

    + +
    Function* F = ...;

    for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) {
    if (Instruction *Inst = dyn_cast<Instruction>(*i)) {
    std::cerr << "F is used in instruction:\n";
    std::cerr << *Inst << "\n";
    }
    }
    + +

    Alternately, it's common to have an instance of the User Class and need to know what + Values are used by it. The list of all Values used by a + User is known as a use-def chain. Instances of class + Instruction are common Users, so we might want to iterate over + all of the values that a particular instruction uses (that is, the operands of + the particular Instruction):

    + +
    Instruction* pi = ...;

    for (User::op_iterator i = pi->op_begin(), e = pi->op_end(); i != e; ++i) {
    Value* v = *i;
    ...
    }
    + + + +
    + + + + +
    + +

    There are some primitive transformation operations present in the LLVM + infrastructure that are worth knowing about. When performing + transformations, it's fairly common to manipulate the contents of basic + blocks. This section describes some of the common methods for doing so + and gives example code.

    + +
    + + + + +
    + +

    Instantiating Instructions

    + +

    Creation of Instructions is straight-forward: simply call the + constructor for the kind of instruction to instantiate and provide the necessary + parameters. For example, an AllocaInst only requires a + (const-ptr-to) Type. Thus:

    + +
    AllocaInst* ai = new AllocaInst(Type::IntTy);
    + +

    will create an AllocaInst instance that represents the allocation of + one integer in the current stack frame, at runtime. Each Instruction + subclass is likely to have varying default parameters which change the semantics + of the instruction, so refer to the doxygen documentation for the subclass of + Instruction that you're interested in instantiating.

    + +

    Naming values

    + +

    It is very useful to name the values of instructions when you're able to, as + this facilitates the debugging of your transformations. If you end up looking + at generated LLVM machine code, you definitely want to have logical names + associated with the results of instructions! By supplying a value for the + Name (default) parameter of the Instruction constructor, you + associate a logical name with the result of the instruction's execution at + runtime. For example, say that I'm writing a transformation that dynamically + allocates space for an integer on the stack, and that integer is going to be + used as some kind of index by some other code. To accomplish this, I place an + AllocaInst at the first point in the first BasicBlock of some + Function, and I'm intending to use it within the same + Function. I might do:

    + +
    AllocaInst* pa = new AllocaInst(Type::IntTy, 0, "indexLoc");
    + +

    where indexLoc is now the logical name of the instruction's + execution value, which is a pointer to an integer on the runtime stack.

    + +

    Inserting instructions

    + +

    There are essentially two ways to insert an Instruction + into an existing sequence of instructions that form a BasicBlock:

    + +
      +
    • Insertion into an explicit instruction list + +

      Given a BasicBlock* pb, an Instruction* pi within that + BasicBlock, and a newly-created instruction we wish to insert + before *pi, we do the following:

      + +
        BasicBlock *pb = ...;
      Instruction *pi = ...;
      Instruction *newInst = new Instruction(...);
      pb->getInstList().insert(pi, newInst); // inserts newInst before pi in pb
      + +

      Appending to the end of a BasicBlock is so common that + the Instruction class and Instruction-derived + classes provide constructors which take a pointer to a + BasicBlock to be appended to. For example code that + looked like:

      + +
        BasicBlock *pb = ...;
      Instruction *newInst = new Instruction(...);
      pb->getInstList().push_back(newInst); // appends newInst to pb
      + +

      becomes:

      + +
        BasicBlock *pb = ...;
      Instruction *newInst = new Instruction(..., pb);
      + +

      which is much cleaner, especially if you are creating + long instruction streams.

    • + +
    • Insertion into an implicit instruction list + +

      Instruction instances that are already in BasicBlocks + are implicitly associated with an existing instruction list: the instruction + list of the enclosing basic block. Thus, we could have accomplished the same + thing as the above code without being given a BasicBlock by doing: +

      + +
        Instruction *pi = ...;
      Instruction *newInst = new Instruction(...);
      pi->getParent()->getInstList().insert(pi, newInst);
      + +

      In fact, this sequence of steps occurs so frequently that the + Instruction class and Instruction-derived classes provide + constructors which take (as a default parameter) a pointer to an + Instruction which the newly-created Instruction should + precede. That is, Instruction constructors are capable of + inserting the newly-created instance into the BasicBlock of a + provided instruction, immediately before that instruction. Using an + Instruction constructor with a insertBefore (default) + parameter, the above code becomes:

      + +
      Instruction* pi = ...;
      Instruction* newInst = new Instruction(..., pi);
      + +

      which is much cleaner, especially if you're creating a lot of + instructions and adding them to BasicBlocks.

    • +
    + +
    + + + + +
    + +

    Deleting an instruction from an existing sequence of instructions that form a + BasicBlock is very straight-forward. First, + you must have a pointer to the instruction that you wish to delete. Second, you + need to obtain the pointer to that instruction's basic block. You use the + pointer to the basic block to get its list of instructions and then use the + erase function to remove your instruction. For example:

    + +
      Instruction *I = .. ;
    BasicBlock *BB = I->getParent();
    BB->getInstList().erase(I);
    + +
    + + + + +
    + +

    Replacing individual instructions

    + +

    Including "llvm/Transforms/Utils/BasicBlockUtils.h" + permits use of two very useful replace functions: ReplaceInstWithValue + and ReplaceInstWithInst.

    + +

    Deleting Instructions

    + +
      +
    • ReplaceInstWithValue + +

      This function replaces all uses (within a basic block) of a given + instruction with a value, and then removes the original instruction. The + following example illustrates the replacement of the result of a particular + AllocaInst that allocates memory for a single integer with a null + pointer to an integer.

      + +
      AllocaInst* instToReplace = ...;
      BasicBlock::iterator ii(instToReplace);
      ReplaceInstWithValue(instToReplace->getParent()->getInstList(), ii,
      Constant::getNullValue(PointerType::get(Type::IntTy)));
    • + +
    • ReplaceInstWithInst + +

      This function replaces a particular instruction with another + instruction. The following example illustrates the replacement of one + AllocaInst with another.

      + +
      AllocaInst* instToReplace = ...;
      BasicBlock::iterator ii(instToReplace);
      ReplaceInstWithInst(instToReplace->getParent()->getInstList(), ii,
      new AllocaInst(Type::IntTy, 0, "ptrToReplacedInt"));
    • +
    + +

    Replacing multiple uses of Users and Values

    + +

    You can use Value::replaceAllUsesWith and + User::replaceUsesOfWith to change more than one use at a time. See the + doxygen documentation for the Value Class + and User Class, respectively, for more + information.

    + + + +
    + + + + + +
    +

    + This section describes some of the advanced or obscure API's that most clients + do not need to be aware of. These API's tend manage the inner workings of the + LLVM system, and only need to be accessed in unusual circumstances. +

    +
    + + + + +
    + +

    + The LLVM type system has a very simple goal: allow clients to compare types for + structural equality with a simple pointer comparison (aka a shallow compare). + This goal makes clients much simpler and faster, and is used throughout the LLVM + system. +

    + +

    + Unfortunately achieving this goal is not a simple matter. In particular, + recursive types and late resolution of opaque types makes the situation very + difficult to handle. Fortunately, for the most part, our implementation makes + most clients able to be completely unaware of the nasty internal details. The + primary case where clients are exposed to the inner workings of it are when + building a recursive type. In addition to this case, the LLVM bytecode reader, + assembly parser, and linker also have to be aware of the inner workings of this + system. +

    + +

    + For our purposes below, we need three concepts. First, an "Opaque Type" is + exactly as defined in the language + reference. Second an "Abstract Type" is any type which includes an + opaque type as part of its type graph (for example "{ opaque, int }"). + Third, a concrete type is a type that is not an abstract type (e.g. "[ int, + float }"). +

    + +
    + + + + +
    + +

    + Because the most common question is "how do I build a recursive type with LLVM", + we answer it now and explain it as we go. Here we include enough to cause this + to be emitted to an output .ll file: +

    + +
    +    %mylist = type { %mylist*, int }
    + 
    + +

    + To build this, use the following LLVM APIs: +

    + +
    +   // Create the initial outer struct.
    +   PATypeHolder StructTy = OpaqueType::get();
    +   std::vector<const Type*> Elts;
    +   Elts.push_back(PointerType::get(StructTy));
    +   Elts.push_back(Type::IntTy);
    +   StructType *NewSTy = StructType::get(Elts);
    + 
    +   // At this point, NewSTy = "{ opaque*, int }". Tell VMCore that
    +   // the struct and the opaque type are actually the same.
    +   cast<OpaqueType>(StructTy.get())->refineAbstractTypeTo(NewSTy);
    + 
    +   // NewSTy is potentially invalidated, but StructTy (a PATypeHolder) is
    +   // kept up-to-date.
    +   NewSTy = cast<StructType>(StructTy.get());
    + 
    +   // Add a name for the type to the module symbol table (optional).
    +   MyModule->addTypeName("mylist", NewSTy);
    + 
    + +

    + This code shows the basic approach used to build recursive types: build a + non-recursive type using 'opaque', then use type unification to close the cycle. + The type unification step is performed by the refineAbstractTypeTo method, which is + described next. After that, we describe the PATypeHolder class. +

    + +
    + + + + +
    +

    + The refineAbstractTypeTo method starts the type unification process. + While this method is actually a member of the DerivedType class, it is most + often used on OpaqueType instances. Type unification is actually a recursive + process. After unification, types can become structurally isomorphic to + existing types, and all duplicates are deleted (to preserve pointer equality). +

    + +

    + In the example above, the OpaqueType object is definitely deleted. + Additionally, if there is an "{ \2*, int}" type already created in the system, + the pointer and struct type created are also deleted. Obviously whenever + a type is deleted, any "Type*" pointers in the program are invalidated. As + such, it is safest to avoid having any "Type*" pointers to abstract types + live across a call to refineAbstractTypeTo (note that non-abstract + types can never move or be deleted). To deal with this, the PATypeHolder class is used to maintain a stable + reference to a possibly refined type, and the AbstractTypeUser class is used to update more + complex datastructures. +

    + +
    + + + + +
    +

    + PATypeHolder is a form of a "smart pointer" for Type objects. When VMCore + happily goes about nuking types that become isomorphic to existing types, it + automatically updates all PATypeHolder objects to point to the new type. In the + example above, this allows the code to maintain a pointer to the resultant + resolved recursive type, even though the Type*'s are potentially invalidated. +

    + +

    + PATypeHolder is an extremely light-weight object that uses a lazy union-find + implementation to update pointers. For example the pointer from a Value to its + Type is maintained by PATypeHolder objects. +

    + +
    + + + + +
    + +

    + Some data structures need more to perform more complex updates when types get + resolved. The SymbolTable class, for example, needs + move and potentially merge type planes in its representation when a pointer + changes.

    + +

    + To support this, a class can derive from the AbstractTypeUser class. This class + allows it to get callbacks when certain types are resolved. To register to get + callbacks for a particular type, the DerivedType::{add/remove}AbstractTypeUser + methods can be called on a type. Note that these methods only work for + abstract types. Concrete types (those that do not include an opaque objects + somewhere) can never be refined. +

    +
    + + + + + +
    +

    This class provides a symbol table that the Function and + Module classes use for naming definitions. The symbol table can + provide a name for any Value or Type. SymbolTable is an abstract data + type. It hides the data it contains and provides access to it through a + controlled interface.

    + +

    Note that the symbol table class is should not be directly accessed by most + clients. It should only be used when iteration over the symbol table names + themselves are required, which is very special purpose. Note that not all LLVM + Values have names, and those without names (i.e. they have + an empty name) do not exist in the symbol table. +

    + +

    To use the SymbolTable well, you need to understand the + structure of the information it holds. The class contains two + std::map objects. The first, pmap, is a map of + Type* to maps of name (std::string) to Value*. + The second, tmap, is a map of names to Type*. Thus, Values + are stored in two-dimensions and accessed by Type and name. Types, + however, are stored in a single dimension and accessed only by name.

    + +

    The interface of this class provides three basic types of operations: +

      +
    1. Accessors. Accessors provide read-only access to information + such as finding a value for a name with the + lookup method.
    2. +
    3. Mutators. Mutators allow the user to add information to the + SymbolTable with methods like + insert.
    4. +
    5. Iterators. Iterators allow the user to traverse the content + of the symbol table in well defined ways, such as the method + type_begin.
    6. +
    + +

    Accessors

    +
    +
    Value* lookup(const Type* Ty, const std::string& name) const: +
    +
    The lookup method searches the type plane given by the + Ty parameter for a Value with the provided name. + If a suitable Value is not found, null is returned.
    + +
    Type* lookupType( const std::string& name) const:
    +
    The lookupType method searches through the types for a + Type with the provided name. If a suitable Type + is not found, null is returned.
    + +
    bool hasTypes() const:
    +
    This function returns true if an entry has been made into the type + map.
    + +
    bool isEmpty() const:
    +
    This function returns true if both the value and types maps are + empty
    +
    + +

    Mutators

    +
    +
    void insert(Value *Val):
    +
    This method adds the provided value to the symbol table. The Value must + have both a name and a type which are extracted and used to place the value + in the correct type plane under the value's name.
    + +
    void insert(const std::string& Name, Value *Val):
    +
    Inserts a constant or type into the symbol table with the specified + name. There can be a many to one mapping between names and constants + or types.
    + +
    void insert(const std::string& Name, Type *Typ):
    +
    Inserts a type into the symbol table with the specified name. There + can be a many-to-one mapping between names and types. This method + allows a type with an existing entry in the symbol table to get + a new name.
    + +
    void remove(Value* Val):
    +
    This method removes a named value from the symbol table. The + type and name of the Value are extracted from \p N and used to + lookup the Value in the correct type plane. If the Value is + not in the symbol table, this method silently ignores the + request.
    + +
    void remove(Type* Typ):
    +
    This method removes a named type from the symbol table. The + name of the type is extracted from \P T and used to look up + the Type in the type map. If the Type is not in the symbol + table, this method silently ignores the request.
    + +
    Value* remove(const std::string& Name, Value *Val):
    +
    Remove a constant or type with the specified name from the + symbol table.
    + +
    Type* remove(const std::string& Name, Type* T):
    +
    Remove a type with the specified name from the symbol table. + Returns the removed Type.
    + +
    Value *value_remove(const value_iterator& It):
    +
    Removes a specific value from the symbol table. + Returns the removed value.
    + +
    bool strip():
    +
    This method will strip the symbol table of its names leaving + the type and values.
    + +
    void clear():
    +
    Empty the symbol table completely.
    +
    + +

    Iteration

    +

    The following functions describe three types of iterators you can obtain + the beginning or end of the sequence for both const and non-const. It is + important to keep track of the different kinds of iterators. There are + three idioms worth pointing out:

    + + + + + + + + + + + + + + +
    UnitsIteratorIdiom
    Planes Of name/Value mapsPI
    
    + for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
    +      PE = ST.plane_end(); PI != PE; ++PI ) {
    +   PI->first // This is the Type* of the plane
    +   PI->second // This is the SymbolTable::ValueMap of name/Value pairs
    +     
    All name/Type PairsTI
    
    + for (SymbolTable::type_const_iterator TI = ST.type_begin(),
    +      TE = ST.type_end(); TI != TE; ++TI )
    +   TI->first  // This is the name of the type
    +   TI->second // This is the Type* value associated with the name
    +     
    name/Value pairs in a planeVI
    
    + for (SymbolTable::value_const_iterator VI = ST.value_begin(SomeType),
    +      VE = ST.value_end(SomeType); VI != VE; ++VI )
    +   VI->first  // This is the name of the Value
    +   VI->second // This is the Value* value associated with the name
    +     
    + +

    Using the recommended iterator names and idioms will help you avoid + making mistakes. Of particular note, make sure that whenever you use + value_begin(SomeType) that you always compare the resulting iterator + with value_end(SomeType) not value_end(SomeOtherType) or else you + will loop infinitely.

    + +
    + +
    plane_iterator plane_begin():
    +
    Get an iterator that starts at the beginning of the type planes. + The iterator will iterate over the Type/ValueMap pairs in the + type planes.
    + +
    plane_const_iterator plane_begin() const:
    +
    Get a const_iterator that starts at the beginning of the type + planes. The iterator will iterate over the Type/ValueMap pairs + in the type planes.
    + +
    plane_iterator plane_end():
    +
    Get an iterator at the end of the type planes. This serves as + the marker for end of iteration over the type planes.
    + +
    plane_const_iterator plane_end() const:
    +
    Get a const_iterator at the end of the type planes. This serves as + the marker for end of iteration over the type planes.
    + +
    value_iterator value_begin(const Type *Typ):
    +
    Get an iterator that starts at the beginning of a type plane. + The iterator will iterate over the name/value pairs in the type plane. + Note: The type plane must already exist before using this.
    + +
    value_const_iterator value_begin(const Type *Typ) const:
    +
    Get a const_iterator that starts at the beginning of a type plane. + The iterator will iterate over the name/value pairs in the type plane. + Note: The type plane must already exist before using this.
    + +
    value_iterator value_end(const Type *Typ):
    +
    Get an iterator to the end of a type plane. This serves as the marker + for end of iteration of the type plane. + Note: The type plane must already exist before using this.
    + +
    value_const_iterator value_end(const Type *Typ) const:
    +
    Get a const_iterator to the end of a type plane. This serves as the + marker for end of iteration of the type plane. + Note: the type plane must already exist before using this.
    + +
    type_iterator type_begin():
    +
    Get an iterator to the start of the name/Type map.
    + +
    type_const_iterator type_begin() cons:
    +
    Get a const_iterator to the start of the name/Type map.
    + +
    type_iterator type_end():
    +
    Get an iterator to the end of the name/Type map. This serves as the + marker for end of iteration of the types.
    + +
    type_const_iterator type_end() const:
    +
    Get a const-iterator to the end of the name/Type map. This serves + as the marker for end of iteration of the types.
    + +
    plane_const_iterator find(const Type* Typ ) const:
    +
    This method returns a plane_const_iterator for iteration over + the type planes starting at a specific plane, given by \p Ty.
    + +
    plane_iterator find( const Type* Typ :
    +
    This method returns a plane_iterator for iteration over the + type planes starting at a specific plane, given by \p Ty.
    + +
    +
    + + + + + + + +
    + +

    The Core LLVM classes are the primary means of representing the program + being inspected or transformed. The core LLVM classes are defined in + header files in the include/llvm/ directory, and implemented in + the lib/VMCore directory.

    + +
    + + + + +
    + +

    #include "llvm/Value.h" +
    + doxygen info: Value Class

    + +

    The Value class is the most important class in the LLVM Source + base. It represents a typed value that may be used (among other things) as an + operand to an instruction. There are many different types of Values, + such as Constants,Arguments. Even Instructions and Functions are Values.

    + +

    A particular Value may be used many times in the LLVM representation + for a program. For example, an incoming argument to a function (represented + with an instance of the Argument class) is "used" by + every instruction in the function that references the argument. To keep track + of this relationship, the Value class keeps a list of all of the Users that is using it (the User class is a base class for all nodes in the LLVM + graph that can refer to Values). This use list is how LLVM represents + def-use information in the program, and is accessible through the use_* + methods, shown below.

    + +

    Because LLVM is a typed representation, every LLVM Value is typed, + and this Type is available through the getType() + method. In addition, all LLVM values can be named. The "name" of the + Value is a symbolic string printed in the LLVM code:

    + +
       %foo = add int 1, 2
    + +

    The name of this instruction is "foo". NOTE + that the name of any value may be missing (an empty string), so names should + ONLY be used for debugging (making the source code easier to read, + debugging printouts), they should not be used to keep track of values or map + between them. For this purpose, use a std::map of pointers to the + Value itself instead.

    + +

    One important aspect of LLVM is that there is no distinction between an SSA + variable and the operation that produces it. Because of this, any reference to + the value produced by an instruction (or the value available as an incoming + argument, for example) is represented as a direct pointer to the instance of + the class that + represents this value. Although this may take some getting used to, it + simplifies the representation and makes it easier to manipulate.

    + +
    + + + + +
    + +
      +
    • Value::use_iterator - Typedef for iterator over the + use-list
      + Value::use_const_iterator - Typedef for const_iterator over + the use-list
      + unsigned use_size() - Returns the number of users of the + value.
      + bool use_empty() - Returns true if there are no users.
      + use_iterator use_begin() - Get an iterator to the start of + the use-list.
      + use_iterator use_end() - Get an iterator to the end of the + use-list.
      + User *use_back() - Returns the last + element in the list. +

      These methods are the interface to access the def-use + information in LLVM. As with all other iterators in LLVM, the naming + conventions follow the conventions defined by the STL.

      +
    • +
    • Type *getType() const +

      This method returns the Type of the Value.

      +
    • +
    • bool hasName() const
      + std::string getName() const
      + void setName(const std::string &Name) +

      This family of methods is used to access and assign a name to a Value, + be aware of the precaution above.

      +
    • +
    • void replaceAllUsesWith(Value *V) + +

      This method traverses the use list of a Value changing all Users of the current value to refer to + "V" instead. For example, if you detect that an instruction always + produces a constant value (for example through constant folding), you can + replace all uses of the instruction with the constant like this:

      + +
        Inst->replaceAllUsesWith(ConstVal);
      +
    + +
    + + + + +
    + +

    + #include "llvm/User.h"
    + doxygen info: User Class
    + Superclass: Value

    + +

    The User class is the common base class of all LLVM nodes that may + refer to Values. It exposes a list of "Operands" + that are all of the Values that the User is + referring to. The User class itself is a subclass of + Value.

    + +

    The operands of a User point directly to the LLVM Value that it refers to. Because LLVM uses Static + Single Assignment (SSA) form, there can only be one definition referred to, + allowing this direct connection. This connection provides the use-def + information in LLVM.

    + +
    + + + + +
    + +

    The User class exposes the operand list in two ways: through + an index access interface and through an iterator based interface.

    + +
      +
    • Value *getOperand(unsigned i)
      + unsigned getNumOperands() +

      These two methods expose the operands of the User in a + convenient form for direct access.

    • + +
    • User::op_iterator - Typedef for iterator over the operand + list
      + op_iterator op_begin() - Get an iterator to the start of + the operand list.
      + op_iterator op_end() - Get an iterator to the end of the + operand list. +

      Together, these methods make up the iterator based interface to + the operands of a User.

    • +
    + +
    + + + + +
    + +

    #include "llvm/Instruction.h"
    + doxygen info: Instruction Class
    + Superclasses: User, Value

    + +

    The Instruction class is the common base class for all LLVM + instructions. It provides only a few methods, but is a very commonly used + class. The primary data tracked by the Instruction class itself is the + opcode (instruction type) and the parent BasicBlock the Instruction is embedded + into. To represent a specific type of instruction, one of many subclasses of + Instruction are used.

    + +

    Because the Instruction class subclasses the User class, its operands can be accessed in the same + way as for other Users (with the + getOperand()/getNumOperands() and + op_begin()/op_end() methods).

    An important file for + the Instruction class is the llvm/Instruction.def file. This + file contains some meta-data about the various different types of instructions + in LLVM. It describes the enum values that are used as opcodes (for example + Instruction::Add and Instruction::SetLE), as well as the + concrete sub-classes of Instruction that implement the instruction (for + example BinaryOperator and SetCondInst). Unfortunately, the use of macros in + this file confuses doxygen, so these enum values don't show up correctly in the + doxygen output.

    + +
    + + + + +
    + +
      +
    • BasicBlock *getParent() +

      Returns the BasicBlock that + this Instruction is embedded into.

    • +
    • bool mayWriteToMemory() +

      Returns true if the instruction writes to memory, i.e. it is a + call,free,invoke, or store.

    • +
    • unsigned getOpcode() +

      Returns the opcode for the Instruction.

    • +
    • Instruction *clone() const +

      Returns another instance of the specified instruction, identical + in all ways to the original except that the instruction has no parent + (ie it's not embedded into a BasicBlock), + and it has no name

    • +
    + +
    + + + + +
    + +

    #include "llvm/BasicBlock.h"
    + doxygen info: BasicBlock + Class
    + Superclass: Value

    + +

    This class represents a single entry multiple exit section of the code, + commonly known as a basic block by the compiler community. The + BasicBlock class maintains a list of Instructions, which form the body of the block. + Matching the language definition, the last element of this list of instructions + is always a terminator instruction (a subclass of the TerminatorInst class).

    + +

    In addition to tracking the list of instructions that make up the block, the + BasicBlock class also keeps track of the Function that it is embedded into.

    + +

    Note that BasicBlocks themselves are Values, because they are referenced by instructions + like branches and can go in the switch tables. BasicBlocks have type + label.

    + +
    + + + + +
    + +
      + +
    • BasicBlock(const std::string &Name = "", Function *Parent = 0) + +

      The BasicBlock constructor is used to create new basic blocks for + insertion into a function. The constructor optionally takes a name for the new + block, and a Function to insert it into. If + the Parent parameter is specified, the new BasicBlock is + automatically inserted at the end of the specified Function, if not specified, the BasicBlock must be + manually inserted into the Function.

    • + +
    • BasicBlock::iterator - Typedef for instruction list iterator
      + BasicBlock::const_iterator - Typedef for const_iterator.
      + begin(), end(), front(), back(), + size(), empty() + STL-style functions for accessing the instruction list. + +

      These methods and typedefs are forwarding functions that have the same + semantics as the standard library methods of the same names. These methods + expose the underlying instruction list of a basic block in a way that is easy to + manipulate. To get the full complement of container operations (including + operations to update the list), you must use the getInstList() + method.

    • + +
    • BasicBlock::InstListType &getInstList() + +

      This method is used to get access to the underlying container that actually + holds the Instructions. This method must be used when there isn't a forwarding + function in the BasicBlock class for the operation that you would like + to perform. Because there are no forwarding functions for "updating" + operations, you need to use this if you want to update the contents of a + BasicBlock.

    • + +
    • Function *getParent() + +

      Returns a pointer to Function the block is + embedded into, or a null pointer if it is homeless.

    • + +
    • TerminatorInst *getTerminator() + +

      Returns a pointer to the terminator instruction that appears at the end of + the BasicBlock. If there is no terminator instruction, or if the last + instruction in the block is not a terminator, then a null pointer is + returned.

    • + +
    + +
    + + + + +
    + +

    #include "llvm/GlobalValue.h"
    + doxygen info: GlobalValue + Class
    + Superclasses: Constant, + User, Value

    + +

    Global values (GlobalVariables or Functions) are the only LLVM values that are + visible in the bodies of all Functions. + Because they are visible at global scope, they are also subject to linking with + other globals defined in different translation units. To control the linking + process, GlobalValues know their linkage rules. Specifically, + GlobalValues know whether they have internal or external linkage, as + defined by the LinkageTypes enumeration.

    + +

    If a GlobalValue has internal linkage (equivalent to being + static in C), it is not visible to code outside the current translation + unit, and does not participate in linking. If it has external linkage, it is + visible to external code, and does participate in linking. In addition to + linkage information, GlobalValues keep track of which Module they are currently part of.

    + +

    Because GlobalValues are memory objects, they are always referred to + by their address. As such, the Type of a + global is always a pointer to its contents. It is important to remember this + when using the GetElementPtrInst instruction because this pointer must + be dereferenced first. For example, if you have a GlobalVariable (a + subclass of GlobalValue) that is an array of 24 ints, type [24 x + int], then the GlobalVariable is a pointer to that array. Although + the address of the first element of this array and the value of the + GlobalVariable are the same, they have different types. The + GlobalVariable's type is [24 x int]. The first element's type + is int. Because of this, accessing a global value requires you to + dereference the pointer with GetElementPtrInst first, then its elements + can be accessed. This is explained in the LLVM + Language Reference Manual.

    + +
    + + + + +
    + +
      +
    • bool hasInternalLinkage() const
      + bool hasExternalLinkage() const
      + void setInternalLinkage(bool HasInternalLinkage) +

      These methods manipulate the linkage characteristics of the GlobalValue.

      +

      +
    • +
    • Module *getParent() +

      This returns the Module that the + GlobalValue is currently embedded into.

    • +
    + +
    + + + + +
    + +

    #include "llvm/Function.h"
    doxygen + info: Function Class
    + Superclasses: GlobalValue, + Constant, + User, + Value

    + +

    The Function class represents a single procedure in LLVM. It is + actually one of the more complex classes in the LLVM heirarchy because it must + keep track of a large amount of data. The Function class keeps track + of a list of BasicBlocks, a list of formal + Arguments, and a + SymbolTable.

    + +

    The list of BasicBlocks is the most + commonly used part of Function objects. The list imposes an implicit + ordering of the blocks in the function, which indicate how the code will be + layed out by the backend. Additionally, the first BasicBlock is the implicit entry node for the + Function. It is not legal in LLVM to explicitly branch to this initial + block. There are no implicit exit nodes, and in fact there may be multiple exit + nodes from a single Function. If the BasicBlock list is empty, this indicates that + the Function is actually a function declaration: the actual body of the + function hasn't been linked in yet.

    + +

    In addition to a list of BasicBlocks, the + Function class also keeps track of the list of formal Arguments that the function receives. This + container manages the lifetime of the Argument + nodes, just like the BasicBlock list does for + the BasicBlocks.

    + +

    The SymbolTable is a very rarely used + LLVM feature that is only used when you have to look up a value by name. Aside + from that, the SymbolTable is used + internally to make sure that there are not conflicts between the names of Instructions, BasicBlocks, or Arguments in the function body.

    + +

    Note that Function is a GlobalValue + and therefore also a Constant. The value of the function + is its address (after linking) which is guaranteed to be constant.

    +
    + + + + +
    + +
      +
    • Function(const FunctionType + *Ty, LinkageTypes Linkage, const std::string &N = "", Module* Parent = 0) + +

      Constructor used when you need to create new Functions to add + the the program. The constructor must specify the type of the function to + create and what type of linkage the function should have. The FunctionType argument + specifies the formal arguments and return value for the function. The same + FunctionType value can be used to + create multiple functions. The Parent argument specifies the Module + in which the function is defined. If this argument is provided, the function + will automatically be inserted into that module's list of + functions.

    • + +
    • bool isExternal() + +

      Return whether or not the Function has a body defined. If the + function is "external", it does not have a body, and thus must be resolved + by linking with a function defined in a different translation unit.

    • + +
    • Function::iterator - Typedef for basic block list iterator
      + Function::const_iterator - Typedef for const_iterator.
      + + begin(), end() + size(), empty() + +

      These are forwarding methods that make it easy to access the contents of + a Function object's BasicBlock + list.

    • + +
    • Function::BasicBlockListType &getBasicBlockList() + +

      Returns the list of BasicBlocks. This + is necessary to use when you need to update the list or perform a complex + action that doesn't have a forwarding method.

    • + +
    • Function::arg_iterator - Typedef for the argument list + iterator
      + Function::const_arg_iterator - Typedef for const_iterator.
      + + arg_begin(), arg_end() + arg_size(), arg_empty() + +

      These are forwarding methods that make it easy to access the contents of + a Function object's Argument + list.

    • + +
    • Function::ArgumentListType &getArgumentList() + +

      Returns the list of Arguments. This is + necessary to use when you need to update the list or perform a complex + action that doesn't have a forwarding method.

    • + +
    • BasicBlock &getEntryBlock() + +

      Returns the entry BasicBlock for the + function. Because the entry block for the function is always the first + block, this returns the first block of the Function.

    • + +
    • Type *getReturnType()
      + FunctionType *getFunctionType() + +

      This traverses the Type of the + Function and returns the return type of the function, or the FunctionType of the actual + function.

    • + +
    • SymbolTable *getSymbolTable() + +

      Return a pointer to the SymbolTable + for this Function.

    • +
    + +
    + + + + +
    + +

    #include "llvm/GlobalVariable.h" +
    + doxygen info: GlobalVariable + Class
    + Superclasses: GlobalValue, + Constant, + User, + Value

    + +

    Global variables are represented with the (suprise suprise) + GlobalVariable class. Like functions, GlobalVariables are also + subclasses of GlobalValue, and as such are + always referenced by their address (global values must live in memory, so their + "name" refers to their constant address). See + GlobalValue for more on this. Global + variables may have an initial value (which must be a + Constant), and if they have an initializer, + they may be marked as "constant" themselves (indicating that their contents + never change at runtime).

    +
    + + + + +
    + +
      +
    • GlobalVariable(const Type *Ty, bool + isConstant, LinkageTypes& Linkage, Constant + *Initializer = 0, const std::string &Name = "", Module* Parent = 0) + +

      Create a new global variable of the specified type. If + isConstant is true then the global variable will be marked as + unchanging for the program. The Linkage parameter specifies the type of + linkage (internal, external, weak, linkonce, appending) for the variable. If + the linkage is InternalLinkage, WeakLinkage, or LinkOnceLinkage,  then + the resultant global variable will have internal linkage. AppendingLinkage + concatenates together all instances (in different translation units) of the + variable into a single variable but is only applicable to arrays.  See + the LLVM Language Reference for + further details on linkage types. Optionally an initializer, a name, and the + module to put the variable into may be specified for the global variable as + well.

    • + +
    • bool isConstant() const + +

      Returns true if this is a global variable that is known not to + be modified at runtime.

    • + +
    • bool hasInitializer() + +

      Returns true if this GlobalVariable has an intializer.

    • + +
    • Constant *getInitializer() + +

      Returns the intial value for a GlobalVariable. It is not legal + to call this method if there is no initializer.

    • +
    + +
    + + + + +
    + +

    #include "llvm/Module.h"
    doxygen info: + Module Class

    + +

    The Module class represents the top level structure present in LLVM + programs. An LLVM module is effectively either a translation unit of the + original program or a combination of several translation units merged by the + linker. The Module class keeps track of a list of Functions, a list of GlobalVariables, and a SymbolTable. Additionally, it contains a few + helpful member functions that try to make common operations easy.

    + +
    + + + + +
    + +
      +
    • Module::Module(std::string name = "")
    • +
    + +

    Constructing a Module is easy. You can optionally + provide a name for it (probably based on the name of the translation unit).

    + +
      +
    • Module::iterator - Typedef for function list iterator
      + Module::const_iterator - Typedef for const_iterator.
      + + begin(), end() + size(), empty() + +

      These are forwarding methods that make it easy to access the contents of + a Module object's Function + list.

    • + +
    • Module::FunctionListType &getFunctionList() + +

      Returns the list of Functions. This is + necessary to use when you need to update the list or perform a complex + action that doesn't have a forwarding method.

      + +

    • +
    + +
    + +
      +
    • Module::global_iterator - Typedef for global variable list iterator
      + + Module::const_global_iterator - Typedef for const_iterator.
      + + global_begin(), global_end() + global_size(), global_empty() + +

      These are forwarding methods that make it easy to access the contents of + a Module object's GlobalVariable list.

    • + +
    • Module::GlobalListType &getGlobalList() + +

      Returns the list of GlobalVariables. This is necessary to + use when you need to update the list or perform a complex action that + doesn't have a forwarding method.

      + +

    • +
    + +
    + + + +
    + +
      +
    • Function *getFunction(const std::string + &Name, const FunctionType *Ty) + +

      Look up the specified function in the Module SymbolTable. If it does not exist, return + null.

    • + +
    • Function *getOrInsertFunction(const + std::string &Name, const FunctionType *T) + +

      Look up the specified function in the Module SymbolTable. If it does not exist, add an + external declaration for the function and return it.

    • + +
    • std::string getTypeName(const Type *Ty) + +

      If there is at least one entry in the SymbolTable for the specified Type, return it. Otherwise return the empty + string.

    • + +
    • bool addTypeName(const std::string &Name, const Type *Ty) + +

      Insert an entry in the SymbolTable + mapping Name to Ty. If there is already an entry for this + name, true is returned and the SymbolTable is not modified.

    • +
    + +
    + + + + +
    + +

    Constant represents a base class for different types of constants. It + is subclassed by ConstantBool, ConstantInt, ConstantSInt, ConstantUInt, + ConstantArray etc for representing the various types of Constants.

    + +
    + + + +
    +
    + + +
    Important Subclasses of Constant
    +
    +
      +
    • ConstantSInt : This subclass of Constant represents a signed integer + constant. +
        +
      • int64_t getValue() const: Returns the underlying value of + this constant.
      • +
      +
    • +
    • ConstantUInt : This class represents an unsigned integer. +
        +
      • uint64_t getValue() const: Returns the underlying value of + this constant.
      • +
      +
    • +
    • ConstantFP : This class represents a floating point constant. +
        +
      • double getValue() const: Returns the underlying value of + this constant.
      • +
      +
    • +
    • ConstantBool : This represents a boolean constant. +
        +
      • bool getValue() const: Returns the underlying value of this + constant.
      • +
      +
    • +
    • ConstantArray : This represents a constant array. +
        +
      • const std::vector<Use> &getValues() const: Returns + a vector of component constants that makeup this array.
      • +
      +
    • +
    • ConstantStruct : This represents a constant struct. +
        +
      • const std::vector<Use> &getValues() const: Returns + a vector of component constants that makeup this array.
      • +
      +
    • +
    • GlobalValue : This represents either a global variable or a function. In + either case, the value is a constant fixed address (after linking). +
    • +
    +
    + + + + +
    + +

    Type as noted earlier is also a subclass of a Value class. Any primitive + type (like int, short etc) in LLVM is an instance of Type Class. All other + types are instances of subclasses of type like FunctionType, ArrayType + etc. DerivedType is the interface for all such dervied types including + FunctionType, ArrayType, PointerType, StructType. Types can have names. They can + be recursive (StructType). There exists exactly one instance of any type + structure at a time. This allows using pointer equality of Type *s for comparing + types.

    + +
    + + + + +
    + +
      + +
    • bool isSigned() const: Returns whether an integral numeric type + is signed. This is true for SByteTy, ShortTy, IntTy, LongTy. Note that this is + not true for Float and Double.
    • + +
    • bool isUnsigned() const: Returns whether a numeric type is + unsigned. This is not quite the complement of isSigned... nonnumeric types + return false as they do with isSigned. This returns true for UByteTy, + UShortTy, UIntTy, and ULongTy.
    • + +
    • bool isInteger() const: Equivalent to isSigned() || isUnsigned().
    • + +
    • bool isIntegral() const: Returns true if this is an integral + type, which is either Bool type or one of the Integer types.
    • + +
    • bool isFloatingPoint(): Return true if this is one of the two + floating point types.
    • + +
    • isLosslesslyConvertableTo (const Type *Ty) const: Return true if + this type can be converted to 'Ty' without any reinterpretation of bits. For + example, uint to int or one pointer type to another.
    • +
    +
    + + + +
    +
      +
    • SequentialType : This is subclassed by ArrayType and PointerType +
        +
      • const Type * getElementType() const: Returns the type of each + of the elements in the sequential type.
      • +
      +
    • +
    • ArrayType : This is a subclass of SequentialType and defines interface for + array types. +
        +
      • unsigned getNumElements() const: Returns the number of + elements in the array.
      • +
      +
    • +
    • PointerType : Subclass of SequentialType for pointer types.
    • +
    • StructType : subclass of DerivedTypes for struct types
    • +
    • FunctionType : subclass of DerivedTypes for function types. +
        +
      • bool isVarArg() const: Returns true if its a vararg + function
      • +
      • const Type * getReturnType() const: Returns the + return type of the function.
      • +
      • const Type * getParamType (unsigned i): Returns + the type of the ith parameter.
      • +
      • const unsigned getNumParams() const: Returns the + number of formal parameters.
      • +
      +
    • +
    +
    + + + + +
    + +

    This subclass of Value defines the interface for incoming formal + arguments to a function. A Function maintains a list of its formal + arguments. An argument has a pointer to the parent Function.

    + +
    + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Dinakar Dhurjati and + Chris Lattner
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/Projects.html diff -c /dev/null llvm-www/releases/1.8/docs/Projects.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/Projects.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,460 ---- + + + + Creating an LLVM Project + + + + +
    Creating an LLVM Project
    + +
      +
    1. Overview
    2. +
    3. Create a project from the Sample Project
    4. +
    5. Source tree layout
    6. +
    7. Writing LLVM-style Makefiles +
        +
      1. Required Variables
      2. +
      3. Variables for Building Subdirectories
      4. +
      5. Variables for Building Libraries
      6. +
      7. Variables for Building Programs
      8. +
      9. Miscellaneous Variables
      10. +
    8. +
    9. Placement of object code
    10. +
    11. Further help
    12. +
    + +
    +

    Written by John Criswell

    +
    + + + + + +
    + +

    The LLVM build system is designed to facilitate the building of third party + projects that use LLVM header files, libraries, and tools. In order to use + these facilities, a Makefile from a project must do the following things:

    + +
      +
    1. Set make variables. There are several variables that a Makefile + needs to set to use the LLVM build system: +
        +
      • PROJECT_NAME - The name by which your project is known.
      • +
      • LLVM_SRC_ROOT - The root of the LLVM source tree.
      • +
      • LLVM_OBJ_ROOT - The root of the LLVM object tree.
      • +
      • PROJ_SRC_ROOT - The root of the project's source tree.
      • +
      • PROJ_OBJ_ROOT - The root of the project's object tree.
      • +
      • PROJ_INSTALL_ROOT - The root installation directory.
      • +
      • LEVEL - The relative path from the current directory to the + project's root ($PROJ_OBJ_ROOT).
      • +
    2. +
    3. Include Makefile.config from $(LLVM_OBJ_ROOT).
    4. +
    5. Include Makefile.rules from $(LLVM_SRC_ROOT).
    6. +
    + +

    There are two ways that you can set all of these variables:

    +
      +
    1. You can write your own Makefiles which hard-code these values.
    2. +
    3. You can use the pre-made LLVM sample project. This sample project + includes Makefiles, a configure script that can be used to configure the + location of LLVM, and the ability to support multiple object directories + from a single source directory.
    4. +
    + +

    This document assumes that you will base your project on the LLVM sample + project found in llvm/projects/sample. If you want to devise your own + build system, studying the sample project and LLVM Makefiles will probably + provide enough information on how to write your own Makefiles.

    + +
    + + + + + +
    + +

    Follow these simple steps to start your project:

    + +
      +
    1. Copy the llvm/projects/sample directory to any place of your + choosing. You can place it anywhere you like. Rename the directory to match + the name of your project.
    2. + +
    3. + If you downloaded LLVM using CVS, remove all the directories named CVS (and all + the files therein) from your project's new source tree. This will keep CVS + from thinking that your project is inside llvm/projects/sample. +
    4. + +
    5. Add your source code and Makefiles to your source tree.
    6. + +
    7. If you want your project to be configured with the configure script + then you need to edit autoconf/configure.ac as follows: +
        +
      • AC_INIT. Place the name of your project, its version number and + a contact email address for your project as the arguments to this macro
      • +
      • AC_CONFIG_AUX_DIR. If your project isn't in the + llvm/projects directory then you might need to adjust this so that + it specifies a relative path to the llvm/autoconf directory.
      • +
      • LLVM_CONFIG_PROJECT. Just leave this alone.
      • +
      • AC_CONFIG_SRCDIR. Specify a path to a file name that identifies + your project; or just leave it at Makefile.common.in
      • +
      • AC_CONFIG_FILES. Do not change.
      • +
      • AC_CONFIG_MAKEFILE. Use one of these macros for each Makefile + that your project uses. This macro arranges for your makefiles to be copied + from the source directory, unmodified, to the build directory.
      • +
      +
    8. + +
    9. After updating autoconf/configure.ac, regenerate the + configure script with these commands: + +
      +

      % cd autoconf
      + % AutoRegen.sh

      +
      + +

      You must be using Autoconf version 2.59 or later and your aclocal version + should 1.9 or later.

    10. + +
    11. Run configure in the directory in which you want to place + object code. Use the following options to tell your project where it + can find LLVM: + +
      +
      --with-llvmsrc=<directory>
      +
      Tell your project where the LLVM source tree is located.
      +

      --with-llvmobj=<directory>
      +
      Tell your project where the LLVM object tree is located.
      +

      --prefix=<directory>
      +
      Tell your project where it should get installed.
      +
      +
    + +

    That's it! Now all you have to do is type gmake (or make + if your on a GNU/Linux system) in the root of your object directory, and your + project should build.

    + +
    + + + + + +
    + +

    In order to use the LLVM build system, you will want to organize your + source code so that it can benefit from the build system's features. + Mainly, you want your source tree layout to look similar to the LLVM + source tree layout. The best way to do this is to just copy the + project tree from llvm/projects/sample and modify it to meet + your needs, but you can certainly add to it if you want.

    + +

    Underneath your top level directory, you should have the following + directories:

    + +
    +
    lib +
    + This subdirectory should contain all of your library source + code. For each library that you build, you will have one + directory in lib that will contain that library's source + code. + +

    + Libraries can be object files, archives, or dynamic libraries. + The lib directory is just a convenient place for libraries + as it places them all in a directory from which they can be linked + later. + +

    include +
    + This subdirectory should contain any header files that are + global to your project. By global, we mean that they are used + by more than one library or executable of your project. +

    + By placing your header files in include, they will be + found automatically by the LLVM build system. For example, if + you have a file include/jazz/note.h, then your source + files can include it simply with #include "jazz/note.h". + +

    tools +
    + This subdirectory should contain all of your source + code for executables. For each program that you build, you + will have one directory in tools that will contain that + program's source code. +

    + +

    test +
    + This subdirectory should contain tests that verify that your code + works correctly. Automated tests are especially useful. +

    + Currently, the LLVM build system provides basic support for tests. + The LLVM system provides the following: +

      +
    • + LLVM provides a tcl procedure that is used by Dejagnu to run + tests. It can be found in llvm/lib/llvm-dg.exp. This + test procedure uses RUN lines in the actual test case to determine + how to run the test. See the TestingGuide for more details. You + can easily write Makefile support similar to the Makefiles in + llvm/test to use Dejagnu to run your project's tests.
    • +
    • + LLVM contains an optional package called llvm-test + which provides benchmarks and programs that are known to compile with the + LLVM GCC front ends. You can use these + programs to test your code, gather statistics information, and + compare it to the current LLVM performance statistics. +
      Currently, there is no way to hook your tests directly into the + llvm/test testing harness. You will simply + need to find a way to use the source provided within that directory + on your own. +
    +
    + +

    Typically, you will want to build your lib directory first followed by + your tools directory.

    + +
    + + + + + +
    + +

    The LLVM build system provides a convenient way to build libraries and + executables. Most of your project Makefiles will only need to define a few + variables. Below is a list of the variables one can set and what they can + do:

    + +
    + + + + +
    + +
    +
    LEVEL +
    + This variable is the relative path from this Makefile to the + top directory of your project's source code. For example, if + your source code is in /tmp/src, then the Makefile in + /tmp/src/jump/high would set LEVEL to "../..". +
    + +
    + + + + +
    + +
    +
    DIRS +
    + This is a space separated list of subdirectories that should be + built. They will be built, one at a time, in the order + specified. +

    + +

    PARALLEL_DIRS +
    + This is a list of directories that can be built in parallel. + These will be built after the directories in DIRS have been + built. +

    + +

    OPTIONAL_DIRS +
    + This is a list of directories that can be built if they exist, + but will not cause an error if they do not exist. They are + built serially in the order in which they are listed. +
    + +
    + + + + +
    + +
    +
    LIBRARYNAME +
    + This variable contains the base name of the library that will + be built. For example, to build a library named + libsample.a, LIBRARYNAME should be set to + sample. +

    + +

    BUILD_ARCHIVE +
    + By default, a library is a .o file that is linked + directly into a program. To build an archive (also known as + a static library), set the BUILD_ARCHIVE variable. +

    + +

    SHARED_LIBRARY +
    + If SHARED_LIBRARY is defined in your Makefile, a shared + (or dynamic) library will be built. +
    + +
    + + + + +
    + +
    +
    TOOLNAME +
    + This variable contains the name of the program that will + be built. For example, to build an executable named + sample, TOOLNAME should be set to sample. +

    + +

    USEDLIBS +
    + This variable holds a space separated list of libraries that + should be linked into the program. These libraries must either + be LLVM libraries or libraries that come from your lib + directory. The libraries must be specified by their base name. + For example, to link libsample.a, you would set USEDLIBS to + sample. +

    + Note that this works only for statically linked libraries. +

    + +

    LIBS +
    + To link dynamic libraries, add -l<library base name> to + the LIBS variable. The LLVM build system will look in the same places + for dynamic libraries as it does for static libraries. +

    + For example, to link libsample.so, you would have the + following line in your Makefile: +

    + + LIBS += -lsample + +

    + +
    + + + + +
    + +
    +
    ExtraSource +
    + This variable contains a space separated list of extra source + files that need to be built. It is useful for including the + output of Lex and Yacc programs. +

    + +

    CFLAGS +
    CPPFLAGS +
    + This variable can be used to add options to the C and C++ + compiler, respectively. It is typically used to add options + that tell the compiler the location of additional directories + to search for header files. +

    + It is highly suggested that you append to CFLAGS and CPPFLAGS as + opposed to overwriting them. The master Makefiles may already + have useful options in them that you may not want to overwrite. +

    +

    + +
    + + + + + +
    + +

    The final location of built libraries and executables will depend upon + whether you do a Debug, Release, or Profile build.

    + +
    +
    Libraries +
    + All libraries (static and dynamic) will be stored in + PROJ_OBJ_ROOT/<type>/lib, where type is Debug, + Release, or Profile for a debug, optimized, or + profiled build, respectively.

    + +

    Executables +
    All executables will be stored in + PROJ_OBJ_ROOT/<type>/bin, where type is Debug, + Release, or Profile for a debug, optimized, or profiled + build, respectively. +
    + +
    + + + + + +
    + +

    If you have any questions or need any help creating an LLVM project, + the LLVM team would be more than happy to help. You can always post your + questions to the LLVM Developers + Mailing List.

    + +
    + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + John Criswell
    + The LLVM Compiler Infrastructure +
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/ReleaseNotes.html diff -c /dev/null llvm-www/releases/1.8/docs/ReleaseNotes.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/ReleaseNotes.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,691 ---- + + + + + + LLVM 1.8 Release Notes + + + +
    LLVM 1.8 Release Notes
    + +
      +
    1. Introduction
    2. +
    3. What's New?
    4. +
    5. Installation Instructions
    6. +
    7. Portability and Supported Platforms
    8. +
    9. Known Problems +
    10. Additional Information
    11. +
    + +
    +

    Written by the LLVM Team

    +

    + + + + + +
    + +

    This document contains the release notes for the LLVM compiler + infrastructure, release 1.8. Here we describe the status of LLVM, including any + known problems and major improvements from the previous release. The most + up-to-date version of this document (corresponding to LLVM CVS) can be found + on the LLVM releases web site. If you are + not reading this on the LLVM web pages, you should probably go there because + this document may be updated after the release.

    + +

    For more information about LLVM, including information about the latest + release, please check out the main LLVM + web site. If you have questions or comments, the LLVM developer's mailing + list is a good place to send them.

    + +

    Note that if you are reading this file from CVS or the main LLVM web page, + this document applies to the next release, not the current one. To see + the release notes for the current or previous releases, see the releases page.

    + +
    + + + + + +
    + +

    This is the nineth public release of the LLVM Compiler Infrastructure. This + release incorporates a large number of enhancements and new features, + including DWARF debugging support (C and C++ on Darwin/PPC), improved inline + assembly support, a new nightly + tester, llvm-config enhancements, many bugs + fixed, and performance and compile time improvements. +

    + +
    + + + + + + + +
    + +

    The llvm-gcc4 C front-end now generates debugging info for C and C++. This + information is propagated through the compiler and the code generator can + currently produce DWARF debugging information from it. DWARF is a standard + debugging format used on many platforms, but currently LLVM only includes + target support for Mac OS X targets for the 1.8 release. +

    + +
    + + + + +
    + +

    Inline assembly support is substantially improved in LLVM 1.8 over LLVM 1.7. + Many unsupported features are now supported, and inline asm support in the X86 + backend is far better. llvm-gcc4 now supports global register variables as + well.

    + +
    + + + + +
    + +

    The loop optimizer passes now uses "Loop-Closed SSA Form", which makes it + easier to update SSA form as loop transformations change the code. An + immediate benefit of this is that the loop unswitching pass can now unswitch + loops in more cases. +

    + +
    + + + + +
    + +

    The code generator now lowers switch statements to jump tables, providing + significant performance boosts for applications (e.g. interpreters) whose + performance is highly correlated to switch statement performance.

    + +
    + + + + +
    + +

    The LLVM JIT now allows clients to deallocate machine code JIT'd to its code + buffer. This is important for long living applications that depend on the JIT. +

    + +
    + + + + +
    + +

    This release includes many other improvements, including improvements to + the optimizers and code generators (improving the generated code) changes to + speed up the compiler in many ways (improving algorithms and fine tuning + code), and changes to reduce the code size of the compiler itself.

    + +

    More specific changes include:

    + +
      +
    • LLVM 1.8 includes an initial ARM backend. This backend is in early + development stages.
    • +
    • LLVM 1.8 now includes significantly better support for mingw and + cygwin.
    • +
    • The llvm-config tool is + now built by default and has several new features.
    • +
    • The X86 and PPC backends now use the correct platform ABI for passing + vectors as arguments to functions.
    • +
    • The X86 backend now includes support for the Microsoft ML assembler + ("MASM").
    • +
    • The PowerPC backend now pattern matches the 'rlwimi' instruction more + aggressively.
    • +
    • Most of LLVM is now built with "-pedantic", ensuring better portability + to more C++ Compilers.
    • +
    • The PowerPC backend now includes initial 64-bit support. The JIT is not + complete, and the static compiler has a couple of known bugs, but support + is mostly in place. LLVM 1.9 will include completed PPC-64 support.
    • + +
    +
    + + + + +
    +
      +
    • The LLVM "SparcV9" backend (deprecated in LLVM 1.7) has been removed in + LLVM 1.8. The LLVM "Sparc" backend replaces it.
    • +
    • The --version option now prints more useful information, including the + build configuration for the tool.
    • +
    +
    + + + + + + +
    + +

    LLVM is known to work on the following platforms:

    + +
      +
    • Intel and AMD machines running Red Hat Linux, Fedora Core and FreeBSD + (and probably other unix-like systems).
    • +
    • Intel and AMD machines running on Win32 using MinGW libraries (native)
    • +
    • Sun UltraSPARC workstations running Solaris 8.
    • +
    • Intel and AMD machines running on Win32 with the Cygwin libraries (limited + support is available for native builds with Visual C++).
    • +
    • PowerPC and X86-based Mac OS X systems, running 10.2 and above.
    • +
    • Alpha-based machines running Debian GNU/Linux.
    • +
    • Itanium-based machines running Linux and HP-UX.
    • +
    + +

    The core LLVM infrastructure uses + GNU autoconf to adapt itself + to the machine and operating system on which it is built. However, minor + porting may be required to get LLVM to work on new platforms. We welcome your + portability patches and reports of successful builds or error messages.

    + +
    + + + + + +
    + +

    This section contains all known problems with the LLVM system, listed by + component. As new problems are discovered, they will be added to these + sections. If you run into a problem, please check the LLVM bug database and submit a bug if + there isn't already one.

    + +
    + + + + +
    + +

    The following components of this LLVM release are either untested, known to + be broken or unreliable, or are in early development. These components should + not be relied on, and bugs should not be filed against them, but they may be + useful to some people. In particular, if you would like to work on one of these + components, please contact us on the LLVMdev list.

    + +
      +
    • The -cee pass is known to be buggy, and may be removed in in a + future release.
    • +
    • The IA64 code generator is experimental.
    • +
    • The Alpha JIT is experimental.
    • +
    • "-filetype=asm" (the default) is the only supported value for the + -filetype llc option.
    • +
    + +
    + + + + +
    + +
      +
    • none yet
    • +
    +
    + + + + + +
    + +
      +
    • In the JIT, dlsym() on a symbol compiled by the JIT will not + work.
    • +
    +
    + + + + + +
    Bugs
    + +
    + +

    + llvm-gcc3 has many significant problems that are fixed by llvm-gcc4. + Two major ones include:

    + +
      +
    • With llvm-gcc3, + C99 variable sized arrays do not release stack memory when they go out of + scope. Thus, the following program may run out of stack space: +
      +     for (i = 0; i != 1000000; ++i) {
      +       int X[n];
      +       foo(X);
      +     }
      + 
    • + +
    • With llvm-gcc3, Initialization of global union variables can only be done with the largest union member.
    • + +
    + +

    llvm-gcc4 is far more stable and produces better code than llvm-gcc3, but + does not currently support Link-Time-Optimization or C++ Exception Handling, + which llvm-gcc3 does.

    + +
    + + +
    + Notes +
    + +
    + +
      + +
    • "long double" is transformed by the front-end into "double". There is no + support for floating point data types of any size other than 32 and 64 + bits.
    • + +
    • The following Unix system functionality has not been tested and may not + work: +
        +
      1. sigsetjmp, siglongjmp - These are not turned into the + appropriate invoke/unwind instructions. Note that + setjmp and longjmp are compiled correctly. +
      2. getcontext, setcontext, makecontext + - These functions have not been tested. +
    • + +
    • Although many GCC extensions are supported, some are not. In particular, + the following extensions are known to not be supported: +
        +
      1. Local Labels: Labels local to a block.
      2. +
      3. Nested Functions: As in Algol and Pascal, lexical scoping of functions.
      4. +
      5. Constructing Calls: Dispatching a call to another function.
      6. +
      7. Extended Asm: Assembler instructions with C expressions as operands.
      8. +
      9. Constraints: Constraints for asm operands.
      10. +
      11. Asm Labels: Specifying the assembler name to use for a C symbol.
      12. +
      13. Explicit Reg Vars: Defining variables residing in specified registers.
      14. +
      15. Vector Extensions: Using vector instructions through built-in functions.
      16. +
      17. Target Builtins: Built-in functions specific to particular targets.
      18. +
      19. Thread-Local: Per-thread variables.
      20. +
      21. Pragmas: Pragmas accepted by GCC.
      22. +
      + +

      The following GCC extensions are partially supported. An ignored + attribute means that the LLVM compiler ignores the presence of the attribute, + but the code should still work. An unsupported attribute is one which is + ignored by the LLVM compiler and will cause a different interpretation of + the program.

      + +
        +
      1. Variable Length: + Arrays whose length is computed at run time.
        + Supported, but allocated stack space is not freed until the function returns (noted above).
      2. + +
      3. Function Attributes: + + Declaring that functions have no side effects or that they can never + return.
        + + Supported: format, format_arg, non_null, + noreturn, constructor, destructor, + unused, used, + deprecated, warn_unused_result, weak
        + + Ignored: noinline, + always_inline, pure, const, nothrow, + malloc, no_instrument_function, cdecl
        + + Unsupported: section, alias, + visibility, regparm, stdcall, + fastcall, all other target specific attributes
      4. + +
      5. Variable Attributes: + Specifying attributes of variables.
        + Supported: cleanup, common, nocommon, + deprecated, transparent_union, + unused, used, weak
        + + Unsupported: aligned, mode, packed, + section, shared, tls_model, + vector_size, dllimport, + dllexport, all target specific attributes.
      6. + +
      7. Type Attributes: Specifying attributes of types.
        + Supported: transparent_union, unused, + deprecated, may_alias
        + + Unsupported: aligned, packed, + all target specific attributes.
      8. + +
      9. Other Builtins: + Other built-in functions.
        + We support all builtins which have a C language equivalent (e.g., + __builtin_cos), __builtin_alloca, + __builtin_types_compatible_p, __builtin_choose_expr, + __builtin_constant_p, and __builtin_expect + (currently ignored). We also support builtins for ISO C99 floating + point comparison macros (e.g., __builtin_islessequal), + __builtin_prefetch, __builtin_popcount[ll], + __builtin_clz[ll], and __builtin_ctz[ll].
      10. +
      + +

      The following extensions are known to be supported:

      + +
        +
      1. Labels as Values: Getting pointers to labels and computed gotos.
      2. +
      3. Statement Exprs: Putting statements and declarations inside expressions.
      4. +
      5. Typeof: typeof: referring to the type of an expression.
      6. +
      7. Lvalues: Using ?:, "," and casts in lvalues.
      8. +
      9. Conditionals: Omitting the middle operand of a ?: expression.
      10. +
      11. Long Long: Double-word integers.
      12. +
      13. Complex: Data types for complex numbers.
      14. +
      15. Hex Floats:Hexadecimal floating-point constants.
      16. +
      17. Zero Length: Zero-length arrays.
      18. +
      19. Empty Structures: Structures with no members.
      20. +
      21. Variadic Macros: Macros with a variable number of arguments.
      22. +
      23. Escaped Newlines: Slightly looser rules for escaped newlines.
      24. +
      25. Subscripting: Any array can be subscripted, even if not an lvalue.
      26. +
      27. Pointer Arith: Arithmetic on void-pointers and function pointers.
      28. +
      29. Initializers: Non-constant initializers.
      30. +
      31. Compound Literals: Compound literals give structures, unions, + or arrays as values.
      32. +
      33. Designated Inits: Labeling elements of initializers.
      34. +
      35. Cast to Union: Casting to union type from any member of the union.
      36. +
      37. Case Ranges: `case 1 ... 9' and such.
      38. +
      39. Mixed Declarations: Mixing declarations and code.
      40. +
      41. Function Prototypes: Prototype declarations and old-style definitions.
      42. +
      43. C++ Comments: C++ comments are recognized.
      44. +
      45. Dollar Signs: Dollar sign is allowed in identifiers.
      46. +
      47. Character Escapes: \e stands for the character <ESC>.
      48. +
      49. Alignment: Inquiring about the alignment of a type or variable.
      50. +
      51. Inline: Defining inline functions (as fast as macros).
      52. +
      53. Alternate Keywords:__const__, __asm__, etc., for header files.
      54. +
      55. Incomplete Enums: enum foo;, with details to follow.
      56. +
      57. Function Names: Printable strings which are the name of the current function.
      58. +
      59. Return Address: Getting the return or frame address of a function.
      60. +
      61. Unnamed Fields: Unnamed struct/union fields within structs/unions.
      62. +
      63. Attribute Syntax: Formal syntax for attributes.
      64. +
    • + +
    + +

    If you run into GCC extensions which have not been included in any of these + lists, please let us know (also including whether or not they work).

    + +
    + + + + +
    + +

    For this release, the C++ front-end is considered to be fully + tested and works for a number of non-trivial programs, including LLVM + itself.

    + +
    + + +
    Bugs
    + +
    + +
      +
    • The C++ front-end inherits all problems afflicting the C + front-end.
    • + +
    + +
    + + +
    + Notes +
    + +
    + +
      + +
    • Destructors for local objects are not always run when a longjmp is + performed. In particular, destructors for objects in the longjmping + function and in the setjmp receiver function may not be run. + Objects in intervening stack frames will be destroyed, however (which is + better than most compilers).
    • + +
    • The LLVM C++ front-end follows the Itanium C++ ABI. + This document, which is not Itanium specific, specifies a standard for name + mangling, class layout, v-table layout, RTTI formats, and other C++ + representation issues. Because we use this API, code generated by the LLVM + compilers should be binary compatible with machine code generated by other + Itanium ABI C++ compilers (such as G++, the Intel and HP compilers, etc). + However, the exception handling mechanism used by LLVM is very + different from the model used in the Itanium ABI, so exceptions will not + interact correctly.
    • + +
    + +
    + + + + +
    + +
      + +
    • The C back-end produces code that violates the ANSI C Type-Based Alias + Analysis rules. As such, special options may be necessary to compile the code + (for example, GCC requires the -fno-strict-aliasing option). This + problem probably cannot be fixed.
    • + +
    • Zero arg vararg functions are not + supported. This should not affect LLVM produced by the C or C++ + frontends.
    • + +
    • The C backend does not correctly implement the llvm.stacksave or + llvm.stackrestore + intrinsics. This means that some code compiled by it can run out of stack + space if they depend on these (e.g. C99 varargs).
    • + +
    + +
    + + + + +
    + +
      +
    • none yet.
    • +
    + +
    + + + + + + + + + +
    + +
      + +
    • On 21164s, some rare FP arithmetic sequences which may trap do not have the + appropriate nops inserted to ensure restartability.
    • + +
    + +
    + + + + +
    + +
      + +
    • C++ programs are likely to fail on IA64, as calls to setjmp are + made where the argument is not 16-byte aligned, as required on IA64. (Strictly + speaking this is not a bug in the IA64 back-end; it will also be encountered + when building C++ programs using the C back-end.)
    • + +
    • The C++ front-end does not use IA64 + ABI compliant layout of v-tables. In particular, it just stores function + pointers instead of function descriptors in the vtable. This bug prevents + mixing C++ code compiled with LLVM with C++ objects compiled by other C++ + compilers.
    • + +
    • There are a few ABI violations which will lead to problems when mixing LLVM + output with code built with other compilers, particularly for floating-point + programs.
    • + +
    • Defining vararg functions is not supported (but calling them is ok).
    • + +
    + +
    + + + + +
    + +
      +
    • The SPARC backend only supports the 32-bit SPARC ABI (-m32), it does not + support the 64-bit SPARC ABI (-m64).
    • +
    + +
    + + + + +
    + +
      +
    • The ARM backend is currently in early development stages, it is not + ready for production use.
    • +
    + +
    + + + + + +
    + +

    A wide variety of additional information is available on the LLVM web page, including documentation and publications describing algorithms and + components implemented in LLVM. The web page also contains versions of the + API documentation which is up-to-date with the CVS version of the source code. + You can access versions of these documents specific to this release by going + into the "llvm/doc/" directory in the LLVM tree.

    + +

    If you have any questions or comments about LLVM, please feel free to contact + us via the mailing + lists.

    + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/SourceLevelDebugging.html diff -c /dev/null llvm-www/releases/1.8/docs/SourceLevelDebugging.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/SourceLevelDebugging.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,1762 ---- + + + + Source Level Debugging with LLVM + + + + +
    Source Level Debugging with LLVM
    + + + + + +
    + + + A leafy and green bug eater +
    + +
    +

    Written by Chris Lattner + and Jim Laskey

    +
    + + + + + + +
    + +

    This document is the central repository for all information pertaining to + debug information in LLVM. It describes the actual format + that the LLVM debug information takes, which is useful for those interested + in creating front-ends or dealing directly with the information. Further, this + document provides specifc examples of what debug information for C/C++.

    + +
    + + + + +
    + +

    The idea of the LLVM debugging information is to capture how the important + pieces of the source-language's Abstract Syntax Tree map onto LLVM code. + Several design aspects have shaped the solution that appears here. The + important ones are:

    + +
      +
    • Debugging information should have very little impact on the rest of the + compiler. No transformations, analyses, or code generators should need to be + modified because of debugging information.
    • + +
    • LLVM optimizations should interact in well-defined and + easily described ways with the debugging information.
    • + +
    • Because LLVM is designed to support arbitrary programming languages, + LLVM-to-LLVM tools should not need to know anything about the semantics of the + source-level-language.
    • + +
    • Source-level languages are often widely different from one another. + LLVM should not put any restrictions of the flavor of the source-language, and + the debugging information should work with any language.
    • + +
    • With code generator support, it should be possible to use an LLVM compiler + to compile a program to native machine code and standard debugging formats. + This allows compatibility with traditional machine-code level debuggers, like + GDB or DBX.
    • + +
    + +

    The approach used by the LLVM implementation is to use a small set of intrinsic functions to define a mapping + between LLVM program objects and the source-level objects. The description of + the source-level program is maintained in LLVM global variables in an implementation-defined format (the C/C++ front-end + currently uses working draft 7 of the Dwarf 3 standard).

    + +

    When a program is being debugged, a debugger interacts with the user and + turns the stored debug information into source-language specific information. + As such, a debugger must be aware of the source-language, and is thus tied to + a specific language of family of languages.

    + +
    + + + + +
    +

    The role of debug information is to provide meta information normally + stripped away during the compilation process. This meta information provides an + llvm user a relationship between generated code and the original program source + code.

    + +

    Currently, debug information is consumed by the DwarfWriter to produce dwarf + information used by the gdb debugger. Other targets could use the same + information to produce stabs or other debug forms.

    + +

    It would also be reasonable to use debug information to feed profiling tools + for analysis of generated code, or, tools for reconstructing the original source + from generated code.

    + +

    TODO - expound a bit more.

    + +
    + + + + +
    + +

    An extremely high priority of LLVM debugging information is to make it + interact well with optimizations and analysis. In particular, the LLVM debug + information provides the following guarantees:

    + +
      + +
    • LLVM debug information always provides information to accurately read the + source-level state of the program, regardless of which LLVM optimizations + have been run, and without any modification to the optimizations themselves. + However, some optimizations may impact the ability to modify the current state + of the program with a debugger, such as setting program variables, or calling + function that have been deleted.
    • + +
    • LLVM optimizations gracefully interact with debugging information. If they + are not aware of debug information, they are automatically disabled as necessary + in the cases that would invalidate the debug info. This retains the LLVM + features making it easy to write new transformations.
    • + +
    • As desired, LLVM optimizations can be upgraded to be aware of the LLVM + debugging information, allowing them to update the debugging information as they + perform aggressive optimizations. This means that, with effort, the LLVM + optimizers could optimize debug code just as well as non-debug code.
    • + +
    • LLVM debug information does not prevent many important optimizations from + happening (for example inlining, basic block reordering/merging/cleanup, tail + duplication, etc), further reducing the amount of the compiler that eventually + is "aware" of debugging information.
    • + +
    • LLVM debug information is automatically optimized along with the rest of the + program, using existing facilities. For example, duplicate information is + automatically merged by the linker, and unused information is automatically + removed.
    • + +
    + +

    Basically, the debug information allows you to compile a program with + "-O0 -g" and get full debug information, allowing you to arbitrarily + modify the program as it executes from a debugger. Compiling a program with + "-O3 -g" gives you full debug information that is always available and + accurate for reading (e.g., you get accurate stack traces despite tail call + elimination and inlining), but you might lose the ability to modify the program + and call functions where were optimized out of the program, or inlined away + completely.

    + +
    + + + + + +
    + +

    LLVM debugging information has been carefully designed to make it possible + for the optimizer to optimize the program and debugging information without + necessarily having to know anything about debugging information. In particular, + the global constant merging pass automatically eliminates duplicated debugging + information (often caused by header files), the global dead code elimination + pass automatically deletes debugging information for a function if it decides to + delete the function, and the linker eliminates debug information when it merges + linkonce functions.

    + +

    To do this, most of the debugging information (descriptors for types, + variables, functions, source files, etc) is inserted by the language front-end + in the form of LLVM global variables. These LLVM global variables are no + different from any other global variables, except that they have a web of LLVM + intrinsic functions that point to them. If the last references to a particular + piece of debugging information are deleted (for example, by the + -globaldce pass), the extraneous debug information will automatically + become dead and be removed by the optimizer.

    + +

    Debug information is designed to be agnostic about the target debugger and + debugging information representation (e.g. DWARF/Stabs/etc). It uses a generic + machine debug information pass to decode the information that represents + variables, types, functions, namespaces, etc: this allows for arbitrary + source-language semantics and type-systems to be used, as long as there is a + module written for the target debugger to interpret the information. In + addition, debug global variables are declared in the "llvm.metadata" + section. All values declared in this section are stripped away after target + debug information is constructed and before the program object is emitted.

    + +

    To provide basic functionality, the LLVM debugger does have to make some + assumptions about the source-level language being debugged, though it keeps + these to a minimum. The only common features that the LLVM debugger assumes + exist are source files, and program objects. These abstract objects are + used by a debugger to form stack traces, show information about local + variables, etc.

    + +

    This section of the documentation first describes the representation aspects + common to any source-language. The next section + describes the data layout conventions used by the C and C++ front-ends.

    + +
    + + + + +
    +

    In consideration of the complexity and volume of debug information, LLVM + provides a specification for well formed debug global variables. The constant + value of each of these globals is one of a limited set of structures, known as + debug descriptors.

    + +

    Consumers of LLVM debug information expect the descriptors for program + objects to start in a canonical format, but the descriptors can include + additional information appended at the end that is source-language specific. All + LLVM debugging information is versioned, allowing backwards compatibility in the + case that the core structures need to change in some way. Also, all debugging + information objects start with a tag to indicate what type of object it is. The + source-language is allowed to define its own objects, by using unreserved tag + numbers. We recommend using with tags in the range 0x1000 thru 0x2000 (there is + a defined enum DW_TAG_user_base = 0x1000.)

    + +

    The fields of debug descriptors used internally by LLVM (MachineDebugInfo) + are restricted to only the simple data types int, uint, + bool, float, double, sbyte* and { }* + . References to arbitrary values are handled using a { }* and a + cast to { }* expression; typically references to other field + descriptors, arrays of descriptors or global variables.

    + +
    +   %llvm.dbg.object.type = type {
    +     uint,   ;; A tag
    +     ...
    +   }
    + 
    + +

    The first field of a descriptor is always an + uint containing a tag value identifying the content of the descriptor. + The remaining fields are specific to the descriptor. The values of tags are + loosely bound to the tag values of Dwarf information entries. However, that + does not restrict the use of the information supplied to Dwarf targets. To + facilitate versioning of debug information, the tag is augmented with the + current debug version (LLVMDebugVersion = 4 << 16 or 0x40000 or 262144.)

    + +

    The details of the various descriptors follow.

    + +
    + + + + +
    + +
    +   %llvm.dbg.anchor.type = type {
    +     uint,   ;; Tag = 0 + LLVMDebugVersion
    +     uint    ;; Tag of descriptors grouped by the anchor
    +   }
    + 
    + +

    One important aspect of the LLVM debug representation is that it allows the + LLVM debugger to efficiently index all of the global objects without having the + scan the program. To do this, all of the global objects use "anchor" + descriptors with designated names. All of the global objects of a particular + type (e.g., compile units) contain a pointer to the anchor. This pointer allows + a debugger to use def-use chains to find all global objects of that type.

    + +

    The following names are recognized as anchors by LLVM:

    + +
    +   %llvm.dbg.compile_units       = linkonce constant %llvm.dbg.anchor.type  { uint 0, uint 17 } ;; DW_TAG_compile_unit
    +   %llvm.dbg.global_variables    = linkonce constant %llvm.dbg.anchor.type  { uint 0, uint 52 } ;; DW_TAG_variable
    +   %llvm.dbg.subprograms         = linkonce constant %llvm.dbg.anchor.type  { uint 0, uint 46 } ;; DW_TAG_subprogram
    + 
    + +

    Using anchors in this way (where the compile unit descriptor points to the + anchors, as opposed to having a list of compile unit descriptors) allows for the + standard dead global elimination and merging passes to automatically remove + unused debugging information. If the globals were kept track of through lists, + there would always be an object pointing to the descriptors, thus would never be + deleted.

    + +
    + + + + +
    + +
    +   %llvm.dbg.compile_unit.type = type {
    +     uint,   ;; Tag = 17 + LLVMDebugVersion (DW_TAG_compile_unit)
    +     {  }*,  ;; Compile unit anchor = cast = (%llvm.dbg.anchor.type* %llvm.dbg.compile_units to {  }*)
    +     uint,   ;; Dwarf language identifier (ex. DW_LANG_C89) 
    +     sbyte*, ;; Source file name
    +     sbyte*, ;; Source file directory (includes trailing slash)
    +     sbyte*  ;; Producer (ex. "4.0.1 LLVM (LLVM research group)")
    +   }
    + 
    + +

    These descriptors contain a source language ID for the file (we use the Dwarf + 3.0 ID numbers, such as DW_LANG_C89, DW_LANG_C_plus_plus, + DW_LANG_Cobol74, etc), three strings describing the filename, working + directory of the compiler, and an identifier string for the compiler that + produced it.

    + +

    Compile unit descriptors provide the root context for objects declared in a + specific source file. Global variables and top level functions would be defined + using this context. Compile unit descriptors also provide context for source + line correspondence.

    + +
    + + + + +
    + +
    +   %llvm.dbg.global_variable.type = type {
    +     uint,   ;; Tag = 52 + LLVMDebugVersion (DW_TAG_variable)
    +     {  }*,  ;; Global variable anchor = cast (%llvm.dbg.anchor.type* %llvm.dbg.global_variables to {  }*),  
    +     {  }*,  ;; Reference to context descriptor
    +     sbyte*, ;; Name
    +     {  }*,  ;; Reference to compile unit where defined
    +     uint,   ;; Line number where defined
    +     {  }*,  ;; Reference to type descriptor
    +     bool,   ;; True if the global is local to compile unit (static)
    +     bool,   ;; True if the global is defined in the compile unit (not extern)
    +     {  }*   ;; Reference to the global variable
    +   }
    + 
    + +

    These descriptors provide debug information about globals variables. The + provide details such as name, type and where the variable is defined.

    + +
    + + + + +
    + +
    +   %llvm.dbg.subprogram.type = type {
    +     uint,   ;; Tag = 46 + LLVMDebugVersion (DW_TAG_subprogram)
    +     {  }*,  ;; Subprogram anchor = cast (%llvm.dbg.anchor.type* %llvm.dbg.subprograms to {  }*),  
    +     {  }*,  ;; Reference to context descriptor
    +     sbyte*, ;; Name
    +     {  }*,  ;; Reference to compile unit where defined
    +     uint,   ;; Line number where defined
    +     {  }*,  ;; Reference to type descriptor
    +     bool,   ;; True if the global is local to compile unit (static)
    +     bool    ;; True if the global is defined in the compile unit (not extern)
    +   }
    + 
    + +

    These descriptors provide debug information about functions, methods and + subprograms. They provide details such as name, return types and the source + location where the subprogram is defined.

    + +
    + + + +
    + +
    +   %llvm.dbg.block = type {
    +     uint,   ;; Tag = 13 + LLVMDebugVersion (DW_TAG_lexical_block)
    +     {  }*   ;; Reference to context descriptor
    +   }
    + 
    + +

    These descriptors provide debug information about nested blocks within a + subprogram. The array of member descriptors is used to define local variables + and deeper nested blocks.

    + +
    + + + + +
    + +
    +   %llvm.dbg.basictype.type = type {
    +     uint,   ;; Tag = 36 + LLVMDebugVersion (DW_TAG_base_type)
    +     {  }*,  ;; Reference to context (typically a compile unit)
    +     sbyte*, ;; Name (may be "" for anonymous types)
    +     {  }*,  ;; Reference to compile unit where defined (may be NULL)
    +     uint,   ;; Line number where defined (may be 0)
    +     uint,   ;; Size in bits
    +     uint,   ;; Alignment in bits
    +     uint,   ;; Offset in bits
    +     uint    ;; Dwarf type encoding
    +   }
    + 
    + +

    These descriptors define primitive types used in the code. Example int, bool + and float. The context provides the scope of the type, which is usually the top + level. Since basic types are not usually user defined the compile unit and line + number can be left as NULL and 0. The size, alignment and offset are expressed + in bits and can be 64 bit values. The alignment is used to round the offset + when embedded in a composite type + (example to keep float doubles on 64 bit boundaries.) The offset is the bit + offset if embedded in a composite + type.

    + +

    The type encoding provides the details of the type. The values are typically + one of the following;

    + +
    +   DW_ATE_address = 1
    +   DW_ATE_boolean = 2
    +   DW_ATE_float = 4
    +   DW_ATE_signed = 5
    +   DW_ATE_signed_char = 6
    +   DW_ATE_unsigned = 7
    +   DW_ATE_unsigned_char = 8
    + 
    + +
    + + + + +
    + +
    +   %llvm.dbg.derivedtype.type = type {
    +     uint,   ;; Tag (see below)
    +     {  }*,  ;; Reference to context
    +     sbyte*, ;; Name (may be "" for anonymous types)
    +     {  }*,  ;; Reference to compile unit where defined (may be NULL)
    +     uint,   ;; Line number where defined (may be 0)
    +     uint,   ;; Size in bits
    +     uint,   ;; Alignment in bits
    +     uint,   ;; Offset in bits
    +     {  }*   ;; Reference to type derived from
    +   }
    + 
    + +

    These descriptors are used to define types derived from other types. The + value of the tag varies depending on the meaning. The following are possible + tag values;

    + +
    +   DW_TAG_formal_parameter = 5
    +   DW_TAG_member = 13
    +   DW_TAG_pointer_type = 15
    +   DW_TAG_reference_type = 16
    +   DW_TAG_typedef = 22
    +   DW_TAG_const_type = 38
    +   DW_TAG_volatile_type = 53
    +   DW_TAG_restrict_type = 55
    + 
    + +

    DW_TAG_member is used to define a member of a composite type or subprogram. The type of the member is the derived type. DW_TAG_formal_parameter + is used to define a member which is a formal argument of a subprogram.

    + +

    DW_TAG_typedef is used to + provide a name for the derived type.

    + +

    DW_TAG_pointer_type, + DW_TAG_reference_type, DW_TAG_const_type, + DW_TAG_volatile_type and DW_TAG_restrict_type are used to + qualify the derived type.

    + +

    Derived type location can be determined + from the compile unit and line number. The size, alignment and offset are + expressed in bits and can be 64 bit values. The alignment is used to round the + offset when embedded in a composite type + (example to keep float doubles on 64 bit boundaries.) The offset is the bit + offset if embedded in a composite + type.

    + +

    Note that the void * type is expressed as a + llvm.dbg.derivedtype.type with tag of DW_TAG_pointer_type and + NULL derived type.

    + +
    + + + + +
    + +
    +   %llvm.dbg.compositetype.type = type {
    +     uint,   ;; Tag (see below)
    +     {  }*,  ;; Reference to context
    +     sbyte*, ;; Name (may be "" for anonymous types)
    +     {  }*,  ;; Reference to compile unit where defined (may be NULL)
    +     uint,   ;; Line number where defined (may be 0)
    +     uint,   ;; Size in bits
    +     uint,   ;; Alignment in bits
    +     uint,   ;; Offset in bits
    +     {  }*   ;; Reference to array of member descriptors
    +   }
    + 
    + +

    These descriptors are used to define types that are composed of 0 or more + elements. The value of the tag varies depending on the meaning. The following + are possible tag values;

    + +
    +   DW_TAG_array_type = 1
    +   DW_TAG_enumeration_type = 4
    +   DW_TAG_structure_type = 19
    +   DW_TAG_union_type = 23
    +   DW_TAG_vector_type = 259
    +   DW_TAG_subroutine_type = 46
    + 
    + +

    The vector flag indicates that an array type is a native packed vector.

    + +

    The members of array types (tag = DW_TAG_array_type) or vector types + (tag = DW_TAG_vector_type) are subrange + descriptors, each representing the range of subscripts at that level of + indexing.

    + +

    The members of enumeration types (tag = DW_TAG_enumeration_type) are + enumerator descriptors, each representing the + definition of enumeration value + for the set.

    + +

    The members of structure (tag = DW_TAG_structure_type) or union (tag + = DW_TAG_union_type) types are any one of the basic, derived + or composite type descriptors, each + representing a field member of the structure or union.

    + +

    The first member of subroutine (tag = DW_TAG_subroutine_type) + type elements is the return type for the subroutine. The remaining + elements are the formal arguments to the subroutine.

    + +

    Composite type location can be + determined from the compile unit and line number. The size, alignment and + offset are expressed in bits and can be 64 bit values. The alignment is used to + round the offset when embedded in a composite + type (as an example, to keep float doubles on 64 bit boundaries.) The offset + is the bit offset if embedded in a composite + type.

    + +
    + + + + +
    + +
    +   %llvm.dbg.subrange.type = type {
    +     uint,   ;; Tag = 33 + LLVMDebugVersion (DW_TAG_subrange_type)
    +     uint,   ;; Low value
    +     uint    ;; High value
    +   }
    + 
    + +

    These descriptors are used to define ranges of array subscripts for an array + composite type. The low value defines the + lower bounds typically zero for C/C++. The high value is the upper bounds. + Values are 64 bit. High - low + 1 is the size of the array. If + low == high the array will be unbounded.

    + +
    + + + + +
    + +
    +   %llvm.dbg.enumerator.type = type {
    +     uint,   ;; Tag = 40 + LLVMDebugVersion (DW_TAG_enumerator)
    +     sbyte*, ;; Name
    +     uint    ;; Value
    +   }
    + 
    + +

    These descriptors are used to define members of an enumeration composite type, it associates the name to the + value.

    + +
    + + + + +
    +
    +   %llvm.dbg.variable.type = type {
    +     uint,    ;; Tag (see below)
    +     {  }*,   ;; Context
    +     sbyte*,  ;; Name
    +     {  }*,   ;; Reference to compile unit where defined
    +     uint,    ;; Line number where defined
    +     {  }*    ;; Type descriptor
    +   }
    + 
    + +

    These descriptors are used to define variables local to a sub program. The + value of the tag depends on the usage of the variable;

    + +
    +   DW_TAG_auto_variable = 256
    +   DW_TAG_arg_variable = 257
    +   DW_TAG_return_variable = 258
    + 
    + +

    An auto variable is any variable declared in the body of the function. An + argument variable is any variable that appears as a formal argument to the + function. A return variable is used to track the result of a function and has + no source correspondent.

    + +

    The context is either the subprogram or block where the variable is defined. + Name the source variable name. Compile unit and line indicate where the + variable was defined. Type descriptor defines the declared type of the + variable.

    + +
    + + + + +
    + +

    LLVM uses several intrinsic functions (name prefixed with "llvm.dbg") to + provide debug information at various points in generated code.

    + +
    + + + + +
    +
    +   void %llvm.dbg.stoppoint( uint, uint, { }* )
    + 
    + +

    This intrinsic is used to provide correspondence between the source file and + the generated code. The first argument is the line number (base 1), second + argument si the column number (0 if unknown) and the third argument the source + %llvm.dbg.compile_unit* cast to a + { }*. Code following a call to this intrinsic will have been defined + in close proximity of the line, column and file. This information holds until + the next call to %lvm.dbg.stoppoint.

    + +
    + + + + +
    +
    +   void %llvm.dbg.func.start( { }* )
    + 
    + +

    This intrinsic is used to link the debug information in %llvm.dbg.subprogram to the function. It also + defines the beginning of the function's declarative region (scope.) The + intrinsic should be called early in the function after the all the alloca + instructions. It should be paired off with a closing %llvm.dbg.region.end. The function's + single argument is the %llvm.dbg.subprogram.type.

    + +
    + + + + +
    +
    +   void %llvm.dbg.region.start( { }* )
    + 
    + +

    This intrinsic is used to define the beginning of a declarative scope (ex. + block) for local language elements. It should be paired off with a closing + %llvm.dbg.region.end. The + function's single argument is the %llvm.dbg.block which is starting.

    + + +
    + + + + +
    +
    +   void %llvm.dbg.region.end( { }* )
    + 
    + +

    This intrinsic is used to define the end of a declarative scope (ex. block) + for local language elements. It should be paired off with an opening %llvm.dbg.region.start or %llvm.dbg.func.start. The function's + single argument is either the %llvm.dbg.block or the %llvm.dbg.subprogram.type which is + ending.

    + +
    + + + + +
    +
    +   void %llvm.dbg.declare( { } *, { }* )
    + 
    + +

    This intrinsic provides information about a local element (ex. variable.) The + first argument is the alloca for the variable, cast to a { }*. The + second argument is the %llvm.dbg.variable containing the description + of the variable, also cast to a { }*.

    + +
    + + + + +
    + +

    LLVM debugger "stop points" are a key part of the debugging representation + that allows the LLVM to maintain simple semantics for debugging optimized code. The basic idea is that the + front-end inserts calls to the %llvm.dbg.stoppoint intrinsic + function at every point in the program where a debugger should be able to + inspect the program (these correspond to places a debugger stops when you + "step" through it). The front-end can choose to place these as + fine-grained as it would like (for example, before every subexpression + evaluated), but it is recommended to only put them after every source statement + that includes executable code.

    + +

    Using calls to this intrinsic function to demark legal points for the + debugger to inspect the program automatically disables any optimizations that + could potentially confuse debugging information. To non-debug-information-aware + transformations, these calls simply look like calls to an external function, + which they must assume to do anything (including reading or writing to any part + of reachable memory). On the other hand, it does not impact many optimizations, + such as code motion of non-trapping instructions, nor does it impact + optimization of subexpressions, code duplication transformations, or basic-block + reordering transformations.

    + +
    + + + + + +
    +

    In many languages, the local variables in functions can have their lifetime + or scope limited to a subset of a function. In the C family of languages, for + example, variables are only live (readable and writable) within the source block + that they are defined in. In functional languages, values are only readable + after they have been defined. Though this is a very obvious concept, it is also + non-trivial to model in LLVM, because it has no notion of scoping in this sense, + and does not want to be tied to a language's scoping rules.

    + +

    In order to handle this, the LLVM debug format uses the notion of "regions" + of a function, delineated by calls to intrinsic functions. These intrinsic + functions define new regions of the program and indicate when the region + lifetime expires. Consider the following C fragment, for example:

    + +
    + 1.  void foo() {
    + 2.    int X = ...;
    + 3.    int Y = ...;
    + 4.    {
    + 5.      int Z = ...;
    + 6.      ...
    + 7.    }
    + 8.    ...
    + 9.  }
    + 
    + +

    Compiled to LLVM, this function would be represented like this:

    + +
    + void %foo() {
    + entry:
    +     %X = alloca int
    +     %Y = alloca int
    +     %Z = alloca int
    +     
    +     ...
    +     
    +     call void %llvm.dbg.func.start( %llvm.dbg.subprogram.type* %llvm.dbg.subprogram )
    +     
    +     call void %llvm.dbg.stoppoint( uint 2, uint 2, %llvm.dbg.compile_unit* %llvm.dbg.compile_unit )
    +     
    +     call void %llvm.dbg.declare({}* %X, ...)
    +     call void %llvm.dbg.declare({}* %Y, ...)
    +     
    +     ;; Evaluate expression on line 2, assigning to X.
    +     
    +     call void %llvm.dbg.stoppoint( uint 3, uint 2, %llvm.dbg.compile_unit* %llvm.dbg.compile_unit )
    +     
    +     ;; Evaluate expression on line 3, assigning to Y.
    +     
    +     call void %llvm.region.start()
    +     call void %llvm.dbg.stoppoint( uint 5, uint 4, %llvm.dbg.compile_unit* %llvm.dbg.compile_unit )
    +     call void %llvm.dbg.declare({}* %X, ...)
    +     
    +     ;; Evaluate expression on line 5, assigning to Z.
    +     
    +     call void %llvm.dbg.stoppoint( uint 7, uint 2, %llvm.dbg.compile_unit* %llvm.dbg.compile_unit )
    +     call void %llvm.region.end()
    +     
    +     call void %llvm.dbg.stoppoint( uint 9, uint 2, %llvm.dbg.compile_unit* %llvm.dbg.compile_unit )
    +     
    +     call void %llvm.region.end()
    +     
    +     ret void
    + }
    + 
    + +

    This example illustrates a few important details about the LLVM debugging + information. In particular, it shows how the various intrinsics are applied + together to allow a debugger to analyze the relationship between statements, + variable definitions, and the code used to implement the function.

    + +

    The first intrinsic %llvm.dbg.func.start provides + a link with the subprogram descriptor + containing the details of this function. This call also defines the beginning + of the function region, bounded by the %llvm.region.end at the end of + the function. This region is used to bracket the lifetime of variables declared + within. For a function, this outer region defines a new stack frame whose + lifetime ends when the region is ended.

    + +

    It is possible to define inner regions for short term variables by using the + %llvm.region.start and %llvm.region.end to bound a + region. The inner region in this example would be for the block containing the + declaration of Z.

    + +

    Using regions to represent the boundaries of source-level functions allow + LLVM interprocedural optimizations to arbitrarily modify LLVM functions without + having to worry about breaking mapping information between the LLVM code and the + and source-level program. In particular, the inliner requires no modification + to support inlining with debugging information: there is no explicit correlation + drawn between LLVM functions and their source-level counterparts (note however, + that if the inliner inlines all instances of a non-strong-linkage function into + its caller that it will not be possible for the user to manually invoke the + inlined function from a debugger).

    + +

    Once the function has been defined, the stopping point corresponding to + line #2 (column #2) of the function is encountered. At this point in the + function, no local variables are live. As lines 2 and 3 of the example + are executed, their variable definitions are introduced into the program using + %llvm.dbg.declare, without the + need to specify a new region. These variables do not require new regions to be + introduced because they go out of scope at the same point in the program: line + 9.

    + +

    In contrast, the Z variable goes out of scope at a different time, + on line 7. For this reason, it is defined within the inner region, which kills + the availability of Z before the code for line 8 is executed. In this + way, regions can support arbitrary source-language scoping rules, as long as + they can only be nested (ie, one scope cannot partially overlap with a part of + another scope).

    + +

    It is worth noting that this scoping mechanism is used to control scoping of + all declarations, not just variable declarations. For example, the scope of a + C++ using declaration is controlled with this couldchange how name lookup is + performed.

    + +
    + + + + + + + +
    + +

    The C and C++ front-ends represent information about the program in a format + that is effectively identical to Dwarf 3.0 in terms of + information content. This allows code generators to trivially support native + debuggers by generating standard dwarf information, and contains enough + information for non-dwarf targets to translate it as needed.

    + +

    This section describes the forms used to represent C and C++ programs. Other + languages could pattern themselves after this (which itself is tuned to + representing programs in the same way that Dwarf 3 does), or they could choose + to provide completely different forms if they don't fit into the Dwarf model. + As support for debugging information gets added to the various LLVM + source-language front-ends, the information used should be documented here.

    + +

    The following sections provide examples of various C/C++ constructs and the + debug information that would best describe those constructs.

    + +
    + + + + +
    + +

    Given the source files "MySource.cpp" and "MyHeader.h" located in the + directory "/Users/mine/sources", the following code;

    + +
    + #include "MyHeader.h"
    + 
    + int main(int argc, char *argv[]) {
    +   return 0;
    + }
    + 
    + +

    a C/C++ front-end would generate the following descriptors;

    + +
    + ...
    + ;;
    + ;; Define types used.  In this case we need one for compile unit anchors and one
    + ;; for compile units.
    + ;;
    + %llvm.dbg.anchor.type = type { uint, uint }
    + %llvm.dbg.compile_unit.type = type { uint, {  }*, uint, uint, sbyte*, sbyte*, sbyte* }
    + ...
    + ;;
    + ;; Define the anchor for compile units.  Note that the second field of the
    + ;; anchor is 17, which is the same as the tag for compile units
    + ;; (17 = DW_TAG_compile_unit.)
    + ;;
    + %llvm.dbg.compile_units = linkonce constant %llvm.dbg.anchor.type { uint 0, uint 17 }, section "llvm.metadata"
    + 
    + ;;
    + ;; Define the compile unit for the source file "/Users/mine/sources/MySource.cpp".
    + ;;
    + %llvm.dbg.compile_unit1 = internal constant %llvm.dbg.compile_unit.type {
    +     uint add(uint 17, uint 262144), 
    +     {  }* cast (%llvm.dbg.anchor.type* %llvm.dbg.compile_units to {  }*), 
    +     uint 1, 
    +     uint 1, 
    +     sbyte* getelementptr ([13 x sbyte]* %str1, int 0, int 0), 
    +     sbyte* getelementptr ([21 x sbyte]* %str2, int 0, int 0), 
    +     sbyte* getelementptr ([33 x sbyte]* %str3, int 0, int 0) }, section "llvm.metadata"
    +     
    + ;;
    + ;; Define the compile unit for the header file "/Users/mine/sources/MyHeader.h".
    + ;;
    + %llvm.dbg.compile_unit2 = internal constant %llvm.dbg.compile_unit.type {
    +     uint add(uint 17, uint 262144), 
    +     {  }* cast (%llvm.dbg.anchor.type* %llvm.dbg.compile_units to {  }*), 
    +     uint 1, 
    +     uint 1, 
    +     sbyte* getelementptr ([11 x sbyte]* %str4, int 0, int 0), 
    +     sbyte* getelementptr ([21 x sbyte]* %str2, int 0, int 0), 
    +     sbyte* getelementptr ([33 x sbyte]* %str3, int 0, int 0) }, section "llvm.metadata"
    + 
    + ;;
    + ;; Define each of the strings used in the compile units.
    + ;;
    + %str1 = internal constant [13 x sbyte] c"MySource.cpp\00", section "llvm.metadata";
    + %str2 = internal constant [21 x sbyte] c"/Users/mine/sources/\00", section "llvm.metadata";
    + %str3 = internal constant [33 x sbyte] c"4.0.1 LLVM (LLVM research group)\00", section "llvm.metadata";
    + %str4 = internal constant [11 x sbyte] c"MyHeader.h\00", section "llvm.metadata";
    + ...
    + 
    + +
    + + + + +
    + +

    Given an integer global variable declared as follows;

    + +
    + int MyGlobal = 100;
    + 
    + +

    a C/C++ front-end would generate the following descriptors;

    + +
    + ;;
    + ;; Define types used. One for global variable anchors, one for the global
    + ;; variable descriptor, one for the global's basic type and one for the global's
    + ;; compile unit.
    + ;;
    + %llvm.dbg.anchor.type = type { uint, uint }
    + %llvm.dbg.global_variable.type = type { uint, {  }*, {  }*, sbyte*, {  }*, uint, {  }*, bool, bool, {  }*, uint }
    + %llvm.dbg.basictype.type = type { uint, {  }*, sbyte*, {  }*, int, uint, uint, uint, uint }
    + %llvm.dbg.compile_unit.type = ...
    + ...
    + ;;
    + ;; Define the global itself.
    + ;;
    + %MyGlobal = global int 100
    + ...
    + ;;
    + ;; Define the anchor for global variables.  Note that the second field of the
    + ;; anchor is 52, which is the same as the tag for global variables
    + ;; (52 = DW_TAG_variable.)
    + ;;
    + %llvm.dbg.global_variables = linkonce constant %llvm.dbg.anchor.type { uint 0, uint 52 }, section "llvm.metadata"
    + 
    + ;;
    + ;; Define the global variable descriptor.  Note the reference to the global
    + ;; variable anchor and the global variable itself.
    + ;;
    + %llvm.dbg.global_variable = internal constant %llvm.dbg.global_variable.type {
    +     uint add(uint 52, uint 262144), 
    +     {  }* cast (%llvm.dbg.anchor.type* %llvm.dbg.global_variables to {  }*), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([9 x sbyte]* %str1, int 0, int 0), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     uint 1,
    +     {  }* cast (%llvm.dbg.basictype.type* %llvm.dbg.basictype to {  }*), 
    +     bool false, 
    +     bool true, 
    +     {  }* cast (int* %MyGlobal to {  }*) }, section "llvm.metadata"
    +     
    + ;;
    + ;; Define the basic type of 32 bit signed integer.  Note that since int is an
    + ;; intrinsic type the source file is NULL and line 0.
    + ;;    
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([4 x sbyte]* %str2, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     uint 5 }, section "llvm.metadata"
    + 
    + ;;
    + ;; Define the names of the global variable and basic type.
    + ;;
    + %str1 = internal constant [9 x sbyte] c"MyGlobal\00", section "llvm.metadata"
    + %str2 = internal constant [4 x sbyte] c"int\00", section "llvm.metadata"
    + 
    + +
    + + + + +
    + +

    Given a function declared as follows;

    + +
    + int main(int argc, char *argv[]) {
    +   return 0;
    + }
    + 
    + +

    a C/C++ front-end would generate the following descriptors;

    + +
    + ;;
    + ;; Define types used. One for subprogram anchors, one for the subprogram
    + ;; descriptor, one for the global's basic type and one for the subprogram's
    + ;; compile unit.
    + ;;
    + %llvm.dbg.subprogram.type = type { uint, {  }*, {  }*, sbyte*, {  }*, bool, bool }
    + %llvm.dbg.anchor.type = type { uint, uint }
    + %llvm.dbg.compile_unit.type = ...
    + 	
    + ;;
    + ;; Define the anchor for subprograms.  Note that the second field of the
    + ;; anchor is 46, which is the same as the tag for subprograms
    + ;; (46 = DW_TAG_subprogram.)
    + ;;
    + %llvm.dbg.subprograms = linkonce constant %llvm.dbg.anchor.type { uint 0, uint 46 }, section "llvm.metadata"
    + 
    + ;;
    + ;; Define the descriptor for the subprogram.  TODO - more details.
    + ;;
    + %llvm.dbg.subprogram = internal constant %llvm.dbg.subprogram.type {
    +     uint add(uint 46, uint 262144), 
    +     {  }* cast (%llvm.dbg.anchor.type* %llvm.dbg.subprograms to {  }*), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([5 x sbyte]* %str1, int 0, int 0), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*),
    +     uint 1,
    +     {  }* null, 
    +     bool false, 
    +     bool true }, section "llvm.metadata"
    + 
    + ;;
    + ;; Define the name of the subprogram.
    + ;;
    + %str1 = internal constant [5 x sbyte] c"main\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define the subprogram itself.
    + ;;
    + int %main(int %argc, sbyte** %argv) {
    + ...
    + }
    + 
    + +
    + + + + +
    + +

    The following are the basic type descriptors for C/C++ core types;

    + +
    + + +
    + bool +
    + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([5 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     uint 2 }, section "llvm.metadata"
    + %str1 = internal constant [5 x sbyte] c"bool\00", section "llvm.metadata"
    + 
    + +
    + + +
    + char +
    + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([5 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 8, 
    +     uint 8, 
    +     uint 0, 
    +     uint 6 }, section "llvm.metadata"
    + %str1 = internal constant [5 x sbyte] c"char\00", section "llvm.metadata"
    + 
    + +
    + + + + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([14 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 8, 
    +     uint 8, 
    +     uint 0, 
    +     uint 8 }, section "llvm.metadata"
    + %str1 = internal constant [14 x sbyte] c"unsigned char\00", section "llvm.metadata"
    + 
    + +
    + + +
    + short +
    + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([10 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 16, 
    +     uint 16, 
    +     uint 0, 
    +     uint 5 }, section "llvm.metadata"
    + %str1 = internal constant [10 x sbyte] c"short int\00", section "llvm.metadata"
    + 
    + +
    + + + + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([19 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 16, 
    +     uint 16, 
    +     uint 0, 
    +     uint 7 }, section "llvm.metadata"
    + %str1 = internal constant [19 x sbyte] c"short unsigned int\00", section "llvm.metadata"
    + 
    + +
    + + +
    + int +
    + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([4 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     uint 5 }, section "llvm.metadata"
    + %str1 = internal constant [4 x sbyte] c"int\00", section "llvm.metadata"
    + 
    + +
    + + + + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([13 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     uint 7 }, section "llvm.metadata"
    + %str1 = internal constant [13 x sbyte] c"unsigned int\00", section "llvm.metadata"
    + 
    + +
    + + +
    + long long +
    + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([14 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 64, 
    +     uint 64, 
    +     uint 0, 
    +     uint 5 }, section "llvm.metadata"
    + %str1 = internal constant [14 x sbyte] c"long long int\00", section "llvm.metadata"
    + 
    + +
    + + + + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([23 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 64, 
    +     uint 64, 
    +     uint 0, 
    +     uint 7 }, section "llvm.metadata"
    + %str1 = internal constant [23 x sbyte] c"long long unsigned int\00", section "llvm.metadata"
    + 
    + +
    + + +
    + float +
    + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([6 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     uint 4 }, section "llvm.metadata"
    + %str1 = internal constant [6 x sbyte] c"float\00", section "llvm.metadata"
    + 
    + +
    + + +
    + double +
    + +
    + +
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([7 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 64, 
    +     uint 64, 
    +     uint 0, 
    +     uint 4 }, section "llvm.metadata"
    + %str1 = internal constant [7 x sbyte] c"double\00", section "llvm.metadata"
    + 
    + +
    + + + + +
    + +

    Given the following as an example of C/C++ derived type;

    + +
    + typedef const int *IntPtr;
    + 
    + +

    a C/C++ front-end would generate the following descriptors;

    + +
    + ;;
    + ;; Define the typedef "IntPtr".
    + ;;
    + %llvm.dbg.derivedtype1 = internal constant %llvm.dbg.derivedtype.type {
    +     uint add(uint 22, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([7 x sbyte]* %str1, int 0, int 0), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     int 1, 
    +     uint 0, 
    +     uint 0, 
    +     uint 0, 
    +     {  }* cast (%llvm.dbg.derivedtype.type* %llvm.dbg.derivedtype2 to {  }*) }, section "llvm.metadata"
    + %str1 = internal constant [7 x sbyte] c"IntPtr\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define the pointer type.
    + ;;
    + %llvm.dbg.derivedtype2 = internal constant %llvm.dbg.derivedtype.type {
    +     uint add(uint 15, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* null, 
    +     {  }* null, 
    +     int 0, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     {  }* cast (%llvm.dbg.derivedtype.type* %llvm.dbg.derivedtype3 to {  }*) }, section "llvm.metadata"
    + 
    + ;;
    + ;; Define the const type.
    + ;;
    + %llvm.dbg.derivedtype3 = internal constant %llvm.dbg.derivedtype.type {
    +     uint add(uint 38, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* null, 
    +     {  }* null, 
    +     int 0, 
    +     uint 0, 
    +     uint 0, 
    +     uint 0, 
    +     {  }* cast (%llvm.dbg.basictype.type* %llvm.dbg.basictype1 to {  }*) }, section "llvm.metadata"	
    + 
    + ;;
    + ;; Define the int type.
    + ;;
    + %llvm.dbg.basictype1 = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([4 x sbyte]* %str2, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     uint 5 }, section "llvm.metadata"
    + %str2 = internal constant [4 x sbyte] c"int\00", section "llvm.metadata"
    + 
    + +
    + + + + +
    + +

    Given the following as an example of C/C++ struct type;

    + +
    + struct Color {
    +   unsigned Red;
    +   unsigned Green;
    +   unsigned Blue;
    + };
    + 
    + +

    a C/C++ front-end would generate the following descriptors;

    + +
    + ;;
    + ;; Define basic type for unsigned int.
    + ;;
    + %llvm.dbg.basictype = internal constant %llvm.dbg.basictype.type {
    +     uint add(uint 36, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([13 x sbyte]* %str1, int 0, int 0), 
    +     {  }* null, 
    +     int 0, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     uint 7 }, section "llvm.metadata"
    + %str1 = internal constant [13 x sbyte] c"unsigned int\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define composite type for struct Color.
    + ;;
    + %llvm.dbg.compositetype = internal constant %llvm.dbg.compositetype.type {
    +     uint add(uint 19, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([6 x sbyte]* %str2, int 0, int 0), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     int 1, 
    +     uint 96, 
    +     uint 32, 
    +     uint 0, 
    +     {  }* null,
    +     {  }* cast ([3 x {  }*]* %llvm.dbg.array to {  }*) }, section "llvm.metadata"
    + %str2 = internal constant [6 x sbyte] c"Color\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define the Red field.
    + ;;
    + %llvm.dbg.derivedtype1 = internal constant %llvm.dbg.derivedtype.type {
    +     uint add(uint 13, uint 262144), 
    +     {  }* null, 
    +     sbyte* getelementptr ([4 x sbyte]* %str3, int 0, int 0), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     int 2, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     {  }* cast (%llvm.dbg.basictype.type* %llvm.dbg.basictype to {  }*) }, section "llvm.metadata"
    + %str3 = internal constant [4 x sbyte] c"Red\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define the Green field.
    + ;;
    + %llvm.dbg.derivedtype2 = internal constant %llvm.dbg.derivedtype.type {
    +     uint add(uint 13, uint 262144), 
    +     {  }* null, 
    +     sbyte* getelementptr ([6 x sbyte]* %str4, int 0, int 0), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     int 3, 
    +     uint 32, 
    +     uint 32, 
    +     uint 32, 
    +     {  }* cast (%llvm.dbg.basictype.type* %llvm.dbg.basictype to {  }*) }, section "llvm.metadata"
    + %str4 = internal constant [6 x sbyte] c"Green\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define the Blue field.
    + ;;
    + %llvm.dbg.derivedtype3 = internal constant %llvm.dbg.derivedtype.type {
    +     uint add(uint 13, uint 262144), 
    +     {  }* null, 
    +     sbyte* getelementptr ([5 x sbyte]* %str5, int 0, int 0), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     int 4, 
    +     uint 32, 
    +     uint 32, 
    +     uint 64, 
    +     {  }* cast (%llvm.dbg.basictype.type* %llvm.dbg.basictype to {  }*) }, section "llvm.metadata"
    + %str5 = internal constant [5 x sbyte] c"Blue\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define the array of fields used by the composite type Color.
    + ;;
    + %llvm.dbg.array = internal constant [3 x {  }*] [
    +       {  }* cast (%llvm.dbg.derivedtype.type* %llvm.dbg.derivedtype1 to {  }*),
    +       {  }* cast (%llvm.dbg.derivedtype.type* %llvm.dbg.derivedtype2 to {  }*),
    +       {  }* cast (%llvm.dbg.derivedtype.type* %llvm.dbg.derivedtype3 to {  }*) ], section "llvm.metadata"
    + 
    + +
    + + + + +
    + +

    Given the following as an example of C/C++ enumeration type;

    + +
    + enum Trees {
    +   Spruce = 100,
    +   Oak = 200,
    +   Maple = 300
    + };
    + 
    + +

    a C/C++ front-end would generate the following descriptors;

    + +
    + ;;
    + ;; Define composite type for enum Trees
    + ;;
    + %llvm.dbg.compositetype = internal constant %llvm.dbg.compositetype.type {
    +     uint add(uint 4, uint 262144), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     sbyte* getelementptr ([6 x sbyte]* %str1, int 0, int 0), 
    +     {  }* cast (%llvm.dbg.compile_unit.type* %llvm.dbg.compile_unit to {  }*), 
    +     int 1, 
    +     uint 32, 
    +     uint 32, 
    +     uint 0, 
    +     {  }* null, 
    +     {  }* cast ([3 x {  }*]* %llvm.dbg.array to {  }*) }, section "llvm.metadata"
    + %str1 = internal constant [6 x sbyte] c"Trees\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define Spruce enumerator.
    + ;;
    + %llvm.dbg.enumerator1 = internal constant %llvm.dbg.enumerator.type {
    +     uint add(uint 40, uint 262144), 
    +     sbyte* getelementptr ([7 x sbyte]* %str2, int 0, int 0), 
    +     int 100 }, section "llvm.metadata"
    + %str2 = internal constant [7 x sbyte] c"Spruce\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define Oak enumerator.
    + ;;
    + %llvm.dbg.enumerator2 = internal constant %llvm.dbg.enumerator.type {
    +     uint add(uint 40, uint 262144), 
    +     sbyte* getelementptr ([4 x sbyte]* %str3, int 0, int 0), 
    +     int 200 }, section "llvm.metadata"
    + %str3 = internal constant [4 x sbyte] c"Oak\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define Maple enumerator.
    + ;;
    + %llvm.dbg.enumerator3 = internal constant %llvm.dbg.enumerator.type {
    +     uint add(uint 40, uint 262144), 
    +     sbyte* getelementptr ([6 x sbyte]* %str4, int 0, int 0), 
    +     int 300 }, section "llvm.metadata"
    + %str4 = internal constant [6 x sbyte] c"Maple\00", section "llvm.metadata"
    + 
    + ;;
    + ;; Define the array of enumerators used by composite type Trees.
    + ;;
    + %llvm.dbg.array = internal constant [3 x {  }*] [
    +   {  }* cast (%llvm.dbg.enumerator.type* %llvm.dbg.enumerator1 to {  }*),
    +   {  }* cast (%llvm.dbg.enumerator.type* %llvm.dbg.enumerator2 to {  }*),
    +   {  }* cast (%llvm.dbg.enumerator.type* %llvm.dbg.enumerator3 to {  }*) ], section "llvm.metadata"
    + 
    + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/Stacker.html diff -c /dev/null llvm-www/releases/1.8/docs/Stacker.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/Stacker.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,1412 ---- + + + + Stacker: An Example Of Using LLVM + + + + +
    Stacker: An Example Of Using LLVM
    + +
      +
    1. Abstract
    2. +
    3. Introduction
    4. +
    5. Lessons I Learned About LLVM +
        +
      1. Everything's a Value!
      2. +
      3. Terminate Those Blocks!
      4. +
      5. Concrete Blocks
      6. +
      7. push_back Is Your Friend
      8. +
      9. The Wily GetElementPtrInst
      10. +
      11. Getting Linkage Types Right
      12. +
      13. Constants Are Easier Than That!
      14. +
    6. +
    7. The Stacker Lexicon +
        +
      1. The Stack
      2. +
      3. Punctuation
      4. +
      5. Comments
      6. +
      7. Literals
      8. +
      9. Words
      10. +
      11. Standard Style
      12. +
      13. Built-Ins
      14. +
    8. +
    9. Prime: A Complete Example
    10. +
    11. Internal Code Details +
        +
      1. The Directory Structure
      2. +
      3. The Lexer
      4. +
      5. The Parser
      6. +
      7. The Compiler
      8. +
      9. The Runtime
      10. +
      11. Compiler Driver
      12. +
      13. Test Programs
      14. +
      15. Exercise
      16. +
      17. Things Remaining To Be Done
      18. +
    12. +
    + +
    +

    Written by Reid Spencer

    +
    + + + +
    +

    This document is another way to learn about LLVM. Unlike the + LLVM Reference Manual or + LLVM Programmer's Manual, here we learn + about LLVM through the experience of creating a simple programming language + named Stacker. Stacker was invented specifically as a demonstration of + LLVM. The emphasis in this document is not on describing the + intricacies of LLVM itself but on how to use it to build your own + compiler system.

    +
    + + +
    +

    Amongst other things, LLVM is a platform for compiler writers. + Because of its exceptionally clean and small IR (intermediate + representation), compiler writing with LLVM is much easier than with + other system. As proof, I wrote the entire compiler (language definition, + lexer, parser, code generator, etc.) in about four days! + That's important to know because it shows how quickly you can get a new + language running when using LLVM. Furthermore, this was the first + language the author ever created using LLVM. The learning curve is + included in that four days.

    +

    The language described here, Stacker, is Forth-like. Programs + are simple collections of word definitions, and the only thing definitions + can do is manipulate a stack or generate I/O. Stacker is not a "real" + programming language; it's very simple. Although it is computationally + complete, you wouldn't use it for your next big project. However, + the fact that it is complete, it's simple, and it doesn't have + a C-like syntax make it useful for demonstration purposes. It shows + that LLVM could be applied to a wide variety of languages.

    +

    The basic notions behind stacker is very simple. There's a stack of + integers (or character pointers) that the program manipulates. Pretty + much the only thing the program can do is manipulate the stack and do + some limited I/O operations. The language provides you with several + built-in words that manipulate the stack in interesting ways. To get + your feet wet, here's how you write the traditional "Hello, World" + program in Stacker:

    +

    : hello_world "Hello, World!" >s DROP CR ;
    + : MAIN hello_world ;

    +

    This has two "definitions" (Stacker manipulates words, not + functions and words have definitions): MAIN and + hello_world. The MAIN definition is standard; it + tells Stacker where to start. Here, MAIN is defined to + simply invoke the word hello_world. The + hello_world definition tells stacker to push the + "Hello, World!" string on to the stack, print it out + (>s), pop it off the stack (DROP), and + finally print a carriage return (CR). Although + hello_world uses the stack, its net effect is null. Well + written Stacker definitions have that characteristic.

    +

    Exercise for the reader: how could you make this a one line program?

    +
    + +
    Lessons I Learned About LLVM
    +
    +

    Stacker was written for two purposes:

    +
      +
    1. to get the author over the learning curve, and
    2. +
    3. to provide a simple example of how to write a compiler using LLVM.
    4. +
    +

    During the development of Stacker, many lessons about LLVM were + learned. Those lessons are described in the following subsections.

    +

    + +
    Everything's a Value!
    +
    +

    Although I knew that LLVM uses a Single Static Assignment (SSA) format, + it wasn't obvious to me how prevalent this idea was in LLVM until I really + started using it. Reading the + Programmer's Manual and Language Reference, + I noted that most of the important LLVM IR (Intermediate Representation) C++ + classes were derived from the Value class. The full power of that simple + design only became fully understood once I started constructing executable + expressions for Stacker.

    + +

    This really makes your programming go faster. Think about compiling code + for the following C/C++ expression: (a|b)*((x+1)/(y+1)). Assuming + the values are on the stack in the order a, b, x, y, this could be + expressed in stacker as: 1 + SWAP 1 + / ROT2 OR *. + You could write a function using LLVM that computes this expression like + this:

    + +
    + Value* 
    + expression(BasicBlock* bb, Value* a, Value* b, Value* x, Value* y )
    + {
    +     ConstantSInt* one = ConstantSInt::get(Type::IntTy, 1);
    +     BinaryOperator* or1 = BinaryOperator::createOr(a, b, "", bb);
    +     BinaryOperator* add1 = BinaryOperator::createAdd(x, one, "", bb);
    +     BinaryOperator* add2 = BinaryOperator::createAdd(y, one, "", bb);
    +     BinaryOperator* div1 = BinaryOperator::createDiv(add1, add2, "", bb);
    +     BinaryOperator* mult1 = BinaryOperator::createMul(or1, div1, "", bb);
    +     return mult1;
    + }
    + 
    + +

    "Okay, big deal," you say? It is a big deal. Here's why. Note that I didn't + have to tell this function which kinds of Values are being passed in. They could be + Instructions, Constants, GlobalVariables, or + any of the other subclasses of Value that LLVM supports. + Furthermore, if you specify Values that are incorrect for this sequence of + operations, LLVM will either notice right away (at compilation time) or the LLVM + Verifier will pick up the inconsistency when the compiler runs. In either case + LLVM prevents you from making a type error that gets passed through to the + generated program. This really helps you write a compiler that + always generates correct code!

    +

    The second point is that we don't have to worry about branching, registers, + stack variables, saving partial results, etc. The instructions we create + are the values we use. Note that all that was created in the above + code is a Constant value and five operators. Each of the instructions is + the resulting value of that instruction. This saves a lot of time.

    +

    The lesson is this: SSA form is very powerful: there is no difference + between a value and the instruction that created it. This is fully + enforced by the LLVM IR. Use it to your best advantage.

    +
    + +
    Terminate Those Blocks!
    +
    +

    I had to learn about terminating blocks the hard way: using the debugger + to figure out what the LLVM verifier was trying to tell me and begging for + help on the LLVMdev mailing list. I hope you avoid this experience.

    +

    Emblazon this rule in your mind:

    +
      +
    • All BasicBlocks in your compiler must be + terminated with a terminating instruction (branch, return, etc.). +
    • +
    +

    Terminating instructions are a semantic requirement of the LLVM IR. There + is no facility for implicitly chaining together blocks placed into a function + in the order they occur. Indeed, in the general case, blocks will not be + added to the function in the order of execution because of the recursive + way compilers are written.

    +

    Furthermore, if you don't terminate your blocks, your compiler code will + compile just fine. You won't find out about the problem until you're running + the compiler and the module you just created fails on the LLVM Verifier.

    +
    + +
    Concrete Blocks
    +
    +

    After a little initial fumbling around, I quickly caught on to how blocks + should be constructed. In general, here's what I learned: +

      +
    1. Create your blocks early. While writing your compiler, you + will encounter several situations where you know apriori that you will + need several blocks. For example, if-then-else, switch, while, and for + statements in C/C++ all need multiple blocks for expression in LVVM. + The rule is, create them early.
    2. +
    3. Terminate your blocks early. This just reduces the chances + that you forget to terminate your blocks which is required (go + here for more). +
    4. Use getTerminator() for instruction insertion. I noticed early on + that many of the constructors for the Instruction classes take an optional + insert_before argument. At first, I thought this was a mistake + because clearly the normal mode of inserting instructions would be one at + a time after some other instruction, not before. However, + if you hold on to your terminating instruction (or use the handy dandy + getTerminator() method on a BasicBlock), it can + always be used as the insert_before argument to your instruction + constructors. This causes the instruction to automatically be inserted in + the RightPlace™ place, just before the terminating instruction. The + nice thing about this design is that you can pass blocks around and insert + new instructions into them without ever knowing what instructions came + before. This makes for some very clean compiler design.
    5. +
    +

    The foregoing is such an important principal, its worth making an idiom:

    +
    + BasicBlock* bb = new BasicBlock();
    + bb->getInstList().push_back( new Branch( ... ) );
    + new Instruction(..., bb->getTerminator() );
    + 
    +

    To make this clear, consider the typical if-then-else statement + (see StackerCompiler::handle_if() method). We can set this up + in a single function using LLVM in the following way:

    +
    + using namespace llvm;
    + BasicBlock*
    + MyCompiler::handle_if( BasicBlock* bb, SetCondInst* condition )
    + {
    +     // Create the blocks to contain code in the structure of if/then/else
    +     BasicBlock* then_bb = new BasicBlock(); 
    +     BasicBlock* else_bb = new BasicBlock();
    +     BasicBlock* exit_bb = new BasicBlock();
    + 
    +     // Insert the branch instruction for the "if"
    +     bb->getInstList().push_back( new BranchInst( then_bb, else_bb, condition ) );
    + 
    +     // Set up the terminating instructions
    +     then->getInstList().push_back( new BranchInst( exit_bb ) );
    +     else->getInstList().push_back( new BranchInst( exit_bb ) );
    + 
    +     // Fill in the then part .. details excised for brevity
    +     this->fill_in( then_bb );
    + 
    +     // Fill in the else part .. details excised for brevity
    +     this->fill_in( else_bb );
    + 
    +     // Return a block to the caller that can be filled in with the code
    +     // that follows the if/then/else construct.
    +     return exit_bb;
    + }
    + 
    +

    Presumably in the foregoing, the calls to the "fill_in" method would add + the instructions for the "then" and "else" parts. They would use the third part + of the idiom almost exclusively (inserting new instructions before the + terminator). Furthermore, they could even recurse back to handle_if + should they encounter another if/then/else statement, and it will just work.

    +

    Note how cleanly this all works out. In particular, the push_back methods on + the BasicBlock's instruction list. These are lists of type + Instruction (which is also of type Value). To create + the "if" branch we merely instantiate a BranchInst that takes as + arguments the blocks to branch to and the condition to branch on. The + BasicBlock objects act like branch labels! This new + BranchInst terminates the BasicBlock provided + as an argument. To give the caller a way to keep inserting after calling + handle_if, we create an exit_bb block which is + returned + to the caller. Note that the exit_bb block is used as the + terminator for both the then_bb and the else_bb + blocks. This guarantees that no matter what else handle_if + or fill_in does, they end up at the exit_bb block. +

    +
    + +
    push_back Is Your Friend
    +
    +

    + One of the first things I noticed is the frequent use of the "push_back" + method on the various lists. This is so common that it is worth mentioning. + The "push_back" inserts a value into an STL list, vector, array, etc. at the + end. The method might have also been named "insert_tail" or "append". + Although I've used STL quite frequently, my use of push_back wasn't very + high in other programs. In LLVM, you'll use it all the time. +

    +
    + +
    The Wily GetElementPtrInst
    +
    +

    + It took a little getting used to and several rounds of postings to the LLVM + mailing list to wrap my head around this instruction correctly. Even though I had + read the Language Reference and Programmer's Manual a couple times each, I still + missed a few very key points: +

    +
      +
    • GetElementPtrInst gives you back a Value for the last thing indexed.
    • +
    • All global variables in LLVM are pointers.
    • +
    • Pointers must also be dereferenced with the GetElementPtrInst + instruction.
    • +
    +

    This means that when you look up an element in the global variable (assuming + it's a struct or array), you must deference the pointer first! For many + things, this leads to the idiom: +

    +
    + std::vector<Value*> index_vector;
    + index_vector.push_back( ConstantSInt::get( Type::LongTy, 0 );
    + // ... push other indices ...
    + GetElementPtrInst* gep = new GetElementPtrInst( ptr, index_vector );
    + 
    +

    For example, suppose we have a global variable whose type is [24 x int]. The + variable itself represents a pointer to that array. To subscript the + array, we need two indices, not just one. The first index (0) dereferences the + pointer. The second index subscripts the array. If you're a "C" programmer, this + will run against your grain because you'll naturally think of the global array + variable and the address of its first element as the same. That tripped me up + for a while until I realized that they really do differ .. by type. + Remember that LLVM is strongly typed. Everything has a type. + The "type" of the global variable is [24 x int]*. That is, it's + a pointer to an array of 24 ints. When you dereference that global variable with + a single (0) index, you now have a "[24 x int]" type. Although + the pointer value of the dereferenced global and the address of the zero'th element + in the array will be the same, they differ in their type. The zero'th element has + type "int" while the pointer value has type "[24 x int]".

    +

    Get this one aspect of LLVM right in your head, and you'll save yourself + a lot of compiler writing headaches down the road.

    +
    + +
    Getting Linkage Types Right
    +
    +

    Linkage types in LLVM can be a little confusing, especially if your compiler + writing mind has affixed firm concepts to particular words like "weak", + "external", "global", "linkonce", etc. LLVM does not use the precise + definitions of, say, ELF or GCC, even though they share common terms. To be fair, + the concepts are related and similar but not precisely the same. This can lead + you to think you know what a linkage type represents but in fact it is slightly + different. I recommend you read the + Language Reference on this topic very + carefully. Then, read it again.

    +

    Here are some handy tips that I discovered along the way:

    +
      +
    • Uninitialized means external. That is, the symbol is declared in the current + module and can be used by that module, but it is not defined by that module.
    • +
    • Setting an initializer changes a global' linkage type. Setting an + initializer changes a global's linkage type from whatever it was to a normal, + defined global (not external). You'll need to call the setLinkage() method to + reset it if you specify the initializer after the GlobalValue has been constructed. + This is important for LinkOnce and Weak linkage types.
    • +
    • Appending linkage can keep track of things. Appending linkage can + be used to keep track of compilation information at runtime. It could be used, + for example, to build a full table of all the C++ virtual tables or hold the + C++ RTTI data, or whatever. Appending linkage can only be applied to arrays. + All arrays with the same name in each module are concatenated together at link + time.
    • +
    +
    + +
    Constants Are Easier Than That!
    +
    +

    + Constants in LLVM took a little getting used to until I discovered a few utility + functions in the LLVM IR that make things easier. Here's what I learned:

    +
      +
    • Constants are Values like anything else and can be operands of instructions
    • +
    • Integer constants, frequently needed, can be created using the static "get" + methods of the ConstantInt, ConstantSInt, and ConstantUInt classes. The nice thing + about these is that you can "get" any kind of integer quickly.
    • +
    • There's a special method on Constant class which allows you to get the null + constant for any type. This is really handy for initializing large + arrays or structures, etc.
    • +
    +
    + + +

    This section describes the Stacker language

    +
    The Stack
    +
    +

    Stacker definitions define what they do to the global stack. Before + proceeding, a few words about the stack are in order. The stack is simply + a global array of 32-bit integers or pointers. A global index keeps track + of the location of the top of the stack. All of this is hidden from the + programmer, but it needs to be noted because it is the foundation of the + conceptual programming model for Stacker. When you write a definition, + you are, essentially, saying how you want that definition to manipulate + the global stack.

    +

    Manipulating the stack can be quite hazardous. There is no distinction + given and no checking for the various types of values that can be placed + on the stack. Automatic coercion between types is performed. In many + cases, this is useful. For example, a boolean value placed on the stack + can be interpreted as an integer with good results. However, using a + word that interprets that boolean value as a pointer to a string to + print out will almost always yield a crash. Stacker simply leaves it + to the programmer to get it right without any interference or hindering + on interpretation of the stack values. You've been warned. :)

    +
    + +
    Punctuation
    +
    +

    Punctuation in Stacker is very simple. The colon and semi-colon + characters are used to introduce and terminate a definition + (respectively). Except for FORWARD declarations, definitions + are all you can specify in Stacker. Definitions are read left to right. + Immediately after the colon comes the name of the word being defined. + The remaining words in the definition specify what the word does. The definition + is terminated by a semi-colon.

    +

    So, your typical definition will have the form:

    +
    : name ... ;
    +

    The name is up to you but it must start with a letter and contain + only letters, numbers, and underscore. Names are case sensitive and must not be + the same as the name of a built-in word. The ... is replaced by + the stack manipulating words that you wish to define name as.

    +

    + +
    Comments
    +
    +

    Stacker supports two types of comments. A hash mark (#) starts a comment + that extends to the end of the line. It is identical to the kind of comments + commonly used in shell scripts. A pair of parentheses also surround a comment. + In both cases, the content of the comment is ignored by the Stacker compiler. The + following does nothing in Stacker. +

    +
    
    + # This is a comment to end of line
    + ( This is an enclosed comment )
    + 
    +

    See the example program to see comments in use in + a real program.

    +
    + +
    Literals
    +
    +

    There are three kinds of literal values in Stacker: Integers, Strings, + and Booleans. In each case, the stack operation is to simply push the + value on to the stack. So, for example:
    + 42 " is the answer." TRUE
    + will push three values on to the stack: the integer 42, the + string " is the answer.", and the boolean TRUE.

    +
    + +
    Words
    +
    +

    Each definition in Stacker is composed of a set of words. Words are + read and executed in order from left to right. There is very little + checking in Stacker to make sure you're doing the right thing with + the stack. It is assumed that the programmer knows how the stack + transformation he applies will affect the program.

    +

    Words in a definition come in two flavors: built-in and programmer + defined. Simply mentioning the name of a previously defined or declared + programmer-defined word causes that word's stack actions to be invoked. It + is somewhat like a function call in other languages. The built-in + words have various effects, described below.

    +

    Sometimes you need to call a word before it is defined. For this, you can + use the FORWARD declaration. It looks like this:

    +

    FORWARD name ;

    +

    This simply states to Stacker that "name" is the name of a definition + that is defined elsewhere. Generally it means the definition can be found + "forward" in the file. But, it doesn't have to be in the current compilation + unit. Anything declared with FORWARD is an external symbol for + linking.

    +
    + +
    Standard Style
    +
    +

    TODO

    +
    + +
    Built In Words
    +
    +

    The built-in words of the Stacker language are put in several groups + depending on what they do. The groups are as follows:

    +
      +
    1. Logical: These words provide the logical operations for + comparing stack operands.
      The words are: < > <= >= + = <> true false.
    2. +
    3. Bitwise: These words perform bitwise computations on + their operands.
      The words are: << >> XOR AND NOT
    4. +
    5. Arithmetic: These words perform arithmetic computations on + their operands.
      The words are: ABS NEG + - * / MOD */ ++ -- MIN MAX
    6. +
    7. StackThese words manipulate the stack directly by moving + its elements around.
      The words are: DROP DROP2 NIP NIP2 DUP DUP2 + SWAP SWAP2 OVER OVER2 ROT ROT2 RROT RROT2 TUCK TUCK2 PICK SELECT ROLL
    8. +
    9. MemoryThese words allocate, free, and manipulate memory + areas outside the stack.
      The words are: MALLOC FREE GET PUT
    10. +
    11. Control: These words alter the normal left to right flow + of execution.
      The words are: IF ELSE ENDIF WHILE END RETURN EXIT RECURSE
    12. +
    13. I/O: These words perform output on the standard output + and input on the standard input. No other I/O is possible in Stacker. +
      The words are: SPACE TAB CR >s >d >c <s <d <c.
    14. +
    +

    While you may be familiar with many of these operations from other + programming languages, a careful review of their semantics is important + for correct programming in Stacker. Of most importance is the effect + that each of these built-in words has on the global stack. The effect is + not always intuitive. To better describe the effects, we'll borrow from Forth the idiom of + describing the effect on the stack with:

    +

    BEFORE -- AFTER

    +

    That is, to the left of the -- is a representation of the stack before + the operation. To the right of the -- is a representation of the stack + after the operation. In the table below that describes the operation of + each of the built in words, we will denote the elements of the stack + using the following construction:

    +
      +
    1. b - a boolean truth value
    2. +
    3. w - a normal integer valued word.
    4. +
    5. s - a pointer to a string value
    6. +
    7. p - a pointer to a malloc'd memory block
    8. +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Definition Of Operation Of Built In Words
    LOGICAL OPERATIONS
    WordNameOperationDescription
    <LTw1 w2 -- bTwo values (w1 and w2) are popped off the stack and + compared. If w1 is less than w2, TRUE is pushed back on + the stack, otherwise FALSE is pushed back on the stack.
    >GTw1 w2 -- bTwo values (w1 and w2) are popped off the stack and + compared. If w1 is greater than w2, TRUE is pushed back on + the stack, otherwise FALSE is pushed back on the stack.
    >=GEw1 w2 -- bTwo values (w1 and w2) are popped off the stack and + compared. If w1 is greater than or equal to w2, TRUE is + pushed back on the stack, otherwise FALSE is pushed back + on the stack.
    <=LEw1 w2 -- bTwo values (w1 and w2) are popped off the stack and + compared. If w1 is less than or equal to w2, TRUE is + pushed back on the stack, otherwise FALSE is pushed back + on the stack.
    =EQw1 w2 -- bTwo values (w1 and w2) are popped off the stack and + compared. If w1 is equal to w2, TRUE is + pushed back on the stack, otherwise FALSE is pushed back +
    <>NEw1 w2 -- bTwo values (w1 and w2) are popped off the stack and + compared. If w1 is equal to w2, TRUE is + pushed back on the stack, otherwise FALSE is pushed back +
    FALSEFALSE -- bThe boolean value FALSE (0) is pushed on to the stack.
    TRUETRUE -- bThe boolean value TRUE (-1) is pushed on to the stack.
    BITWISE OPERATORS
    WordNameOperationDescription
    <<SHLw1 w2 -- w1<<w2Two values (w1 and w2) are popped off the stack. The w2 + operand is shifted left by the number of bits given by the + w1 operand. The result is pushed back to the stack.
    >>SHRw1 w2 -- w1>>w2Two values (w1 and w2) are popped off the stack. The w2 + operand is shifted right by the number of bits given by the + w1 operand. The result is pushed back to the stack.
    ORORw1 w2 -- w2|w1Two values (w1 and w2) are popped off the stack. The values + are bitwise OR'd together and pushed back on the stack. This is + not a logical OR. The sequence 1 2 OR yields 3 not 1.
    ANDANDw1 w2 -- w2&w1Two values (w1 and w2) are popped off the stack. The values + are bitwise AND'd together and pushed back on the stack. This is + not a logical AND. The sequence 1 2 AND yields 0 not 1.
    XORXORw1 w2 -- w2^w1Two values (w1 and w2) are popped off the stack. The values + are bitwise exclusive OR'd together and pushed back on the stack. + For example, The sequence 1 3 XOR yields 2.
    ARITHMETIC OPERATORS
    WordNameOperationDescription
    ABSABSw -- |w|One value s popped off the stack; its absolute value is computed + and then pushed on to the stack. If w1 is -1 then w2 is 1. If w1 is + 1 then w2 is also 1.
    NEGNEGw -- -wOne value is popped off the stack which is negated and then + pushed back on to the stack. If w1 is -1 then w2 is 1. If w1 is + 1 then w2 is -1.
    + ADDw1 w2 -- w2+w1Two values are popped off the stack. Their sum is pushed back + on to the stack
    - SUBw1 w2 -- w2-w1Two values are popped off the stack. Their difference is pushed back + on to the stack
    * MULw1 w2 -- w2*w1Two values are popped off the stack. Their product is pushed back + on to the stack
    / DIVw1 w2 -- w2/w1Two values are popped off the stack. Their quotient is pushed back + on to the stack
    MODMODw1 w2 -- w2%w1Two values are popped off the stack. Their remainder after division + of w1 by w2 is pushed back on to the stack
    */ STAR_SLAHw1 w2 w3 -- (w3*w2)/w1Three values are popped off the stack. The product of w1 and w2 is + divided by w3. The result is pushed back on to the stack.
    ++ INCRw -- w+1One value is popped off the stack. It is incremented by one and then + pushed back on to the stack.
    -- DECRw -- w-1One value is popped off the stack. It is decremented by one and then + pushed back on to the stack.
    MINMINw1 w2 -- (w2<w1?w2:w1)Two values are popped off the stack. The larger one is pushed back + on to the stack.
    MAXMAXw1 w2 -- (w2>w1?w2:w1)Two values are popped off the stack. The larger value is pushed back + on to the stack.
    STACK MANIPULATION OPERATORS
    WordNameOperationDescription
    DROPDROPw -- One value is popped off the stack.
    DROP2DROP2w1 w2 -- Two values are popped off the stack.
    NIPNIPw1 w2 -- w2The second value on the stack is removed from the stack. That is, + a value is popped off the stack and retained. Then a second value is + popped and the retained value is pushed.
    NIP2NIP2w1 w2 w3 w4 -- w3 w4The third and fourth values on the stack are removed from it. That is, + two values are popped and retained. Then two more values are popped and + the two retained values are pushed back on.
    DUPDUPw1 -- w1 w1One value is popped off the stack. That value is then pushed on to + the stack twice to duplicate the top stack vaue.
    DUP2DUP2w1 w2 -- w1 w2 w1 w2The top two values on the stack are duplicated. That is, two vaues + are popped off the stack. They are alternately pushed back on the + stack twice each.
    SWAPSWAPw1 w2 -- w2 w1The top two stack items are reversed in their order. That is, two + values are popped off the stack and pushed back on to the stack in + the opposite order they were popped.
    SWAP2SWAP2w1 w2 w3 w4 -- w3 w4 w2 w1The top four stack items are swapped in pairs. That is, two values + are popped and retained. Then, two more values are popped and retained. + The values are pushed back on to the stack in the reverse order but + in pairs.
    OVEROVERw1 w2-- w1 w2 w1Two values are popped from the stack. They are pushed back + on to the stack in the order w1 w2 w1. This seems to cause the + top stack element to be duplicated "over" the next value.
    OVER2OVER2w1 w2 w3 w4 -- w1 w2 w3 w4 w1 w2The third and fourth values on the stack are replicated on to the + top of the stack
    ROTROTw1 w2 w3 -- w2 w3 w1The top three values are rotated. That is, three value are popped + off the stack. They are pushed back on to the stack in the order + w1 w3 w2.
    ROT2ROT2w1 w2 w3 w4 w5 w6 -- w3 w4 w5 w6 w1 w2Like ROT but the rotation is done using three pairs instead of + three singles.
    RROTRROTw1 w2 w3 -- w3 w1 w2Reverse rotation. Like ROT, but it rotates the other way around. + Essentially, the third element on the stack is moved to the top + of the stack.
    RROT2RROT2w1 w2 w3 w4 w5 w6 -- w3 w4 w5 w6 w1 w2Double reverse rotation. Like RROT but the rotation is done using + three pairs instead of three singles. The fifth and sixth stack + elements are moved to the first and second positions
    TUCKTUCKw1 w2 -- w2 w1 w2Similar to OVER except that the second operand is being + replicated. Essentially, the first operand is being "tucked" + in between two instances of the second operand. Logically, two + values are popped off the stack. They are placed back on the + stack in the order w2 w1 w2.
    TUCK2TUCK2w1 w2 w3 w4 -- w3 w4 w1 w2 w3 w4Like TUCK but a pair of elements is tucked over two pairs. + That is, the top two elements of the stack are duplicated and + inserted into the stack at the fifth and positions.
    PICKPICKx0 ... Xn n -- x0 ... Xn x0The top of the stack is used as an index into the remainder of + the stack. The element at the nth position replaces the index + (top of stack). This is useful for cycling through a set of + values. Note that indexing is zero based. So, if n=0 then you + get the second item on the stack. If n=1 you get the third, etc. + Note also that the index is replaced by the n'th value.
    SELECTSELECTm n X0..Xm Xm+1 .. Xn -- XmThis is like PICK but the list is removed and you need to specify + both the index and the size of the list. Careful with this one, + the wrong value for n can blow away a huge amount of the stack.
    ROLLROLLx0 x1 .. xn n -- x1 .. xn x0Not Implemented. This one has been left as an exercise to + the student. See Exercise. ROLL requires + a value, "n", to be on the top of the stack. This value specifies how + far into the stack to "roll". The n'th value is moved (not + copied) from its location and replaces the "n" value on the top of the + stack. In this way, all the values between "n" and x0 roll up the stack. + The operation of ROLL is a generalized ROT. The "n" value specifies + how much to rotate. That is, ROLL with n=1 is the same as ROT and + ROLL with n=2 is the same as ROT2.
    MEMORY OPERATORS
    WordNameOperationDescription
    MALLOCMALLOCw1 -- pOne value is popped off the stack. The value is used as the size + of a memory block to allocate. The size is in bytes, not words. + The memory allocation is completed and the address of the memory + block is pushed on to the stack.
    FREEFREEp -- One pointer value is popped off the stack. The value should be + the address of a memory block created by the MALLOC operation. The + associated memory block is freed. Nothing is pushed back on the + stack. Many bugs can be created by attempting to FREE something + that isn't a pointer to a MALLOC allocated memory block. Make + sure you know what's on the stack. One way to do this is with + the following idiom:
    + 64 MALLOC DUP DUP (use ptr) DUP (use ptr) ... FREE +
    This ensures that an extra copy of the pointer is placed on + the stack (for the FREE at the end) and that every use of the + pointer is preceded by a DUP to retain the copy for FREE.
    GETGETw1 p -- w2 pAn integer index and a pointer to a memory block are popped of + the block. The index is used to index one byte from the memory + block. That byte value is retained, the pointer is pushed again + and the retained value is pushed. Note that the pointer value + s essentially retained in its position so this doesn't count + as a "use ptr" in the FREE idiom.
    PUTPUTw1 w2 p -- p An integer value is popped of the stack. This is the value to + be put into a memory block. Another integer value is popped of + the stack. This is the indexed byte in the memory block. A + pointer to the memory block is popped off the stack. The + first value (w1) is then converted to a byte and written + to the element of the memory block(p) at the index given + by the second value (w2). The pointer to the memory block is + pushed back on the stack so this doesn't count as a "use ptr" + in the FREE idiom.
    CONTROL FLOW OPERATORS
    WordNameOperationDescription
    RETURNRETURN -- The currently executing definition returns immediately to its caller. + Note that there is an implicit RETURN at the end of each + definition, logically located at the semi-colon. The sequence + RETURN ; is valid but redundant.
    EXITEXITw1 -- A return value for the program is popped off the stack. The program is + then immediately terminated. This is normally an abnormal exit from the + program. For a normal exit (when MAIN finishes), the exit + code will always be zero in accordance with UNIX conventions.
    RECURSERECURSE -- The currently executed definition is called again. This operation is + needed since the definition of a word doesn't exist until the semi colon + is reacher. Attempting something like:
    + : recurser recurser ;
    will yield and error saying that + "recurser" is not defined yet. To accomplish the same thing, change this + to:
    + : recurser RECURSE ;
    IF (words...) ENDIFIF (words...) ENDIFb -- A boolean value is popped of the stack. If it is non-zero then the "words..." + are executed. Otherwise, execution continues immediately following the ENDIF.
    IF (words...) ELSE (words...) ENDIFIF (words...) ELSE (words...) ENDIFb -- A boolean value is popped of the stack. If it is non-zero then the "words..." + between IF and ELSE are executed. Otherwise the words between ELSE and ENDIF are + executed. In either case, after the (words....) have executed, execution continues + immediately following the ENDIF.
    WHILE word ENDWHILE word ENDb -- b The boolean value on the top of the stack is examined (not popped). If + it is non-zero then the "word" between WHILE and END is executed. + Execution then begins again at the WHILE where the boolean on the top of + the stack is examined again. The stack is not modified by the WHILE...END + loop, only examined. It is imperative that the "word" in the body of the + loop ensure that the top of the stack contains the next boolean to examine + when it completes. Note that since booleans and integers can be coerced + you can use the following "for loop" idiom:
    + (push count) WHILE word -- END
    + For example:
    + 10 WHILE >d -- END
    + This will print the numbers from 10 down to 1. 10 is pushed on the + stack. Since that is non-zero, the while loop is entered. The top of + the stack (10) is printed out with >d. The top of the stack is + decremented, yielding 9 and control is transfered back to the WHILE + keyword. The process starts all over again and repeats until + the top of stack is decremented to 0 at which point the WHILE test + fails and control is transfered to the word after the END. +
    INPUT & OUTPUT OPERATORS
    WordNameOperationDescription
    SPACESPACE -- A space character is put out. There is no stack effect.
    TABTAB -- A tab character is put out. There is no stack effect.
    CRCR -- A carriage return character is put out. There is no stack effect.
    >sOUT_STR -- A string pointer is popped from the stack. It is put out.
    >dOUT_STR -- A value is popped from the stack. It is put out as a decimal + integer.
    >cOUT_CHR -- A value is popped from the stack. It is put out as an ASCII + character.
    <sIN_STR -- s A string is read from the input via the scanf(3) format string " %as". + The resulting string is pushed on to the stack.
    <dIN_STR -- w An integer is read from the input via the scanf(3) format string " %d". + The resulting value is pushed on to the stack
    <cIN_CHR -- w A single character is read from the input via the scanf(3) format string + " %c". The value is converted to an integer and pushed on to the stack.
    DUMPDUMP -- The stack contents are dumped to standard output. This is useful for + debugging your definitions. Put DUMP at the beginning and end of a definition + to see instantly the net effect of the definition.
    + +
    + + +
    +

    The following fully documented program highlights many features of both + the Stacker language and what is possible with LLVM. The program has two modes + of operation. If you provide numeric arguments to the program, it checks to see + if those arguments are prime numbers and prints out the results. Without any + arguments, the program prints out any prime numbers it finds between 1 and one + million (there's a lot of them!). The source code comments below tell the + remainder of the story. +

    +
    +
    +
    
    + ################################################################################
    + #
    + # Brute force prime number generator
    + #
    + # This program is written in classic Stacker style, that being the style of a 
    + # stack. Start at the bottom and read your way up !
    + #
    + # Reid Spencer - Nov 2003 
    + ################################################################################
    + # Utility definitions
    + ################################################################################
    + : print >d CR ;
    + : it_is_a_prime TRUE ;
    + : it_is_not_a_prime FALSE ;
    + : continue_loop TRUE ;
    + : exit_loop FALSE;
    +     
    + ################################################################################
    + # This definition tries an actual division of a candidate prime number. It
    + # determines whether the division loop on this candidate should continue or
    + # not.
    + # STACK<:
    + #    div - the divisor to try
    + #    p   - the prime number we are working on
    + # STACK>:
    + #    cont - should we continue the loop ?
    + #    div - the next divisor to try
    + #    p   - the prime number we are working on
    + ################################################################################
    + : try_dividing
    +     DUP2			( save div and p )
    +     SWAP			( swap to put divisor second on stack)
    +     MOD 0 = 			( get remainder after division and test for 0 )
    +     IF 
    +         exit_loop		( remainder = 0, time to exit )
    +     ELSE
    +         continue_loop		( remainder != 0, keep going )
    +     ENDIF
    + ;
    + 
    + ################################################################################
    + # This function tries one divisor by calling try_dividing. But, before doing
    + # that it checks to see if the value is 1. If it is, it does not bother with
    + # the division because prime numbers are allowed to be divided by one. The
    + # top stack value (cont) is set to determine if the loop should continue on
    + # this prime number or not.
    + # STACK<:
    + #    cont - should we continue the loop (ignored)?
    + #    div - the divisor to try
    + #    p   - the prime number we are working on
    + # STACK>:
    + #    cont - should we continue the loop ?
    + #    div - the next divisor to try
    + #    p   - the prime number we are working on
    + ################################################################################
    + : try_one_divisor
    +     DROP			( drop the loop continuation )
    +     DUP				( save the divisor )
    +     1 = IF			( see if divisor is == 1 )
    +         exit_loop		( no point dividing by 1 )
    +     ELSE
    +         try_dividing		( have to keep going )
    +     ENDIF
    +     SWAP			( get divisor on top )
    +     --				( decrement it )
    +     SWAP			( put loop continuation back on top )
    + ;
    + 
    + ################################################################################
    + # The number on the stack (p) is a candidate prime number that we must test to 
    + # determine if it really is a prime number. To do this, we divide it by every 
    + # number from one p-1 to 1. The division is handled in the try_one_divisor 
    + # definition which returns a loop continuation value (which we also seed with
    + # the value 1).  After the loop, we check the divisor. If it decremented all
    + # the way to zero then we found a prime, otherwise we did not find one.
    + # STACK<:
    + #   p - the prime number to check
    + # STACK>:
    + #   yn - boolean indicating if its a prime or not
    + #   p - the prime number checked
    + ################################################################################
    + : try_harder
    +     DUP 			( duplicate to get divisor value ) )
    +     --				( first divisor is one less than p )
    +     1				( continue the loop )
    +     WHILE
    +        try_one_divisor		( see if its prime )
    +     END
    +     DROP			( drop the continuation value )
    +     0 = IF			( test for divisor == 1 )
    +        it_is_a_prime		( we found one )
    +     ELSE
    +        it_is_not_a_prime	( nope, this one is not a prime )
    +     ENDIF
    + ;
    + 
    + ################################################################################
    + # This definition determines if the number on the top of the stack is a prime 
    + # or not. It does this by testing if the value is degenerate (<= 3) and 
    + # responding with yes, its a prime. Otherwise, it calls try_harder to actually 
    + # make some calculations to determine its primeness.
    + # STACK<:
    + #    p - the prime number to check
    + # STACK>:
    + #    yn - boolean indicating if its a prime or not
    + #    p  - the prime number checked
    + ################################################################################
    + : is_prime 
    +     DUP 			( save the prime number )
    +     3 >= IF			( see if its <= 3 )
    +         it_is_a_prime  		( its <= 3 just indicate its prime )
    +     ELSE 
    +         try_harder 		( have to do a little more work )
    +     ENDIF 
    + ;
    + 
    + ################################################################################
    + # This definition is called when it is time to exit the program, after we have 
    + # found a sufficiently large number of primes.
    + # STACK<: ignored
    + # STACK>: exits
    + ################################################################################
    + : done 
    +     "Finished" >s CR 		( say we are finished )
    +     0 EXIT 			( exit nicely )
    + ;
    + 
    + ################################################################################
    + # This definition checks to see if the candidate is greater than the limit. If 
    + # it is, it terminates the program by calling done. Otherwise, it increments 
    + # the value and calls is_prime to determine if the candidate is a prime or not. 
    + # If it is a prime, it prints it. Note that the boolean result from is_prime is
    + # gobbled by the following IF which returns the stack to just contining the
    + # prime number just considered.
    + # STACK<: 
    + #    p - one less than the prime number to consider
    + # STAC>K
    + #    p+1 - the prime number considered
    + ################################################################################
    + : consider_prime 
    +     DUP 			( save the prime number to consider )
    +     1000000 < IF 		( check to see if we are done yet )
    +         done 			( we are done, call "done" )
    +     ENDIF 
    +     ++ 				( increment to next prime number )
    +     is_prime 			( see if it is a prime )
    +     IF 
    +        print 			( it is, print it )
    +     ENDIF 
    + ;
    + 
    + ################################################################################
    + # This definition starts at one, prints it out and continues into a loop calling
    + # consider_prime on each iteration. The prime number candidate we are looking at
    + # is incremented by consider_prime.
    + # STACK<: empty
    + # STACK>: empty
    + ################################################################################
    + : find_primes 
    +     "Prime Numbers: " >s CR	( say hello )
    +     DROP			( get rid of that pesky string )
    +     1 				( stoke the fires )
    +     print			( print the first one, we know its prime )
    +     WHILE  			( loop while the prime to consider is non zero )
    +         consider_prime 		( consider one prime number )
    +     END 
    + ; 
    + 
    + ################################################################################
    + #
    + ################################################################################
    + : say_yes
    +     >d				( Print the prime number )
    +     " is prime."		( push string to output )
    +     >s				( output it )
    +     CR				( print carriage return )
    +     DROP			( pop string )
    + ;
    + 
    + : say_no
    +     >d				( Print the prime number )
    +     " is NOT prime."		( push string to put out )
    +     >s				( put out the string )
    +     CR				( print carriage return )
    +     DROP			( pop string )
    + ;
    + 
    + ################################################################################
    + # This definition processes a single command line argument and determines if it
    + # is a prime number or not.
    + # STACK<:
    + #    n - number of arguments
    + #    arg1 - the prime numbers to examine
    + # STACK>:
    + #    n-1 - one less than number of arguments
    + #    arg2 - we processed one argument
    + ################################################################################
    + : do_one_argument
    +     --				( decrement loop counter )
    +     SWAP			( get the argument value  )
    +     is_prime IF			( determine if its prime )
    +         say_yes			( uhuh )
    +     ELSE
    +         say_no			( nope )
    +     ENDIF
    +     DROP			( done with that argument )
    + ;
    + 
    + ################################################################################
    + # The MAIN program just prints a banner and processes its arguments.
    + # STACK<:
    + #    n - number of arguments
    + #    ... - the arguments
    + ################################################################################
    + : process_arguments
    +     WHILE			( while there are more arguments )
    +        do_one_argument		( process one argument )
    +     END
    + ;
    +     
    + ################################################################################
    + # The MAIN program just prints a banner and processes its arguments.
    + # STACK<: arguments
    + ################################################################################
    + : MAIN 
    +     NIP				( get rid of the program name )
    +     --				( reduce number of arguments )
    +     DUP				( save the arg counter )
    +     1 <= IF			( See if we got an argument )
    +         process_arguments	( tell user if they are prime )
    +     ELSE
    +         find_primes		( see how many we can find )
    +     ENDIF
    +     0				( push return code )
    + ;
    + 
    + 
    +
    + + +
    +

    This section is under construction. +

    In the mean time, you can always read the code! It has comments!

    +
    + + +
    +

    The source code, test programs, and sample programs can all be found + under the LLVM "projects" directory. You will need to obtain the LLVM sources + to find it (either via anonymous CVS or a tarball. See the + Getting Started document).

    +

    Under the "projects" directory there is a directory named "Stacker". That + directory contains everything, as follows:

    +
      +
    • lib - contains most of the source code +
        +
      • lib/compiler - contains the compiler library +
      • lib/runtime - contains the runtime library +
    • +
    • test - contains the test programs
    • +
    • tools - contains the Stacker compiler main program, stkrc +
        +
      • lib/stkrc - contains the Stacker compiler main program + +
      • sample - contains the sample programs
      • +
      +
    + +
    The Lexer
    +
    +

    See projects/Stacker/lib/compiler/Lexer.l

    +
    + +
    The Parser
    +
    +

    See projects/Stacker/lib/compiler/StackerParser.y

    +
    + +
    The Compiler
    +
    +

    See projects/Stacker/lib/compiler/StackerCompiler.cpp

    +
    + +
    The Runtime
    +
    +

    See projects/Stacker/lib/runtime/stacker_rt.c

    +
    + +
    Compiler Driver
    +
    +

    See projects/Stacker/tools/stkrc/stkrc.cpp

    +
    + +
    Test Programs
    +
    +

    See projects/Stacker/test/*.st

    +
    + + +
    +

    As you may have noted from a careful inspection of the Built-In word + definitions, the ROLL word is not implemented. This word was left out of + Stacker on purpose so that it can be an exercise for the student. The exercise + is to implement the ROLL functionality (in your own workspace) and build a test + program for it. If you can implement ROLL, you understand Stacker and probably + a fair amount about LLVM since this is one of the more complicated Stacker + operations. The work will almost be completely limited to the + compiler. +

    The ROLL word is already recognized by both the lexer and parser but ignored + by the compiler. That means you don't have to futz around with figuring out how + to get the keyword recognized. It already is. The part of the compiler that + you need to implement is the ROLL case in the + StackerCompiler::handle_word(int) method.

    See the + implementations of PICK and SELECT in the same method to get some hints about + how to complete this exercise.

    +

    Good luck!

    +
    + + +
    +

    The initial implementation of Stacker has several deficiencies. If you're + interested, here are some things that could be implemented better:

    +
      +
    1. Write an LLVM pass to compute the correct stack depth needed by the + program. Currently the stack is set to a fixed number which means programs + with large numbers of definitions might fail.
    2. +
    3. Write an LLVM pass to optimize the use of the global stack. The code + emitted currently is somewhat wasteful. It gets cleaned up a lot by existing + passes but more could be done.
    4. +
    5. Make the compiler driver use the LLVM linking facilities (with IPO) + before depending on GCC to do the final link.
    6. +
    7. Clean up parsing. It doesn't handle errors very well.
    8. +
    9. Rearrange the StackerCompiler.cpp code to make better use of inserting + instructions before a block's terminating instruction. I didn't figure this + technique out until I was nearly done with LLVM. As it is, its a bad example + of how to insert instructions!
    10. +
    11. Provide for I/O to arbitrary files instead of just stdin/stdout.
    12. +
    13. Write additional built-in words; with inspiration from FORTH
    14. +
    15. Write additional sample Stacker programs.
    16. +
    17. Add your own compiler writing experiences and tips in the + Lessons I Learned About LLVM section.
    18. +
    +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Reid Spencer
    + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/SystemLibrary.html diff -c /dev/null llvm-www/releases/1.8/docs/SystemLibrary.html:1.1 *** /dev/null Wed Aug 9 00:56:52 2006 --- llvm-www/releases/1.8/docs/SystemLibrary.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,344 ---- + + + + System Library + + + + +
    System Library
    + + +
    +

    Written by Reid Spencer

    +
    + + + + +
    +

    This document provides some details on LLVM's System Library, located in + the source at lib/System and include/llvm/System. The + library's purpose is to shield LLVM from the differences between operating + systems for the few services LLVM needs from the operating system. Much of + LLVM is written using portability features of standard C++. However, in a few + areas, system dependent facilities are needed and the System Library is the + wrapper around those system calls.

    +

    By centralizing LLVM's use of operating system interfaces, we make it + possible for the LLVM tool chain and runtime libraries to be more easily + ported to new platforms since (theoretically) only lib/System needs + to be ported. This library also unclutters the rest of LLVM from #ifdef use + and special cases for specific operating systems. Such uses are replaced + with simple calls to the interfaces provided in include/llvm/System. +

    +

    Note that the System Library is not intended to be a complete operating + system wrapper (such as the Adaptive Communications Environment (ACE) or + Apache Portable Runtime (APR)), but only provides the functionality necessary + to support LLVM. +

    The System Library was written by Reid Spencer who formulated the + design based on similar work originating from the eXtensible Programming + System (XPS). Several people helped with the effort; especially, + Jeff Cohen and Henrik Bach on the Win32 port.

    +
    + + + +
    +

    In order to keep LLVM portable, LLVM developers should adhere to a set of + portability rules associated with the System Library. Adherence to these rules + should help the System Library achieve its goal of shielding LLVM from the + variations in operating system interfaces and doing so efficiently. The + following sections define the rules needed to fulfill this objective.

    +
    + + + +
    +

    Except in lib/System, no LLVM source code should directly + #include a system header. Care has been taken to remove all such + #includes from LLVM while lib/System was being + developed. Specifically this means that header files like "unistd.h", + "windows.h", "stdio.h", and "string.h" are forbidden to be included by LLVM + source code outside the implementation of lib/System.

    +

    To obtain system-dependent functionality, existing interfaces to the system + found in include/llvm/System should be used. If an appropriate + interface is not available, it should be added to include/llvm/System + and implemented in lib/System for all supported platforms.

    +
    + + + +
    +

    The System Library must shield LLVM from all system headers. To + obtain system level functionality, LLVM source must + #include "llvm/System/Thing.h" and nothing else. This means that + Thing.h cannot expose any system header files. This protects LLVM + from accidentally using system specific functionality and only allows it + via the lib/System interface.

    +
    + + + +
    +

    The standard C headers (the ones beginning with "c") are allowed + to be exposed through the lib/System interface. These headers and + the things they declare are considered to be platform agnostic. LLVM source + files may include them directly or obtain their inclusion through + lib/System interfaces.

    +
    + + + +
    +

    The standard C++ headers from the standard C++ library and + standard template library may be exposed through the lib/System + interface. These headers and the things they declare are considered to be + platform agnostic. LLVM source files may include them or obtain their + inclusion through lib/System interfaces.

    +
    + + + +
    +

    The entry points specified in the interface of lib/System must be aimed at + completing some reasonably high level task needed by LLVM. We do not want to + simply wrap each operating system call. It would be preferable to wrap several + operating system calls that are always used in conjunction with one another by + LLVM.

    +

    For example, consider what is needed to execute a program, wait for it to + complete, and return its result code. On Unix, this involves the following + operating system calls: getenv, fork, execve, and wait. The + correct thing for lib/System to provide is a function, say + ExecuteProgramAndWait, that implements the functionality completely. + what we don't want is wrappers for the operating system calls involved.

    +

    There must not be a one-to-one relationship between operating + system calls and the System library's interface. Any such interface function + will be suspicious.

    +
    + + + +
    +

    There must be no functionality specified in the interface of lib/System + that isn't actually used by LLVM. We're not writing a general purpose + operating system wrapper here, just enough to satisfy LLVM's needs. And, LLVM + doesn't need much. This design goal aims to keep the lib/System interface + small and understandable which should foster its actual use and adoption.

    +
    + + + +
    +

    The implementation of a function for a given platform must be written + exactly once. This implies that it must be possible to apply a function's + implementation to multiple operating systems if those operating systems can + share the same implementation. This rule applies to the set of operating + systems supported for a given class of operating system (e.g. Unix, Win32). +

    +
    + + + +
    +

    The System Library interfaces can be called quite frequently by LLVM. In + order to make those calls as efficient as possible, we discourage the use of + virtual methods. There is no need to use inheritance for implementation + differences, it just adds complexity. The #include mechanism works + just fine.

    +
    + + + +
    +

    Any functions defined by system libraries (i.e. not defined by lib/System) + must not be exposed through the lib/System interface, even if the header file + for that function is not exposed. This prevents inadvertent use of system + specific functionality.

    +

    For example, the stat system call is notorious for having + variations in the data it provides. lib/System must not declare + stat nor allow it to be declared. Instead it should provide its own + interface to discovering information about files and directories. Those + interfaces may be implemented in terms of stat but that is strictly + an implementation detail. The interface provided by the System Library must + be implemented on all platforms (even those without stat).

    +
    + + + +
    +

    Any data defined by system libraries (i.e. not defined by lib/System) must + not be exposed through the lib/System interface, even if the header file for + that function is not exposed. As with functions, this prevents inadvertent use + of data that might not exist on all platforms.

    +
    + + + +
    +

    Operating system interfaces will generally provide error results for every + little thing that could go wrong. In almost all cases, you can divide these + error results into two groups: normal/good/soft and abnormal/bad/hard. That + is, some of the errors are simply information like "file not found", + "insufficient privileges", etc. while other errors are much harder like + "out of space", "bad disk sector", or "system call interrupted". We'll call + the first group "soft" errors and the second group "hard" + errors.

    +

    lib/System must always attempt to minimize soft errors and always just + throw a std::string on hard errors. This is a design requirement because the + minimization of soft errors can affect the granularity and the nature of the + interface. In general, if you find that you're wanting to throw soft errors, + you must review the granularity of the interface because it is likely you're + trying to implement something that is too low level. The rule of thumb is to + provide interface functions that can't fail, except when faced with + hard errors.

    +

    For a trivial example, suppose we wanted to add an "OpenFileForWriting" + function. For many operating systems, if the file doesn't exist, attempting + to open the file will produce an error. However, lib/System should not + simply throw that error if it occurs because its a soft error. The problem + is that the interface function, OpenFileForWriting is too low level. It should + be OpenOrCreateFileForWriting. In the case of the soft "doesn't exist" error, + this function would just create it and then open it for writing.

    +

    This design principle needs to be maintained in lib/System because it + avoids the propagation of soft error handling throughout the rest of LLVM. + Hard errors will generally just cause a termination for an LLVM tool so don't + be bashful about throwing them.

    +

    Rules of thumb:

    +
      +
    1. Don't throw soft errors, only hard errors.
    2. +
    3. If you're tempted to throw a soft error, re-think the interface.
    4. +
    5. Handle internally the most common normal/good/soft error conditions + so the rest of LLVM doesn't have to.
    6. +
    +
    + + + +
    +

    If an error occurs that lib/System cannot handle, the only action taken by + lib/System is to throw an instance of std:string. The contents of the string + must explain both what happened and the context in which it happened. The + format of the string should be a (possibly empty) list of contexts each + terminated with a : and a space, followed by the error message, optionally + followed by a reason, and optionally followed by a suggestion.

    +

    For example, failure to open a file named "foo" could result in a message + like:

    +
    • foo: Unable to open file because it doesn't exist."
    +

    The "foo:" part is the context. The "Unable to open file" part is the error + message. The "because it doesn't exist." part is the reason. This message has + no suggestion. Where possible, the implementation of lib/System should use + operating system specific facilities for converting the error code returned by + a system call into an error message. This will help to make the error message + more familiar to users of that type of operating system.

    +

    Note that this requirement precludes the throwing of any other exceptions. + For example, various C++ standard library functions can cause exceptions to be + thrown (e.g. out of memory situation). In all cases, if there is a possibility + that non-string exceptions could be thrown, the lib/System library must ensure + that the exceptions are translated to std::string form.

    +
    + + + +
    +

    None of the lib/System interface functions may be declared with C++ + throw() specifications on them. This requirement makes sure that the + compiler does not insert additional exception handling code into the interface + functions. This is a performance consideration: lib/System functions are at + the bottom of many call chains and as such can be frequently called. We + need them to be as efficient as possible.

    +
    + + + +
    +

    Implementations of the System Library interface are separated by their + general class of operating system. Currently only Unix and Win32 classes are + defined but more could be added for other operating system classifications. + To distinguish which implementation to compile, the code in lib/System uses + the LLVM_ON_UNIX and LLVM_ON_WIN32 #defines provided via configure through the + llvm/Config/config.h file. Each source file in lib/System, after implementing + the generic (operating system independent) functionality needs to include the + correct implementation using a set of #if defined(LLVM_ON_XYZ) + directives. For example, if we had lib/System/File.cpp, we'd expect to see in + that file:

    +
    
    +   #if defined(LLVM_ON_UNIX)
    +   #include "Unix/File.cpp"
    +   #endif
    +   #if defined(LLVM_ON_WIN32)
    +   #include "Win32/File.cpp"
    +   #endif
    +   
    +

    The implementation in lib/System/Unix/File.cpp should handle all Unix + variants. The implementation in lib/System/Win32/File.cpp should handle all + Win32 variants. What this does is quickly differentiate the basic class of + operating system that will provide the implementation. The specific details + for a given platform must still be determined through the use of + #ifdef.

    +
    + + + +
    +

    The implementation of a lib/System interface can vary drastically between + platforms. That's okay as long as the end result of the interface function + is the same. For example, a function to create a directory is pretty straight + forward on all operating system. System V IPC on the other hand isn't even + supported on all platforms. Instead of "supporting" System V IPC, lib/System + should provide an interface to the basic concept of inter-process + communications. The implementations might use System V IPC if that was + available or named pipes, or whatever gets the job done effectively for a + given operating system. In all cases, the interface and the implementation + must be semantically consistent.

    +
    + + + +
    +

    See bug 351 + for further details on the progress of this work

    +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Reid Spencer
    + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + Index: llvm-www/releases/1.8/docs/TableGenFundamentals.html diff -c /dev/null llvm-www/releases/1.8/docs/TableGenFundamentals.html:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/TableGenFundamentals.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,567 ---- + + + + TableGen Fundamentals + + + + +
    TableGen Fundamentals
    + + + +
    +

    Written by Chris Lattner

    +
    + + + + + +
    + +

    TableGen's purpose is to help a human develop and maintain records of + domain-specific information. Because there may be a large number of these + records, it is specifically designed to allow writing flexible descriptions and + for common features of these records to be factored out. This reduces the + amount of duplication in the description, reduces the chance of error, and + makes it easier to structure domain specific information.

    + +

    The core part of TableGen parses a file, instantiates + the declarations, and hands the result off to a domain-specific "TableGen backend" for processing. The current major user + of TableGen is the LLVM code generator.

    + +

    Note that if you work on TableGen much, and use emacs or vim, that you can + find an emacs "TableGen mode" and a vim language file in + llvm/utils/emacs and llvm/utils/vim directory of your LLVM + distribution, respectively.

    + +
    + + + + +
    + +

    TableGen files consist of two key parts: 'classes' and 'definitions', both + of which are considered 'records'.

    + +

    TableGen records have a unique name, a list of values, and a list of + superclasses. The list of values is main data that TableGen builds for each + record, it is this that holds the domain specific information for the + application. The interpretation of this data is left to a specific TableGen backend, but the structure and format rules are + taken care of and fixed by TableGen.

    + +

    TableGen definitions are the concrete form of 'records'. These + generally do not have any undefined values, and are marked with the + 'def' keyword.

    + +

    TableGen classes are abstract records that are used to build and + describe other records. These 'classes' allow the end-user to build + abstractions for either the domain they are targetting (such as "Register", + "RegisterClass", and "Instruction" in the LLVM code generator) or for the + implementor to help factor out common properties of records (such as "FPInst", + which is used to represent floating point instructions in the X86 backend). + TableGen keeps track of all of the classes that are used to build up a + definition, so the backend can find all definitions of a particular class, such + as "Instruction".

    + +
    + + + + +
    + +

    With no other arguments, TableGen parses the specified file and prints out + all of the classes, then all of the definitions. This is a good way to see what + the various definitions expand to fully. Running this on the X86.td + file prints this (at the time of this writing):

    + +
    + ...
    + def ADDrr8 {    // Instruction X86Inst I2A8 Pattern
    +   string Name = "add";
    +   string Namespace = "X86";
    +   list<Register> Uses = [];
    +   list<Register> Defs = [];
    +   bit isReturn = 0;
    +   bit isBranch = 0;
    +   bit isCall = 0;
    +   bit isTwoAddress = 1;
    +   bit isTerminator = 0;
    +   dag Pattern = (set R8, (plus R8, R8));
    +   bits<8> Opcode = { 0, 0, 0, 0, 0, 0, 0, 0 };
    +   Format Form = MRMDestReg;
    +   bits<5> FormBits = { 0, 0, 0, 1, 1 };
    +   ArgType Type = Arg8;
    +   bits<3> TypeBits = { 0, 0, 1 };
    +   bit hasOpSizePrefix = 0;
    +   bit printImplicitUses = 0;
    +   bits<4> Prefix = { 0, 0, 0, 0 };
    +   FPFormat FPForm = ?;
    +   bits<3> FPFormBits = { 0, 0, 0 };
    + }
    + ...
    + 
    + +

    This definition corresponds to an 8-bit register-register add instruction in + the X86. The string after the 'def' string indicates the name of the + record ("ADDrr8" in this case), and the comment at the end of the line + indicates the superclasses of the definition. The body of the record contains + all of the data that TableGen assembled for the record, indicating that the + instruction is part of the "X86" namespace, should be printed as "add" + in the assembly file, it is a two-address instruction, has a particular + encoding, etc. The contents and semantics of the information in the record is + specific to the needs of the X86 backend, and is only shown as an example.

    + +

    As you can see, a lot of information is needed for every instruction + supported by the code generator, and specifying it all manually would be + unmaintainble, prone to bugs, and tiring to do in the first place. Because we + are using TableGen, all of the information was derived from the following + definition:

    + +
    + def ADDrr8   : I2A8<"add", 0x00, MRMDestReg>,
    +                Pattern<(set R8, (plus R8, R8))>;
    + 
    + +

    This definition makes use of the custom I2A8 (two address instruction with + 8-bit operand) class, which is defined in the X86-specific TableGen file to + factor out the common features that instructions of its class share. A key + feature of TableGen is that it allows the end-user to define the abstractions + they prefer to use when describing their information.

    + +
    + + + + +
    + +

    TableGen runs just like any other LLVM tool. The first (optional) argument + specifies the file to read. If a filename is not specified, tblgen + reads from standard input.

    + +

    To be useful, one of the TableGen backends must be + used. These backends are selectable on the command line (type 'tblgen + --help' for a list). For example, to get a list of all of the definitions + that subclass a particular type (which can be useful for building up an enum + list of these records), use the --print-enums option:

    + +
    + $ tblgen X86.td -print-enums -class=Register
    + AH, AL, AX, BH, BL, BP, BX, CH, CL, CX, DH, DI, DL, DX,
    + EAX, EBP, EBX, ECX, EDI, EDX, ESI, ESP, FP0, FP1, FP2, FP3, FP4, FP5, FP6,
    + SI, SP, ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7, 
    + 
    + $ tblgen X86.td -print-enums -class=Instruction 
    + ADCrr32, ADDri16, ADDri16b, ADDri32, ADDri32b, ADDri8, ADDrr16, ADDrr32,
    + ADDrr8, ADJCALLSTACKDOWN, ADJCALLSTACKUP, ANDri16, ANDri16b, ANDri32, ANDri32b,
    + ANDri8, ANDrr16, ANDrr32, ANDrr8, BSWAPr32, CALLm32, CALLpcrel32, ...
    + 
    + +

    The default backend prints out all of the records, as described above.

    + +

    If you plan to use TableGen for some purpose, you will most likely have to + write a backend that extracts the information specific + to what you need and formats it in the appropriate way.

    + +
    + + + + + + +
    +

    TableGen doesn't care about the meaning of data (that is up to the backend + to define), but it does care about syntax, and it enforces a simple type system. + This section describes the syntax and the constructs allowed in a TableGen file. +

    +
    + + + + + + + +
    +

    TableGen supports BCPL style "//" comments, which run to the end of + the line, and it also supports nestable "/* */" comments.

    +
    + + + + +
    +

    TableGen files are strongly typed, in a simple (but complete) type-system. + These types are used to perform automatic conversions, check for errors, and to + help interface designers constrain the input that they allow. Every value definition is required to have an associated type. +

    + +

    TableGen supports a mixture of very low-level types (such as bit) + and very high-level types (such as dag). This flexibility is what + allows it to describe a wide range of information conveniently and compactly. + The TableGen types are:

    + +
      +
    • "bit" - A 'bit' is a boolean value that can hold either 0 or + 1.
    • + +
    • "int" - The 'int' type represents a simple 32-bit integer + value, such as 5.
    • + +
    • "string" - The 'string' type represents an ordered sequence + of characters of arbitrary length.
    • + +
    • "bits<n>" - A 'bits' type is an arbitrary, but fixed, + size integer that is broken up into individual bits. This type is useful + because it can handle some bits being defined while others are undefined.
    • + +
    • "list<ty>" - This type represents a list whose + elements are some other type. The contained type is arbitrary: it can even be + another list type.
    • + +
    • Class type - Specifying a class name in a type context means that the + defined value must be a subclass of the specified class. This is useful in + conjunction with the "list" type, for example, to constrain the elements of the + list to a common base class (e.g., a list<Register> can + only contain definitions derived from the "Register" class).
    • + +
    • "code" - This represents a big hunk of text. NOTE: I don't + remember why this is distinct from string!
    • + +
    • "dag" - This type represents a nestable directed graph of + elements.
    • +
    + +

    To date, these types have been sufficient for describing things that + TableGen has been used for, but it is straight-forward to extend this list if + needed.

    + +
    + + + + +
    + +

    TableGen allows for a pretty reasonable number of different expression forms + when building up values. These forms allow the TableGen file to be written in a + natural syntax and flavor for the application. The current expression forms + supported include:

    + +
      +
    • ? - uninitialized field
    • +
    • 0b1001011 - binary integer value
    • +
    • 07654321 - octal integer value (indicated by a leading 0)
    • +
    • 7 - decimal integer value
    • +
    • 0x7F - hexadecimal integer value
    • +
    • "foo" - string value
    • +
    • [{ ... }] - code fragment
    • +
    • [ X, Y, Z ] - list value.
    • +
    • { a, b, c } - initializer for a "bits<3>" value
    • +
    • value - value reference
    • +
    • value{17} - access to one bit of a value
    • +
    • value{15-17} - access to multiple bits of a value
    • +
    • DEF - reference to a record definition
    • +
    • CLASS<val list> - reference to a new anonymous definition of + CLASS with the specified template arguments.
    • +
    • X.Y - reference to the subfield of a value
    • +
    • list[4-7,17,2-3] - A slice of the 'list' list, including elements + 4,5,6,7,17,2, and 3 from it. Elements may be included multiple times.
    • +
    • (DEF a, b) - a dag value. The first element is required to be a + record definition, the remaining elements in the list may be arbitrary other + values, including nested `dag' values.
    • +
    + +

    Note that all of the values have rules specifying how they convert to values + for different types. These rules allow you to assign a value like "7" to a + "bits<4>" value, for example.

    + +
    + + + + +
    + +

    As mentioned in the intro, classes and definitions + (collectively known as 'records') in TableGen are the main high-level unit of + information that TableGen collects. Records are defined with a def or + class keyword, the record name, and an optional list of "template arguments". If the record has superclasses, + they are specified as a comma separated list that starts with a colon character + (":"). If value definitions or let + expressions are needed for the class, they are enclosed in curly braces + ("{}"); otherwise, the record ends with a semicolon. Here is a simple TableGen + file:

    + +
    + class C { bit V = 1; }
    + def X : C;
    + def Y : C {
    +   string Greeting = "hello";
    + }
    + 
    + +

    This example defines two definitions, X and Y, both of + which derive from the C class. Because of this, they both get the + V bit value. The Y definition also gets the Greeting member + as well.

    + +

    In general, classes are useful for collecting together the commonality + between a group of records and isolating it in a single place. Also, classes + permit the specification of default values for their subclasses, allowing the + subclasses to override them as they wish.

    + +
    + + + + +
    +

    Value definitions define named entries in records. A value must be defined + before it can be referred to as the operand for another value definition or + before the value is reset with a let expression. A + value is defined by specifying a TableGen type and a name. + If an initial value is available, it may be specified after the type with an + equal sign. Value definitions require terminating semicolons.

    +
    + + + + +
    +

    A record-level let expression is used to change the value of a value + definition in a record. This is primarily useful when a superclass defines a + value that a derived class or definition wants to override. Let expressions + consist of the 'let' keyword followed by a value name, an equal sign + ("="), and a new value. For example, a new class could be added to the example + above, redefining the V field for all of its subclasses:

    + +
    + class D : C { let V = 0; }
    + def Z : D;
    + 
    + +

    In this case, the Z definition will have a zero value for its "V" + value, despite the fact that it derives (indirectly) from the C class, + because the D class overrode its value.

    + +
    + + + + +
    +

    TableGen permits the definition of parameterized classes as well as normal + concrete classes. Parameterized TableGen classes specify a list of variable + bindings (which may optionally have defaults) that are bound when used. Here is + a simple example:

    + +
    + class FPFormat<bits<3> val> {
    +   bits<3> Value = val;
    + }
    + def NotFP      : FPFormat<0>;
    + def ZeroArgFP  : FPFormat<1>;
    + def OneArgFP   : FPFormat<2>;
    + def OneArgFPRW : FPFormat<3>;
    + def TwoArgFP   : FPFormat<4>;
    + def SpecialFP  : FPFormat<5>;
    + 
    + +

    In this case, template arguments are used as a space efficient way to specify + a list of "enumeration values", each with a "Value" field set to the specified + integer.

    + +

    The more esoteric forms of TableGen expressions are + useful in conjunction with template arguments. As an example:

    + +
    + class ModRefVal<bits<2> val> {
    +   bits<2> Value = val;
    + }
    + 
    + def None   : ModRefVal<0>;
    + def Mod    : ModRefVal<1>;
    + def Ref    : ModRefVal<2>;
    + def ModRef : ModRefVal<3>;
    + 
    + class Value<ModRefVal MR> {
    +   // decode some information into a more convenient format, while providing
    +   // a nice interface to the user of the "Value" class.
    +   bit isMod = MR.Value{0};
    +   bit isRef = MR.Value{1};
    + 
    +   // other stuff...
    + }
    + 
    + // Example uses
    + def bork : Value<Mod>;
    + def zork : Value<Ref>;
    + def hork : Value<ModRef>;
    + 
    + +

    This is obviously a contrived example, but it shows how template arguments + can be used to decouple the interface provided to the user of the class from the + actual internal data representation expected by the class. In this case, + running tblgen on the example prints the following definitions:

    + +
    + def bork {      // Value
    +   bit isMod = 1;
    +   bit isRef = 0;
    + }
    + def hork {      // Value
    +   bit isMod = 1;
    +   bit isRef = 1;
    + }
    + def zork {      // Value
    +   bit isMod = 0;
    +   bit isRef = 1;
    + }
    + 
    + +

    This shows that TableGen was able to dig into the argument and extract a + piece of information that was requested by the designer of the "Value" class. + For more realistic examples, please see existing users of TableGen, such as the + X86 backend.

    + +
    + + + + + + + +
    +

    TableGen supports the 'include' token, which textually substitutes + the specified file in place of the include directive. The filename should be + specified as a double quoted string immediately after the 'include' + keyword. Example:

    + +
    + include "foo.td"
    + 
    + +
    + + + + +
    +

    "let" expressions at file scope are similar to "let" + expressions within a record, except they can specify a value binding for + multiple records at a time, and may be useful in certain other cases. + File-scope let expressions are really just another way that TableGen allows the + end-user to factor out commonality from the records.

    + +

    File-scope "let" expressions take a comma-separated list of bindings to + apply, and one of more records to bind the values in. Here are some + examples:

    + +
    + let isTerminator = 1, isReturn = 1 in
    +   def RET : X86Inst<"ret", 0xC3, RawFrm, NoArg>;
    + 
    + let isCall = 1 in
    +   // All calls clobber the non-callee saved registers...
    +   let Defs = [EAX, ECX, EDX, FP0, FP1, FP2, FP3, FP4, FP5, FP6] in {
    +     def CALLpcrel32 : X86Inst<"call", 0xE8, RawFrm, NoArg>;
    +     def CALLr32     : X86Inst<"call", 0xFF, MRMS2r, Arg32>;
    +     def CALLm32     : X86Inst<"call", 0xFF, MRMS2m, Arg32>;
    +   }
    + 
    + +

    File-scope "let" expressions are often useful when a couple of definitions + need to be added to several records, and the records do not otherwise need to be + opened, as in the case with the CALL* instructions above.

    +
    + + + + + +
    +

    How they work, how to write one. This section should not contain details + about any particular backend, except maybe -print-enums as an example. This + should highlight the APIs in TableGen/Record.h.

    +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/TestingGuide.html diff -c /dev/null llvm-www/releases/1.8/docs/TestingGuide.html:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/TestingGuide.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,620 ---- + + + + LLVM Test Suite Guide + + + + +
    + LLVM Test Suite Guide +
    + +
      +
    1. Overview
    2. +
    3. Requirements
    4. +
    5. Quick Start
    6. +
    7. LLVM Test Suite Organization + +
    8. +
    9. LLVM Test Suite Tree
    10. +
    11. DejaGNU Structure
    12. +
    13. llvm-test Structure
    14. +
    15. Running the LLVM Tests + +
    16. +
    17. Running the nightly tester
    18. +
    + +
    +

    Written by John T. Criswell, Reid Spencer, and Tanya Lattner

    +
    + + + + + +
    + +

    This document is the reference manual for the LLVM test suite. It documents + the structure of the LLVM test suite, the tools needed to use it, and how to add + and run tests.

    + +
    + + + + + +
    + +

    In order to use the LLVM test suite, you will need all of the software + required to build LLVM, plus the following:

    + +
    +
    DejaGNU
    +
    The Feature and Regressions tests are organized and run by DejaGNU.
    +
    Expect
    +
    Expect is required by DejaGNU.
    +
    tcl
    +
    Tcl is required by DejaGNU.
    + +
    F2C
    +
    For now, LLVM does not have a Fortran front-end, but using F2C, we can run + Fortran benchmarks. F2C support must be enabled via configure if not + installed in a standard place. F2C requires three items: the f2c + executable, f2c.h to compile the generated code, and libf2c.a + to link generated code. By default, given an F2C directory $DIR, the + configure script will search $DIR/bin for f2c, + $DIR/include for f2c.h, and $DIR/lib for + libf2c.a. The default $DIR values are: /usr, + /usr/local, /sw, and /opt. If you installed F2C in a + different location, you must tell configure: + +
      +
    • ./configure --with-f2c=$DIR
      + This will specify a new $DIR for the above-described search + process. This will only work if the binary, header, and library are in their + respective subdirectories of $DIR.
    • + +
    • ./configure --with-f2c-bin=/binary/path --with-f2c-inc=/include/path + --with-f2c-lib=/lib/path
      + This allows you to specify the F2C components separately. Note: if you choose + this route, you MUST specify all three components, and you need to only specify + directories where the files are located; do NOT include the + filenames themselves on the configure line.
    • +
    +
    + +

    Darwin (Mac OS X) developers can simplify the installation of Expect and tcl + by using fink. fink install expect will install both. Alternatively, + Darwinports users can use sudo port install expect to install Expect + and tcl.

    + +
    + + + + + +
    + +

    The tests are located in two separate CVS modules. The basic feature and + regression tests are in the main "llvm" module under the directory + llvm/test. A more comprehensive test suite that includes whole + programs in C and C++ is in the llvm-test module. This module should + be checked out to the llvm/projects directory. When you + configure the llvm module, the llvm-test module + will be automatically configured. Alternatively, you can configure the + llvm-test module manually.

    +

    To run all of the simple tests in LLVM using DejaGNU, use the master Makefile + in the llvm/test directory:

    +
    + % gmake -C llvm/test
    + 
    + or
    +
    + % gmake check
    + 
    + +

    To run only a subdirectory of tests in llvm/test using DejaGNU (ie. + Regression/Transforms), just set the TESTSUITE variable to the path of the + subdirectory (relative to llvm/test):

    +
    + % gmake -C llvm/test TESTSUITE=Regression/Transforms
    + 
    + +

    Note: If you are running the tests with objdir != subdir, you + must have run the complete testsuite before you can specify a + subdirectory.

    + +

    To run the comprehensive test suite (tests that compile and execute whole + programs), run the llvm-test tests:

    + +
    + % cd llvm/projects
    + % cvs co llvm-test
    + % cd llvm-test
    + % ./configure --with-llvmsrc=$LLVM_SRC_ROOT --with-llvmobj=$LLVM_OBJ_ROOT
    + % gmake
    + 
    + +
    + + + + + +
    + +

    The LLVM test suite contains two major categories of tests: code + fragments and whole programs. Code fragments are in the llvm module + under the llvm/test directory. The whole programs + test suite is in the llvm-test module under the main directory.

    + +
    + + + + + +
    + +

    Code fragments are small pieces of code that test a specific feature of LLVM + or trigger a specific bug in LLVM. They are usually written in LLVM assembly + language, but can be written in other languages if the test targets a particular + language front end.

    + +

    Code fragments are not complete programs, and they are never executed to + determine correct behavior.

    + +

    These code fragment tests are located in the llvm/test/Features and + llvm/test/Regression directories.

    + +
    + + + + + +
    + +

    Whole Programs are pieces of code which can be compiled and linked into a + stand-alone program that can be executed. These programs are generally written + in high level languages such as C or C++, but sometimes they are written + straight in LLVM assembly.

    + +

    These programs are compiled and then executed using several different + methods (native compiler, LLVM C backend, LLVM JIT, LLVM native code generation, + etc). The output of these programs is compared to ensure that LLVM is compiling + the program correctly.

    + +

    In addition to compiling and executing programs, whole program tests serve as + a way of benchmarking LLVM performance, both in terms of the efficiency of the + programs generated as well as the speed with which LLVM compiles, optimizes, and + generates code.

    + +

    All "whole program" tests are located in the llvm-test CVS + module.

    + +
    + + + + + +
    + +

    Each type of test in the LLVM test suite has its own directory. The major + subtrees of the test suite directory tree are as follows:

    + +
      +
    • llvm/test/Features +

      This directory contains sample codes that test various features of the + LLVM language. These pieces of sample code are run through various + assembler, disassembler, and optimizer passes.

      +
    • + +
    • llvm/test/Regression +

      This directory contains regression tests for LLVM. When a bug is found + in LLVM, a regression test containing just enough code to reproduce the + problem should be written and placed somewhere underneath this directory. + In most cases, this will be a small piece of LLVM assembly language code, + often distilled from an actual application or benchmark.

      +
    • + +
    • llvm-test +

      The llvm-test CVS module contains programs that can be compiled + with LLVM and executed. These programs are compiled using the native compiler + and various LLVM backends. The output from the program compiled with the + native compiler is assumed correct; the results from the other programs are + compared to the native program output and pass if they match.

      + +

      In addition for testing correctness, the llvm-test directory also + performs timing tests of various LLVM optimizations. It also records + compilation times for the compilers and the JIT. This information can be + used to compare the effectiveness of LLVM's optimizations and code + generation.

    • + +
    • llvm-test/SingleSource +

      The SingleSource directory contains test programs that are only a single + source file in size. These are usually small benchmark programs or small + programs that calculate a particular value. Several such programs are grouped + together in each directory.

    • + +
    • llvm-test/MultiSource +

      The MultiSource directory contains subdirectories which contain entire + programs with multiple source files. Large benchmarks and whole applications + go here.

    • + +
    • llvm-test/External +

      The External directory contains Makefiles for building code that is external + to (i.e., not distributed with) LLVM. The most prominent members of this + directory are the SPEC 95 and SPEC 2000 benchmark suites. The presence and + location of these external programs is configured by the llvm-test + configure script.

    • + +
    + +
    + + + + +
    +

    The LLVM test suite is partially driven by DejaGNU and partially + driven by GNU Make. Specifically, the Features and Regression tests + are all driven by DejaGNU. The llvm-test + module is currently driven by a set of Makefiles.

    + +

    The DejaGNU structure is very simple, but does require some + information to be set. This information is gathered via configure and + is written to a file, site.exp in llvm/test. The + llvm/test + Makefile does this work for you.

    + +

    In order for DejaGNU to work, each directory of tests must have a + dg.exp file. This file is a program written in tcl that calls + the llvm-runtests procedure on each test file. The + llvm-runtests procedure is defined in + llvm/test/lib/llvm-dg.exp. Any directory that contains only + directories does not need the dg.exp file.

    + +

    In order for a test to be run, it must contain information within + the test file on how to run the test. These are called RUN + lines. Run lines are specified in the comments of the test program + using the keyword RUN followed by a colon, and lastly the + commands to execute. These commands will be executed in a bash script, + so any bash syntax is acceptable. You can specify as many RUN lines as + necessary. Each RUN line translates to one line in the resulting bash + script. Below is an example of legal RUN lines in a .ll + file:

    +
    + ; RUN: llvm-as < %s | llvm-dis > %t1
    + ; RUN: llvm-dis < %s.bc-13 > %t2
    + ; RUN: diff %t1 %t2
    + 
    +

    There are a couple patterns within a RUN line that the + llvm-runtest procedure looks for and replaces with the appropriate + syntax:

    + +
    +
    %p
    +
    The path to the source directory. This is for locating + any supporting files that are not generated by the test, but used by + the test.
    +
    %s
    +
    The test file.
    + +
    %t
    +
    Temporary filename: testscript.test_filename.tmp, where + test_filename is the name of the test file. All temporary files are + placed in the Output directory within the directory the test is + located.
    + +
    %prcontext
    +
    Path to a script that performs grep -C. Use this since not all + platforms support grep -C.
    + +
    %llvmgcc
    Full path to the llvm-gcc executable.
    +
    %llvmgxx
    Full path to the llvm-g++ executable.
    +
    + +

    There are also several scripts in the llvm/test/Scripts directory + that you might find useful when writing RUN lines.

    + +

    Lastly, you can easily mark a test that is expected to fail on a + specific platform or with a specific version of llvmgcc by using the + XFAIL keyword. Xfail lines are + specified in the comments of the test program using XFAIL, + followed by a colon, and one or more regular expressions (separated by + a comma) that will match against the target triplet or llvmgcc version for the + machine. You can use * to match all targets. You can specify the major or full + version (i.e. 3.4) for llvmgcc. Here is an example of an + XFAIL line:

    +
    + ; XFAIL: darwin,sun,llvmgcc4
    + 
    + +
    + + + + + +
    + +

    As mentioned previously, the llvm-test module provides three types + of tests: MultiSource, SingleSource, and External. Each tree is then subdivided + into several categories, including applications, benchmarks, regression tests, + code that is strange grammatically, etc. These organizations should be + relatively self explanatory.

    + +

    In addition to the regular "whole program" tests, the llvm-test + module also provides a mechanism for compiling the programs in different ways. + If the variable TEST is defined on the gmake command line, the test system will + include a Makefile named TEST.<value of TEST variable>.Makefile. + This Makefile can modify build rules to yield different results.

    + +

    For example, the LLVM nightly tester uses TEST.nightly.Makefile to + create the nightly test reports. To run the nightly tests, run gmake + TEST=nightly.

    + +

    There are several TEST Makefiles available in the tree. Some of them are + designed for internal LLVM research and will not work outside of the LLVM + research group. They may still be valuable, however, as a guide to writing your + own TEST Makefile for any optimization or analysis passes that you develop with + LLVM.

    + +

    Note, when configuring the llvm-test module, you might want to + specify the following configuration options:

    +
    +
    --enable-spec2000 +
    --enable-spec2000=<directory> +
    + Enable the use of SPEC2000 when testing LLVM. This is disabled by default + (unless configure finds SPEC2000 installed). By specifying + directory, you can tell configure where to find the SPEC2000 + benchmarks. If directory is left unspecified, configure + uses the default value + /home/vadve/shared/benchmarks/speccpu2000/benchspec. +

    +

    --enable-spec95 +
    --enable-spec95=<directory> +
    + Enable the use of SPEC95 when testing LLVM. It is similar to the + --enable-spec2000 option. +

    +

    --enable-povray +
    --enable-povray=<directory> +
    + Enable the use of Povray as an external test. Versions of Povray written + in C should work. This option is similar to the --enable-spec2000 + option. +
    +
    + + + + + +
    + +

    First, all tests are executed within the LLVM object directory tree. They + are not executed inside of the LLVM source tree. This is because the + test suite creates temporary files during execution.

    + +

    The master Makefile in llvm/test is capable of running only the DejaGNU + driven tests. By default, it will run all of these tests.

    + +

    To run only the DejaGNU driven tests, run gmake at the + command line in llvm/test. To run a specific directory of tests, use + the TESTSUITE variable. +

    + +

    For example, to run the Regression tests, type + gmake TESTSUITE=Regression in llvm/tests.

    + +

    Note that there are no Makefiles in llvm/test/Features and + llvm/test/Regression. You must use DejaGNU from the llvm/test + directory to run them.

    + +

    To run the llvm-test suite, you need to use the following steps: +

    +
      +
    1. cd into the llvm/projects directory
    2. +
    3. check out the llvm-test module with:
      + cvs -d :pserver:anon at llvm.org:/var/cvs/llvm co -PR llvm-test
      + This will get the test suite into llvm/projects/llvm-test
    4. +
    5. configure the test suite. You can do this one of two ways: +
        +
      1. Use the regular llvm configure:
        + cd $LLVM_OBJ_ROOT ; $LLVM_SRC_ROOT/configure
        + This will ensure that the projects/llvm-test directory is also + properly configured.
      2. +
      3. Use the configure script found in the llvm-test source + directory:
        + $LLVM_SRC_ROOT/projects/llvm-test/configure + --with-llvmsrc=$LLVM_SRC_ROOT --with-llvmobj=$LLVM_OBJ_ROOT +
      4. +
      +
    6. gmake
    7. +
    +

    Note that the second and third steps only need to be done once. After you + have the suite checked out and configured, you don't need to do it again (unless + the test code or configure script changes).

    + +

    To make a specialized test (use one of the + llvm-test/TEST.<type>.Makefiles), just run:
    + gmake TEST=<type> test
    For example, you could run the + nightly tester tests using the following commands:

    + +
    +  % cd llvm/projects/llvm-test
    +  % gmake TEST=nightly test
    + 
    + +

    Regardless of which test you're running, the results are printed on standard + output and standard error. You can redirect these results to a file if you + choose.

    + +

    Some tests are known to fail. Some are bugs that we have not fixed yet; + others are features that we haven't added yet (or may never add). In DejaGNU, + the result for such tests will be XFAIL (eXpected FAILure). In this way, you + can tell the difference between an expected and unexpected failure.

    + +

    The tests in llvm-test have no such feature at this time. If the + test passes, only warnings and other miscellaneous output will be generated. If + a test fails, a large <program> FAILED message will be displayed. This + will help you separate benign warnings from actual test failures.

    + +
    + + + + + +
    + +

    Assuming you can run llvm-test, (e.g. "gmake TEST=nightly report" + should work), it is really easy to run optimizations or code generator + components against every program in the tree, collecting statistics or running + custom checks for correctness. At base, this is how the nightly tester works, + it's just one example of a general framework.

    + +

    Lets say that you have an LLVM optimization pass, and you want to see how + many times it triggers. First thing you should do is add an LLVM + statistic to your pass, which + will tally counts of things you care about.

    + +

    Following this, you can set up a test and a report that collects these and + formats them for easy viewing. This consists of two files, an + "llvm-test/TEST.XXX.Makefile" fragment (where XXX is the name of your + test) and an "llvm-test/TEST.XXX.report" file that indicates how to + format the output into a table. There are many example reports of various + levels of sophistication included with llvm-test, and the framework is very + general.

    + +

    If you are interested in testing an optimization pass, check out the + "libcalls" test as an example. It can be run like this:

    + +

    +
    + % cd llvm/projects/llvm-test/MultiSource/Benchmarks  # or some other level
    + % make TEST=libcalls report
    + 
    +
    + +

    This will do a bunch of stuff, then eventually print a table like this:

    + +
    +
    + Name                                  | total | #exit |
    + ...
    + FreeBench/analyzer/analyzer           | 51    | 6     | 
    + FreeBench/fourinarow/fourinarow       | 1     | 1     | 
    + FreeBench/neural/neural               | 19    | 9     | 
    + FreeBench/pifft/pifft                 | 5     | 3     | 
    + MallocBench/cfrac/cfrac               | 1     | *     | 
    + MallocBench/espresso/espresso         | 52    | 12    | 
    + MallocBench/gs/gs                     | 4     | *     | 
    + Prolangs-C/TimberWolfMC/timberwolfmc  | 302   | *     | 
    + Prolangs-C/agrep/agrep                | 33    | 12    | 
    + Prolangs-C/allroots/allroots          | *     | *     | 
    + Prolangs-C/assembler/assembler        | 47    | *     | 
    + Prolangs-C/bison/mybison              | 74    | *     | 
    + ...
    + 
    +
    + +

    This basically is grepping the -stats output and displaying it in a table. + You can also use the "TEST=libcalls report.html" target to get the table in HTML + form, similarly for report.csv and report.tex.

    + +

    The source for this is in llvm-test/TEST.libcalls.*. The format is pretty + simple: the Makefile indicates how to run the test (in this case, + "opt -simplify-libcalls -stats"), and the report contains one line for + each column of the output. The first value is the header for the column and the + second is the regex to grep the output of the command for. There are lots of + example reports that can do fancy stuff.

    + +
    + + + + + + +
    + +

    + The LLVM Nightly Testers + automatically check out an LLVM tree, build it, run the "nightly" + program test (described above), run all of the feature and regression tests, + and then delete the checked out tree. This tester is designed to ensure that + programs don't break as well as keep track of LLVM's progress over time.

    + +

    If you'd like to set up an instance of the nightly tester to run on your + machine, take a look at the comments at the top of the + utils/NightlyTest.pl file. We usually run it from a crontab entry + that looks like this:

    + +
    +
    + 5 3 * * *  $HOME/llvm/utils/NightlyTest.pl -parallel $CVSROOT \
    +            $HOME/buildtest $HOME/cvs/testresults
    + 
    +
    + +

    Or, you can create a shell script to encapsulate the running of the script. + The optimized x86 Linux nightly test is run from just such a script:

    + +
    +
    + #!/bin/bash
    + BASE=/proj/work/llvm/nightlytest
    + export CVSROOT=:pserver:anon at llvm.org:/var/cvs/llvm
    + export BUILDDIR=$BASE/build 
    + export WEBDIR=$BASE/testresults 
    + export LLVMGCCDIR=/proj/work/llvm/cfrontend/install
    + export PATH=/proj/install/bin:$LLVMGCCDIR/bin:$PATH
    + export LD_LIBRARY_PATH=/proj/install/lib
    + cd $BASE
    + cp /proj/work/llvm/llvm/utils/NightlyTest.pl .
    + nice ./NightlyTest.pl -nice -release -verbose -parallel -enable-linscan \
    +    -noexternals 2>&1 > output.log
    + mail -s 'X86 nightly tester results' llvm-testresults at cs.uiuc.edu < output.log
    + 
    +
    + +

    Take a look at the NightlyTest.pl file to see what all of the flags + and strings do. If you start running the nightly tests, please let us know and + we'll link your page to the global tester page. Thanks!

    + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + John T. Criswell, Reid Spencer, and Tanya Lattner
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + Index: llvm-www/releases/1.8/docs/UsingLibraries.html diff -c /dev/null llvm-www/releases/1.8/docs/UsingLibraries.html:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/UsingLibraries.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,398 ---- + + + + Using The LLVM Libraries + + + +
    Using The LLVM Libraries
    +
      +
    1. Abstract
    2. +
    3. Introduction
    4. +
    5. Library Descriptions
    6. +
    7. Library Dependencies
    8. +
    9. Linkage Rules Of Thumb +
        +
      1. Always link LLVMCore, LLVMSupport, LLVMSystem +
      2. Never link both archive and re-linked +
      +
    10. +
    + +
    +

    Written by Reid Spencer

    +
    + +

    Warning: This document is out of date, please see llvm-config for more information.

    + + + +
    +

    Amongst other things, LLVM is a toolkit for building compilers, linkers, + runtime executives, virtual machines, and other program execution related + tools. In addition to the LLVM tool set, the functionality of LLVM is + available through a set of libraries. To use LLVM as a toolkit for + constructing tools, a developer needs to understand what is contained in the + various libraries, what they depend on, and how to use them. This document + describes the contents of the libraries and how and when to use them. +

    +
    + + + +
    +

    If you're writing a compiler, virtual machine, or any other utility based + on LLVM, you'll need to figure out which of the many libraries files you will + need to link with to be successful. An understanding of the contents of these + files and their inter-relationships will be useful in coming up with an optimal + specification for the libraries to link with. The purpose of this document is + to reduce some of the trial and error that the author experienced in using + LLVM.

    +

    LLVM produces two types of libraries: archives (ending in .a) and + objects (ending in .o). However, both are libraries. Libraries ending + in .o are known as re-linked libraries because they contain all the + compilation units of the library linked together as a single .o file. + Furthermore, many of the libraries have both forms of library. The + re-linked libraries are used whenever you want to include all symbols from the + library. The archive libraries are used whenever you want to only resolve + outstanding symbols at that point in the link without including everything in + the library.

    +

    When linking your tools, you will use the LLVMLIBS make variable. + (see the Makefile Guide for + details). This variable specifies which LLVM libraries to link into your tool + and the order in which they will be linked. You specify re-linked libraries by + naming the library without a suffix. You specify archive libraries by naming + the library with a .a suffix but without the lib prefix. The + order in which the libraries appear in the LLVMLIBS variable + definition is the order in which they will be linked. Getting this order + correct for your tool can sometimes be challenging. +

    + +
    Library Descriptions
    +
    +

    The table below categorizes each library + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    LibraryFormsDescription
    Core Libraries
    LLVMArchive.aLLVM archive reading and writing
    LLVMAsmParser.oLLVM assembly parsing
    LLVMBCReader.oLLVM bytecode reading
    LLVMBCWriter.oLLVM bytecode writing
    LLVMCore.oLLVM core intermediate representation
    LLVMDebugger.oSource level debugging support
    LLVMLinker.aBytecode and archive linking interface
    LLVMSupport.a .oGeneral support utilities
    LLVMSystem.a .oOperating system abstraction layer
    Analysis Libraries
    LLVMAnalysis.a .oVarious analysis passes.
    LLVMDataStructure.a .oData structure analysis passes.
    LLVMipa.a .oInter-procedural analysis passes.
    Transformation Libraries
    LLVMInstrumentation.a .oInstrumentation passes.
    LLVMipo.a .oAll inter-procedural optimization passes.
    LLVMScalarOpts.a .oAll scalar optimization passes.
    LLVMTransforms.a .oUncategorized transformation passes.
    LLVMTransformUtils.a .oTransformation utilities.
    Code Generation Libraries
    LLVMCodeGen.oNative code generation infrastructure
    Target Libraries
    LLVMAlpha.oCode generation for Alpha architecture
    LLVMCBackend.o'C' language code generator.
    LLVMIA64.oCode generation for IA64 architecture
    LLVMPowerPC.oCode generation for PowerPC architecture
    LLVMSelectionDAG.oAggressive instruction selector for directed acyclic graphs
    LLVMSparc.oCode generation for Sparc architecture
    LLVMTarget.a .oGeneric code generation utilities.
    LLVMX86.oCode generation for Intel x86 architecture
    Runtime Libraries
    LLVMInterpreter.oBytecode Interpreter
    LLVMJIT.oBytecode JIT Compiler
    LLVMExecutionEngine.oVirtual machine engine
    +

    + + +
    Library Dependencies
    +
    +

    Below are two dependency graphs and a list that show the relationships + between the various LLVM archive libraries and object files. This information + can be automatically generated with the GenLibDeps.pl utility found + in the llvm/utils directory.

    + + + + + + +

    Dependency Relationships Of Libraries

    +

    This graph shows the dependency of archive libraries on other archive + libraries or objects. Where a library has both archive and object forms, only + the archive form is shown.

    + Library Dependencies +

    Dependency Relationships Of Object Files

    +

    This graph shows the dependency of object files on archive libraries or + other objects. Where a library has both object and archive forms, only the + dependency to the archive form is shown.

    + Object File Dependencies +

    The following list shows the dependency relationships between libraries in + textual form. The information is the same as shown on the graphs but arranged + alphabetically.

    +
    +
    libLLVMAnalysis.a
      +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCore.o
    • +
    +
    libLLVMArchive.a
      +
    • libLLVMSupport.a
    • +
    • libLLVMSystem.a
    • +
    • LLVMBCReader.o
    • +
    • LLVMCore.o
    • +
    +
    libLLVMInstrumentation.a
      +
    • libLLVMScalarOpts.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTransformUtils.a
    • +
    • LLVMCore.o
    • +
    +
    libLLVMLinker.a
      +
    • libLLVMArchive.a
    • +
    • libLLVMSystem.a
    • +
    • LLVMBCReader.o
    • +
    • LLVMCore.o
    • +
    +
    libLLVMScalarOpts.a
      +
    • libLLVMAnalysis.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • libLLVMTransformUtils.a
    • +
    • LLVMCore.o
    • +
    +
    libLLVMSupport.a
      +
    • libLLVMSystem.a
    • +
    • LLVMbzip2.o
    • +
    +
    libLLVMSystem.a
      +
    +
    libLLVMTarget.a
      +
    • libLLVMSupport.a
    • +
    • LLVMCore.o
    • +
    • LLVMSelectionDAG.o
    • +
    +
    libLLVMTransformUtils.a
      +
    • libLLVMAnalysis.a
    • +
    • libLLVMipa.a
    • +
    • libLLVMScalarOpts.a
    • +
    • libLLVMSupport.a
    • +
    • LLVMCore.o
    • +
    +
    libLLVMTransforms.a
      +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • libLLVMTransformUtils.a
    • +
    • LLVMCore.o
    • +
    +
    libLLVMipa.a
      +
    • libLLVMAnalysis.a
    • +
    • libLLVMSupport.a
    • +
    • LLVMCore.o
    • +
    +
    libLLVMipo.a
      +
    • libLLVMAnalysis.a
    • +
    • libLLVMipa.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • libLLVMTransformUtils.a
    • +
    • LLVMCore.o
    • +
    +
    LLVMAlpha.o
      +
    • libLLVMScalarOpts.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCodeGen.o
    • +
    • LLVMCore.o
    • +
    • LLVMSelectionDAG.o
    • +
    +
    LLVMAsmParser.o
      +
    • LLVMCore.o
    • +
    +
    LLVMBCReader.o
      +
    • libLLVMSupport.a
    • +
    • libLLVMSystem.a
    • +
    • LLVMCore.o
    • +
    +
    LLVMBCWriter.o
      +
    • libLLVMSupport.a
    • +
    • LLVMCore.o
    • +
    +
    LLVMCBackend.o
      +
    • libLLVMAnalysis.a
    • +
    • libLLVMipa.a
    • +
    • libLLVMScalarOpts.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCodeGen.o
    • +
    • LLVMCore.o
    • +
    +
    LLVMCodeGen.o
      +
    • libLLVMAnalysis.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCore.o
    • +
    +
    LLVMCore.o
      +
    • libLLVMSupport.a
    • +
    +
    LLVMDataStructure.o
      +
    • libLLVMAnalysis.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCore.o
    • +
    +
    LLVMDebugger.o
      +
    • libLLVMSupport.a
    • +
    • libLLVMSystem.a
    • +
    • LLVMBCReader.o
    • +
    • LLVMCore.o
    • +
    +
    LLVMExecutionEngine.o
      +
    • libLLVMSupport.a
    • +
    • libLLVMSystem.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCore.o
    • +
    +
    LLVMIA64.o
      +
    • libLLVMScalarOpts.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCodeGen.o
    • +
    • LLVMCore.o
    • +
    • LLVMSelectionDAG.o
    • +
    +
    LLVMInterpreter.o
      +
    • libLLVMSupport.a
    • +
    • libLLVMSystem.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCore.o
    • +
    • LLVMExecutionEngine.o
    • +
    +
    LLVMJIT.o
      +
    • libLLVMSupport.a
    • +
    • libLLVMSystem.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCodeGen.o
    • +
    • LLVMCore.o
    • +
    • LLVMExecutionEngine.o
    • +
    +
    LLVMPowerPC.o
      +
    • libLLVMScalarOpts.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCodeGen.o
    • +
    • LLVMCore.o
    • +
    • LLVMSelectionDAG.o
    • +
    +
    LLVMSelectionDAG.o
      +
    • libLLVMSupport.a
    • +
    • libLLVMSystem.a
    • +
    • libLLVMTarget.a
    • +
    • libLLVMTransformUtils.a
    • +
    • LLVMCodeGen.o
    • +
    • LLVMCore.o
    • +
    +
    LLVMSparc.o
      +
    • libLLVMScalarOpts.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCodeGen.o
    • +
    • LLVMCore.o
    • +
    • LLVMSelectionDAG.o
    • +
    +
    LLVMX86.o
      +
    • libLLVMScalarOpts.a
    • +
    • libLLVMSupport.a
    • +
    • libLLVMTarget.a
    • +
    • LLVMCodeGen.o
    • +
    • LLVMCore.o
    • +
    • LLVMSelectionDAG.o
    • +
    +
    LLVMbzip2.o
      +
    +
    +
    + + + +
    +

    This section contains various "rules of thumb" about what files you + should link into your programs.

    +
    + + +
    +

    No matter what you do with LLVM, the last three entries in the value of + your LLVMLIBS make variable should always be: + LLVMCore LLVMSupport.a LLVMSystem.a. There are no LLVM + programs that don't depend on these three.

    +
    + + +
    +

    There is never any point to linking both the re-linked (.o) and + the archive (.a) versions of a library. Since the re-linked version + includes the entire library, the archive version will not resolve any symbols. + You could even end up with link error if you place the archive version before + the re-linked version on the linker's command line.

    +
    + +
    + + + + Index: llvm-www/releases/1.8/docs/WritingAnLLVMBackend.html diff -c /dev/null llvm-www/releases/1.8/docs/WritingAnLLVMBackend.html:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/WritingAnLLVMBackend.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,260 ---- + + + + Writing an LLVM backend + + + + + +
    + Writing an LLVM backend +
    + +
      +
    1. Introduction +
    2. Writing a backend +
        +
      1. Machine backends +
          +
        1. Outline
        2. +
        3. Implementation details
        4. +
      2. +
      3. Language backends
      4. +
    3. +
    4. Related reading material +
    + +
    +

    Written by Misha Brukman

    +
    + + + + + +
    + +

    This document describes techniques for writing backends for LLVM which + convert the LLVM representation to machine assembly code or other languages.

    + +
    + + + + + + + + + +
    + Outline +
    + +
    + +

    In general, you want to follow the format of SPARC, X86 or PowerPC (in + lib/Target). SPARC is the simplest backend, and is RISC, so if + you're working on a RISC target, it is a good one to start with.

    + +

    To create a static compiler (one that emits text assembly), you need to + implement the following:

    + +
      +
    • Describe the register set. +
        +
      • Create a TableGen description of + the register set and register classes
      • +
      • Implement a subclass of MRegisterInfo
      • +
    • +
    • Describe the instruction set. +
    • +
    • Describe the target machine. +
        +
      • Create a TableGen description of + the target that describes the pointer size and references the instruction + set
      • +
      • Implement a subclass of TargetMachine, which + configures TargetData + correctly
      • +
      • Register your new target using the RegisterTarget + template:

        +
        + RegisterTarget<MyTargetMachine> M("short_name", "  Target name");
        + 
        +
        Here, MyTargetMachine is the name of your implemented + subclass of TargetMachine, + short_name is the option that will be active following + -march= to select a target in llc and lli, and the last string + is the description of your target to appear in -help + listing.
      • +
    • +
    • Implement the assembly printer for the architecture. +
        +
      • Define all of the assembly strings for your target, adding them to the + instructions in your *InstrInfo.td file.
      • +
      • Implement the llvm::AsmPrinter interface.
      • +
      +
    • +
    • Implement an instruction selector for the architecture. +
        +
      • The recommended method is the + pattern-matching DAG-to-DAG instruction selector (for example, see + the PowerPC backend in PPCISelDAGtoDAG.cpp). Parts of instruction + selector creation can be performed by adding patterns to the instructions + in your .td file.
      • +
      +
    • +
    • Optionally, add subtarget support. +
        +
      • If your target has multiple subtargets (e.g. variants with different + capabilities), implement the llvm::TargetSubtarget interface + for your architecture. This allows you to add -mcpu= and + -mattr= options.
      • +
      +
    • Optionally, add JIT support. +
        +
      • Create a subclass of TargetJITInfo
      • +
      • Create a machine code emitter that will be used to emit binary code + directly into memory, given MachineInstrs
      • +
      +
    +
    + + + + +
    + +
      + +
    • TableGen register info description - describe a class which + will store the register's number in the binary encoding of the instruction + (e.g., for JIT purposes).

      + +

      You also need to define register classes to contain these registers, such as + the integer register class and floating-point register class, so that you can + allocate virtual registers to instructions from these sets, and let the + target-independent register allocator automatically choose the actual + architected registers.

      + +
      +
      + // class Register is defined in Target.td
      + class TargetReg<string name> : Register<name> {
      +   let Namespace = "Target";
      + }
      + 
      + class IntReg<bits<5> num, string name> : TargetReg<name> {
      +   field bits<5> Num = num;
      + }
      + 
      + def R0 : IntReg<0, "%R0">;
      + ...
      + 
      + // class RegisterClass is defined in Target.td
      + def IReg : RegisterClass<i64, 64, [R0, ... ]>;
      + 
      +
      +
    • + +
    • TableGen instruction info description - break up instructions into + classes, usually that's already done by the manufacturer (see instruction + manual). Define a class for each instruction category. Define each opcode as a + subclass of the category, with appropriate parameters such as the fixed binary + encoding of opcodes and extended opcodes, and map the register bits to the bits + of the instruction which they are encoded in (for the JIT). Also specify how + the instruction should be printed so it can use the automatic assembly printer, + e.g.:

      + +
      +
      + // class Instruction is defined in Target.td
      + class Form<bits<6> opcode, dag OL, string asmstr> : Instruction {
      +   field bits<42> Inst;
      + 
      +   let Namespace = "Target";
      +   let Inst{0-6} = opcode;
      +   let OperandList = OL;
      +   let AsmString = asmstr;
      + }
      + 
      + def ADD : Form<42, (ops IReg:$rD, IReg:$rA, IReg:$rB), "add $rD, $rA, $rB">;
      + 
      +
      +
    • + +
    + +
    + + + + +
    + +

    For now, just take a look at lib/Target/CBackend for an example of + how the C backend is written.

    + +
    + + + + + +
    + + + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Misha Brukman
    + The LLVM Compiler Infrastructure +
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/WritingAnLLVMPass.html diff -c /dev/null llvm-www/releases/1.8/docs/WritingAnLLVMPass.html:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/WritingAnLLVMPass.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,1600 ---- + + + + + Writing an LLVM Pass + + + + +
    + Writing an LLVM Pass +
    + +
      +
    1. Introduction - What is a pass?
    2. +
    3. Quick Start - Writing hello world +
    4. +
    5. Pass classes and requirements + +
    6. Pass Registration +
    7. +
    8. Specifying interactions between passes +
    9. +
    10. Implementing Analysis Groups +
    11. +
    12. Pass Statistics +
    13. What PassManager does +
    14. +
    15. Using GDB with dynamically loaded passes +
    16. +
    17. Future extensions planned +
    18. +
    + +
    +

    Written by Chris Lattner

    +
    + + + + + +
    + +

    The LLVM Pass Framework is an important part of the LLVM system, because LLVM + passes are where most of the interesting parts of the compiler exist. Passes + perform the transformations and optimizations that make up the compiler, they + build the analysis results that are used by these transformations, and they are, + above all, a structuring technique for compiler code.

    + +

    All LLVM passes are subclasses of the Pass + class, which implement functionality by overriding virtual methods inherited + from Pass. Depending on how your pass works, you should inherit from + the ModulePass, CallGraphSCCPass, FunctionPass, or BasicBlockPass classes, which gives the system + more information about what your pass does, and how it can be combined with + other passes. One of the main features of the LLVM Pass Framework is that it + schedules passes to run in an efficient way based on the constraints that your + pass meets (which are indicated by which class they derive from).

    + +

    We start by showing you how to construct a pass, everything from setting up + the code, to compiling, loading, and executing it. After the basics are down, + more advanced features are discussed.

    + +
    + + + + + +
    + +

    Here we describe how to write the "hello world" of passes. The "Hello" pass + is designed to simply print out the name of non-external functions that exist in + the program being compiled. It does not modify the program at all, it just + inspects it. The source code and files for this pass are available in the LLVM + source tree in the lib/Transforms/Hello directory.

    + +
    + + + + +
    + +

    First, you need to create a new directory somewhere in the LLVM source + base. For this example, we'll assume that you made + lib/Transforms/Hello. Next, you must set up a build script + (Makefile) that will compile the source code for the new pass. To do this, + copy the following into Makefile:

    +
    + +
    + # Makefile for hello pass
    + 
    + # Path to top level of LLVM heirarchy
    + LEVEL = ../../..
    + 
    + # Name of the library to build
    + LIBRARYNAME = Hello
    + 
    + # Build a dynamically linkable shared object
    + SHARED_LIBRARY = 1
    + 
    + # Make the shared library become a loadable module so the tools can 
    + # dlopen/dlsym on the resulting library.
    + LOADABLE_MODULE = 1
    + 
    + # Include the makefile implementation stuff
    + include $(LEVEL)/Makefile.common
    + 
    + +

    This makefile specifies that all of the .cpp files in the current + directory are to be compiled and linked together into a + Debug/lib/Hello.so shared object that can be dynamically loaded by + the opt or analyze tools via their -load options. + If your operating system uses a suffix other than .so (such as windows or + Mac OS/X), the appropriate extension will be used.

    + +

    Now that we have the build scripts set up, we just need to write the code for + the pass itself.

    + +
    + + + + +
    + +

    Now that we have a way to compile our new pass, we just have to write it. + Start out with:

    + +
    + #include "llvm/Pass.h"
    + #include "llvm/Function.h"
    + 
    + +

    Which are needed because we are writing a Pass, and + we are operating on Function's.

    + +

    Next we have:

    +
    + using namespace llvm;
    + 
    +

    ... which is required because the functions from the include files + live in the llvm namespace. +

    + +

    Next we have:

    + +
    + namespace {
    + 
    + +

    ... which starts out an anonymous namespace. Anonymous namespaces are to C++ + what the "static" keyword is to C (at global scope). It makes the + things declared inside of the anonymous namespace only visible to the current + file. If you're not familiar with them, consult a decent C++ book for more + information.

    + +

    Next, we declare our pass itself:

    + +
    +   struct Hello : public FunctionPass {
    + 

    + +

    This declares a "Hello" class that is a subclass of FunctionPass. + The different builtin pass subclasses are described in detail later, but for now, know that FunctionPass's operate a function at a + time.

    + +
    +     virtual bool runOnFunction(Function &F) {
    +       std::cerr << "Hello: " << F.getName() << "\n";
    +       return false;
    +     }
    +   };  // end of struct Hello
    + 
    + +

    We declare a "runOnFunction" method, + which overloads an abstract virtual method inherited from FunctionPass. This is where we are supposed + to do our thing, so we just print out our message with the name of each + function.

    + +
    +   RegisterOpt<Hello> X("hello", "Hello World Pass");
    + }  // end of anonymous namespace
    + 
    + +

    Lastly, we register our class Hello, giving it a command line + argument "hello", and a name "Hello World Pass". There are + several different ways of registering your pass, + depending on what it is to be used for. For "optimizations" we use the + RegisterOpt template.

    + +

    As a whole, the .cpp file looks like:

    + +
    + #include "llvm/Pass.h"
    + #include "llvm/Function.h"
    + 
    + using namespace llvm;
    + 
    + namespace {
    +   struct Hello : public FunctionPass {
    +     virtual bool runOnFunction(Function &F) {
    +       std::cerr << "Hello: " << F.getName() << "\n";
    +       return false;
    +     }
    +   };
    +   
    +   RegisterOpt<Hello> X("hello", "Hello World Pass");
    + }
    + 
    + +

    Now that it's all together, compile the file with a simple "gmake" + command in the local directory and you should get a new + "Debug/lib/Hello.so file. Note that everything in this file is + contained in an anonymous namespace: this reflects the fact that passes are self + contained units that do not need external interfaces (although they can have + them) to be useful.

    + +
    + + + + +
    + +

    Now that you have a brand new shiny shared object file, we can use the + opt command to run an LLVM program through your pass. Because you + registered your pass with the RegisterOpt template, you will be able to + use the opt tool to access it, once loaded.

    + +

    To test it, follow the example at the end of the Getting Started Guide to compile "Hello World" to + LLVM. We can now run the bytecode file (hello.bc) for the program + through our transformation like this (or course, any bytecode file will + work):

    + +
    + $ opt -load ../../../Debug/lib/Hello.so -hello < hello.bc > /dev/null
    + Hello: __main
    + Hello: puts
    + Hello: main
    + 
    + +

    The '-load' option specifies that 'opt' should load your + pass as a shared object, which makes '-hello' a valid command line + argument (which is one reason you need to register your + pass). Because the hello pass does not modify the program in any + interesting way, we just throw away the result of opt (sending it to + /dev/null).

    + +

    To see what happened to the other string you registered, try running + opt with the --help option:

    + +
    + $ opt -load ../../../Debug/lib/Hello.so --help
    + OVERVIEW: llvm .bc -> .bc modular optimizer
    + 
    + USAGE: opt [options] <input bytecode>
    + 
    + OPTIONS:
    +   Optimizations available:
    + ...
    +     -funcresolve    - Resolve Functions
    +     -gcse           - Global Common Subexpression Elimination
    +     -globaldce      - Dead Global Elimination
    +     -hello          - Hello World Pass
    +     -indvars        - Canonicalize Induction Variables
    +     -inline         - Function Integration/Inlining
    +     -instcombine    - Combine redundant instructions
    + ...
    + 
    + +

    The pass name get added as the information string for your pass, giving some + documentation to users of opt. Now that you have a working pass, you + would go ahead and make it do the cool transformations you want. Once you get + it all working and tested, it may become useful to find out how fast your pass + is. The PassManager provides a nice command + line option (--time-passes) that allows you to get information about + the execution time of your pass along with the other passes you queue up. For + example:

    + +
    + $ opt -load ../../../Debug/lib/Hello.so -hello -time-passes < hello.bc > /dev/null
    + Hello: __main
    + Hello: puts
    + Hello: main
    + ===============================================================================
    +                       ... Pass execution timing report ...
    + ===============================================================================
    +   Total Execution Time: 0.02 seconds (0.0479059 wall clock)
    + 
    +    ---User Time---   --System Time--   --User+System--   ---Wall Time---  --- Pass Name ---
    +    0.0100 (100.0%)   0.0000 (  0.0%)   0.0100 ( 50.0%)   0.0402 ( 84.0%)  Bytecode Writer
    +    0.0000 (  0.0%)   0.0100 (100.0%)   0.0100 ( 50.0%)   0.0031 (  6.4%)  Dominator Set Construction
    +    0.0000 (  0.0%)   0.0000 (  0.0%)   0.0000 (  0.0%)   0.0013 (  2.7%)  Module Verifier
    +    0.0000 (  0.0%)   0.0000 (  0.0%)   0.0000 (  0.0%)   0.0033 (  6.9%)  Hello World Pass
    +    0.0100 (100.0%)   0.0100 (100.0%)   0.0200 (100.0%)   0.0479 (100.0%)  TOTAL
    + 
    + +

    As you can see, our implementation above is pretty fast :). The additional + passes listed are automatically inserted by the 'opt' tool to verify + that the LLVM emitted by your pass is still valid and well formed LLVM, which + hasn't been broken somehow.

    + +

    Now that you have seen the basics of the mechanics behind passes, we can talk + about some more details of how they work and how to use them.

    + +
    + + + + + +
    + +

    One of the first things that you should do when designing a new pass is to + decide what class you should subclass for your pass. The Hello World example uses the FunctionPass class for its implementation, but we + did not discuss why or when this should occur. Here we talk about the classes + available, from the most general to the most specific.

    + +

    When choosing a superclass for your Pass, you should choose the most + specific class possible, while still being able to meet the requirements + listed. This gives the LLVM Pass Infrastructure information necessary to + optimize how passes are run, so that the resultant compiler isn't unneccesarily + slow.

    + +
    + + + + +
    + +

    The most plain and boring type of pass is the "ImmutablePass" + class. This pass type is used for passes that do not have to be run, do not + change state, and never need to be updated. This is not a normal type of + transformation or analysis, but can provide information about the current + compiler configuration.

    + +

    Although this pass class is very infrequently used, it is important for + providing information about the current target machine being compiled for, and + other static information that can affect the various transformations.

    + +

    ImmutablePasses never invalidate other transformations, are never + invalidated, and are never "run".

    + +
    + + + + +
    + +

    The "ModulePass" + class is the most general of all superclasses that you can use. Deriving from + ModulePass indicates that your pass uses the entire program as a unit, + refering to function bodies in no predictable order, or adding and removing + functions. Because nothing is known about the behavior of ModulePass + subclasses, no optimization can be done for their execution.

    + +

    To write a correct ModulePass subclass, derive from + ModulePass and overload the runOnModule method with the + following signature:

    + +
    + + + + +
    + +
    +   virtual bool runOnModule(Module &M) = 0;
    + 
    + +

    The runOnModule method performs the interesting work of the pass. + It should return true if the module was modified by the transformation and + false otherwise.

    + +
    + + + + +
    + +

    The "CallGraphSCCPass" + is used by passes that need to traverse the program bottom-up on the call graph + (callees before callers). Deriving from CallGraphSCCPass provides some + mechanics for building and traversing the CallGraph, but also allows the system + to optimize execution of CallGraphSCCPass's. If your pass meets the + requirements outlined below, and doesn't meet the requirements of a FunctionPass or BasicBlockPass, you should derive from + CallGraphSCCPass.

    + +

    TODO: explain briefly what SCC, Tarjan's algo, and B-U mean.

    + +

    To be explicit, CallGraphSCCPass subclasses are:

    + +
      + +
    1. ... not allowed to modify any Functions that are not in + the current SCC.
    2. + +
    3. ... allowed to inspect any Function's other than those in the + current SCC and the direct callees of the SCC.
    4. + +
    5. ... required to preserve the current CallGraph object, updating it + to reflect any changes made to the program.
    6. + +
    7. ... not allowed to add or remove SCC's from the current Module, + though they may change the contents of an SCC.
    8. + +
    9. ... allowed to add or remove global variables from the current + Module.
    10. + +
    11. ... allowed to maintain state across invocations of + runOnSCC (including global data).
    12. +
    + +

    Implementing a CallGraphSCCPass is slightly tricky in some cases + because it has to handle SCCs with more than one node in it. All of the virtual + methods described below should return true if they modified the program, or + false if they didn't.

    + +
    + + + + +
    + +
    +   virtual bool doInitialization(Module &M);
    + 
    + +

    The doIninitialize method is allowed to do most of the things that + CallGraphSCCPass's are not allowed to do. They can add and remove + functions, get pointers to functions, etc. The doInitialization method + is designed to do simple initialization type of stuff that does not depend on + the SCCs being processed. The doInitialization method call is not + scheduled to overlap with any other pass executions (thus it should be very + fast).

    + +
    + + + + +
    + +
    +   virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCCM) = 0;
    + 
    + +

    The runOnSCC method performs the interesting work of the pass, and + should return true if the module was modified by the transformation, false + otherwise.

    + +
    + + + + +
    + +
    +   virtual bool doFinalization(Module &M);
    + 
    + +

    The doFinalization method is an infrequently used method that is + called when the pass framework has finished calling runOnFunction for every function in the + program being compiled.

    + +
    + + + + +
    + +

    In contrast to ModulePass subclasses, FunctionPass + subclasses do have a predictable, local behavior that can be expected by the + system. All FunctionPass execute on each function in the program + independent of all of the other functions in the program. + FunctionPass's do not require that they are executed in a particular + order, and FunctionPass's do not modify external functions.

    + +

    To be explicit, FunctionPass subclasses are not allowed to:

    + +
      +
    1. Modify a Function other than the one currently being processed.
    2. +
    3. Add or remove Function's from the current Module.
    4. +
    5. Add or remove global variables from the current Module.
    6. +
    7. Maintain state across invocations of + runOnFunction (including global data)
    8. +
    + +

    Implementing a FunctionPass is usually straightforward (See the Hello World pass for example). FunctionPass's + may overload three virtual methods to do their work. All of these methods + should return true if they modified the program, or false if they didn't.

    + +
    + + + + +
    + +
    +   virtual bool doInitialization(Module &M);
    + 
    + +

    The doIninitialize method is allowed to do most of the things that + FunctionPass's are not allowed to do. They can add and remove + functions, get pointers to functions, etc. The doInitialization method + is designed to do simple initialization type of stuff that does not depend on + the functions being processed. The doInitialization method call is not + scheduled to overlap with any other pass executions (thus it should be very + fast).

    + +

    A good example of how this method should be used is the LowerAllocations + pass. This pass converts malloc and free instructions into + platform dependent malloc() and free() function calls. It + uses the doInitialization method to get a reference to the malloc and + free functions that it needs, adding prototypes to the module if necessary.

    + +
    + + + + +
    + +
    +   virtual bool runOnFunction(Function &F) = 0;
    + 

    + +

    The runOnFunction method must be implemented by your subclass to do + the transformation or analysis work of your pass. As usual, a true value should + be returned if the function is modified.

    + +
    + + + + +
    + +
    +   virtual bool doFinalization(Module &M);
    + 
    + +

    The doFinalization method is an infrequently used method that is + called when the pass framework has finished calling runOnFunction for every function in the + program being compiled.

    + +
    + + + + +
    + +

    BasicBlockPass's are just like FunctionPass's, except that they must limit + their scope of inspection and modification to a single basic block at a time. + As such, they are not allowed to do any of the following:

    + +
      +
    1. Modify or inspect any basic blocks outside of the current one
    2. +
    3. Maintain state across invocations of + runOnBasicBlock
    4. +
    5. Modify the control flow graph (by altering terminator instructions)
    6. +
    7. Any of the things forbidden for + FunctionPasses.
    8. +
    + +

    BasicBlockPasses are useful for traditional local and "peephole" + optimizations. They may override the same doInitialization(Module &) and doFinalization(Module &) methods that FunctionPass's have, but also have the following virtual methods that may also be implemented:

    + +
    + + + + +
    + +
    +   virtual bool doInitialization(Function &F);
    + 
    + +

    The doIninitialize method is allowed to do most of the things that + BasicBlockPass's are not allowed to do, but that + FunctionPass's can. The doInitialization method is designed + to do simple initialization that does not depend on the + BasicBlocks being processed. The doInitialization method call is not + scheduled to overlap with any other pass executions (thus it should be very + fast).

    + +
    + + + + +
    + +
    +   virtual bool runOnBasicBlock(BasicBlock &BB) = 0;
    + 
    + +

    Override this function to do the work of the BasicBlockPass. This + function is not allowed to inspect or modify basic blocks other than the + parameter, and are not allowed to modify the CFG. A true value must be returned + if the basic block is modified.

    + +
    + + + + +
    + +
    +   virtual bool doFinalization(Function &F);
    + 
    + +

    The doFinalization method is an infrequently used method that is + called when the pass framework has finished calling runOnBasicBlock for every BasicBlock in the + program being compiled. This can be used to perform per-function + finalization.

    + +
    + + + + +
    + +

    A MachineFunctionPass is a part of the LLVM code generator that + executes on the machine-dependent representation of each LLVM function in the + program. A MachineFunctionPass is also a FunctionPass, so all + the restrictions that apply to a FunctionPass also apply to it. + MachineFunctionPasses also have additional restrictions. In particular, + MachineFunctionPasses are not allowed to do any of the following:

    + +
      +
    1. Modify any LLVM Instructions, BasicBlocks or Functions.
    2. +
    3. Modify a MachineFunction other than the one currently being processed.
    4. +
    5. Add or remove MachineFunctions from the current Module.
    6. +
    7. Add or remove global variables from the current Module.
    8. +
    9. Maintain state across invocations of runOnMachineFunction (including global + data)
    10. +
    + +
    + + + + +
    + +
    +   virtual bool runOnMachineFunction(MachineFunction &MF) = 0;
    + 
    + +

    runOnMachineFunction can be considered the main entry point of a + MachineFunctionPass; that is, you should override this method to do the + work of your MachineFunctionPass.

    + +

    The runOnMachineFunction method is called on every + MachineFunction in a Module, so that the + MachineFunctionPass may perform optimizations on the machine-dependent + representation of the function. If you want to get at the LLVM Function + for the MachineFunction you're working on, use + MachineFunction's getFunction() accessor method -- but + remember, you may not modify the LLVM Function or its contents from a + MachineFunctionPass.

    + +
    + + + + + +
    + +

    In the Hello World example pass we illustrated how + pass registration works, and discussed some of the reasons that it is used and + what it does. Here we discuss how and why passes are registered.

    + +

    Passes can be registered in several different ways. Depending on the general + classification of the pass, you should use one of the following templates to + register the pass:

    + +
      +
    • RegisterOpt - This template should be used when you are + registering a pass that logically should be available for use in the + 'opt' utility.
    • + +
    • RegisterAnalysis - This template should be used when you are + registering a pass that logically should be available for use in the + 'analyze' utility.
    • + +
    • RegisterPass - This is the generic form of the + Register* templates that should be used if you want your pass listed by + multiple or no utilities. This template takes an extra third argument that + specifies which tools it should be listed in. See the PassSupport.h + file for more information.
    • + +
    + +

    Regardless of how you register your pass, you must specify at least two + parameters. The first parameter is the name of the pass that is to be used on + the command line to specify that the pass should be added to a program (for + example opt or analyze). The second argument is the name of + the pass, which is to be used for the --help output of programs, as + well as for debug output generated by the --debug-pass option.

    + +

    If a pass is registered to be used by the analyze utility, you + should implement the virtual print method:

    + +
    + + + + +
    + +
    +   virtual void print(std::ostream &O, const Module *M) const;
    + 
    + +

    The print method must be implemented by "analyses" in order to print + a human readable version of the analysis results. This is useful for debugging + an analysis itself, as well as for other people to figure out how an analysis + works. The analyze tool uses this method to generate its output.

    + +

    The ostream parameter specifies the stream to write the results on, + and the Module parameter gives a pointer to the top level module of the + program that has been analyzed. Note however that this pointer may be null in + certain circumstances (such as calling the Pass::dump() from a + debugger), so it should only be used to enhance debug output, it should not be + depended on.

    + +
    + + + + + +
    + +

    One of the main responsibilities of the PassManager is the make sure + that passes interact with each other correctly. Because PassManager + tries to optimize the execution of passes it must + know how the passes interact with each other and what dependencies exist between + the various passes. To track this, each pass can declare the set of passes that + are required to be executed before the current pass, and the passes which are + invalidated by the current pass.

    + +

    Typically this functionality is used to require that analysis results are + computed before your pass is run. Running arbitrary transformation passes can + invalidate the computed analysis results, which is what the invalidation set + specifies. If a pass does not implement the getAnalysisUsage method, it defaults to not + having any prerequisite passes, and invalidating all other passes.

    + +
    + + + + +
    + +
    +   virtual void getAnalysisUsage(AnalysisUsage &Info) const;
    + 
    + +

    By implementing the getAnalysisUsage method, the required and + invalidated sets may be specified for your transformation. The implementation + should fill in the AnalysisUsage + object with information about which passes are required and not invalidated. To + do this, a pass may call any of the following methods on the AnalysisUsage + object:

    +
    + + + + +
    +

    + If your pass requires a previous pass to be executed (an analysis for example), + it can use one of these methods to arrange for it to be run before your pass. + LLVM has many different types of analyses and passes that can be required, + spanning the range from DominatorSet to BreakCriticalEdges. + Requiring BreakCriticalEdges, for example, guarantees that there will + be no critical edges in the CFG when your pass has been run. +

    + +

    + Some analyses chain to other analyses to do their job. For example, an AliasAnalysis implementation is required to chain to other alias analysis passes. In + cases where analyses chain, the addRequiredTransitive method should be + used instead of the addRequired method. This informs the PassManager + that the transitively required pass should be alive as long as the requiring + pass is. +

    +
    + + + + +
    +

    + One of the jobs of the PassManager is to optimize how and when analyses are run. + In particular, it attempts to avoid recomputing data unless it needs to. For + this reason, passes are allowed to declare that they preserve (i.e., they don't + invalidate) an existing analysis if it's available. For example, a simple + constant folding pass would not modify the CFG, so it can't possibly affect the + results of dominator analysis. By default, all passes are assumed to invalidate + all others. +

    + +

    + The AnalysisUsage class provides several methods which are useful in + certain circumstances that are related to addPreserved. In particular, + the setPreservesAll method can be called to indicate that the pass does + not modify the LLVM program at all (which is true for analyses), and the + setPreservesCFG method can be used by transformations that change + instructions in the program but do not modify the CFG or terminator instructions + (note that this property is implicitly set for BasicBlockPass's). +

    + +

    + addPreserved is particularly useful for transformations like + BreakCriticalEdges. This pass knows how to update a small set of loop + and dominator related analyses if they exist, so it can preserve them, despite + the fact that it hacks on the CFG. +

    +
    + + + + +
    + +
    +   // This is an example implementation from an analysis, which does not modify
    +   // the program at all, yet has a prerequisite.
    +   void PostDominanceFrontier::getAnalysisUsage(AnalysisUsage &AU) const {
    +     AU.setPreservesAll();
    +     AU.addRequired<PostDominatorTree>();
    +   }
    + 
    + +

    and:

    + +
    +   // This example modifies the program, but does not modify the CFG
    +   void LICM::getAnalysisUsage(AnalysisUsage &AU) const {
    +     AU.setPreservesCFG();
    +     AU.addRequired<LoopInfo>();
    +   }
    + 
    + +
    + + + + +
    + +

    The Pass::getAnalysis<> method is automatically inherited by + your class, providing you with access to the passes that you declared that you + required with the getAnalysisUsage + method. It takes a single template argument that specifies which pass class you + want, and returns a reference to that pass. For example:

    + +
    +    bool LICM::runOnFunction(Function &F) {
    +      LoopInfo &LI = getAnalysis<LoopInfo>();
    +      ...
    +    }
    + 
    + +

    This method call returns a reference to the pass desired. You may get a + runtime assertion failure if you attempt to get an analysis that you did not + declare as required in your getAnalysisUsage implementation. This + method can be called by your run* method implementation, or by any + other local method invoked by your run* method.

    + +

    + If your pass is capable of updating analyses if they exist (e.g., + BreakCriticalEdges, as described above), you can use the + getAnalysisToUpdate method, which returns a pointer to the analysis if + it is active. For example:

    + +
    +   ...
    +   if (DominatorSet *DS = getAnalysisToUpdate<DominatorSet>()) {
    +     // A DominatorSet is active.  This code will update it.
    +   }
    +   ...
    + 
    + +
    + + + + + +
    + +

    Now that we understand the basics of how passes are defined, how the are + used, and how they are required from other passes, it's time to get a little bit + fancier. All of the pass relationships that we have seen so far are very + simple: one pass depends on one other specific pass to be run before it can run. + For many applications, this is great, for others, more flexibility is + required.

    + +

    In particular, some analyses are defined such that there is a single simple + interface to the analysis results, but multiple ways of calculating them. + Consider alias analysis for example. The most trivial alias analysis returns + "may alias" for any alias query. The most sophisticated analysis a + flow-sensitive, context-sensitive interprocedural analysis that can take a + significant amount of time to execute (and obviously, there is a lot of room + between these two extremes for other implementations). To cleanly support + situations like this, the LLVM Pass Infrastructure supports the notion of + Analysis Groups.

    + +
    + + + + +
    + +

    An Analysis Group is a single simple interface that may be implemented by + multiple different passes. Analysis Groups can be given human readable names + just like passes, but unlike passes, they need not derive from the Pass + class. An analysis group may have one or more implementations, one of which is + the "default" implementation.

    + +

    Analysis groups are used by client passes just like other passes are: the + AnalysisUsage::addRequired() and Pass::getAnalysis() methods. + In order to resolve this requirement, the PassManager + scans the available passes to see if any implementations of the analysis group + are available. If none is available, the default implementation is created for + the pass to use. All standard rules for interaction + between passes still apply.

    + +

    Although Pass Registration is optional for normal + passes, all analysis group implementations must be registered, and must use the + RegisterAnalysisGroup template to join the + implementation pool. Also, a default implementation of the interface + must be registered with RegisterAnalysisGroup.

    + +

    As a concrete example of an Analysis Group in action, consider the AliasAnalysis + analysis group. The default implementation of the alias analysis interface (the + basicaa + pass) just does a few simple checks that don't require significant analysis to + compute (such as: two different globals can never alias each other, etc). + Passes that use the AliasAnalysis + interface (for example the gcse pass), do + not care which implementation of alias analysis is actually provided, they just + use the designated interface.

    + +

    From the user's perspective, commands work just like normal. Issuing the + command 'opt -gcse ...' will cause the basicaa class to be + instantiated and added to the pass sequence. Issuing the command 'opt + -somefancyaa -gcse ...' will cause the gcse pass to use the + somefancyaa alias analysis (which doesn't actually exist, it's just a + hypothetical example) instead.

    + +
    + + + + +
    + +

    The RegisterAnalysisGroup template is used to register the analysis + group itself as well as add pass implementations to the analysis group. First, + an analysis should be registered, with a human readable name provided for it. + Unlike registration of passes, there is no command line argument to be specified + for the Analysis Group Interface itself, because it is "abstract":

    + +
    +   static RegisterAnalysisGroup<AliasAnalysis> A("Alias Analysis");
    + 
    + +

    Once the analysis is registered, passes can declare that they are valid + implementations of the interface by using the following code:

    + +
    + namespace {
    +   // Analysis Group implementations must be registered normally...
    +   RegisterOpt<FancyAA>
    +   B("somefancyaa", "A more complex alias analysis implementation");
    + 
    +   // Declare that we implement the AliasAnalysis interface
    +   RegisterAnalysisGroup<AliasAnalysis, FancyAA> C;
    + }
    + 
    + +

    This just shows a class FancyAA that is registered normally, then + uses the RegisterAnalysisGroup template to "join" the AliasAnalysis + analysis group. Every implementation of an analysis group should join using + this template. A single pass may join multiple different analysis groups with + no problem.

    + +
    + namespace {
    +   // Analysis Group implementations must be registered normally...
    +   RegisterOpt<BasicAliasAnalysis>
    +   D("basicaa", "Basic Alias Analysis (default AA impl)");
    + 
    +   // Declare that we implement the AliasAnalysis interface
    +   RegisterAnalysisGroup<AliasAnalysis, BasicAliasAnalysis, true> E;
    + }
    + 
    + +

    Here we show how the default implementation is specified (using the extra + argument to the RegisterAnalysisGroup template). There must be exactly + one default implementation available at all times for an Analysis Group to be + used. Here we declare that the BasicAliasAnalysis + pass is the default implementation for the interface.

    + +
    + + + + + +
    +

    The Statistic + class is designed to be an easy way to expose various success + metrics from passes. These statistics are printed at the end of a + run, when the -stats command line option is enabled on the command + line. See the Statistics section in the Programmer's Manual for details. + +

    + + + + + + +
    + +

    The PassManager + class + takes a list of passes, ensures their prerequisites + are set up correctly, and then schedules passes to run efficiently. All of the + LLVM tools that run passes use the PassManager for execution of these + passes.

    + +

    The PassManager does two main things to try to reduce the execution + time of a series of passes:

    + +
      +
    1. Share analysis results - The PassManager attempts to avoid + recomputing analysis results as much as possible. This means keeping track of + which analyses are available already, which analyses get invalidated, and which + analyses are needed to be run for a pass. An important part of work is that the + PassManager tracks the exact lifetime of all analysis results, allowing + it to free memory allocated to holding analysis + results as soon as they are no longer needed.
    2. + +
    3. Pipeline the execution of passes on the program - The + PassManager attempts to get better cache and memory usage behavior out + of a series of passes by pipelining the passes together. This means that, given + a series of consequtive FunctionPass's, it + will execute all of the FunctionPass's on + the first function, then all of the FunctionPasses on the second function, + etc... until the entire program has been run through the passes. + +

      This improves the cache behavior of the compiler, because it is only touching + the LLVM program representation for a single function at a time, instead of + traversing the entire program. It reduces the memory consumption of compiler, + because, for example, only one DominatorSet + needs to be calculated at a time. This also makes it possible some interesting enhancements in the future.

    4. + +
    + +

    The effectiveness of the PassManager is influenced directly by how + much information it has about the behaviors of the passes it is scheduling. For + example, the "preserved" set is intentionally conservative in the face of an + unimplemented getAnalysisUsage method. + Not implementing when it should be implemented will have the effect of not + allowing any analysis results to live across the execution of your pass.

    + +

    The PassManager class exposes a --debug-pass command line + options that is useful for debugging pass execution, seeing how things work, and + diagnosing when you should be preserving more analyses than you currently are + (To get information about all of the variants of the --debug-pass + option, just type 'opt --help-hidden').

    + +

    By using the --debug-pass=Structure option, for example, we can see + how our Hello World pass interacts with other passes. + Lets try it out with the gcse and licm passes:

    + +
    + $ opt -load ../../../Debug/lib/Hello.so -gcse -licm --debug-pass=Structure < hello.bc > /dev/null
    + Module Pass Manager
    +   Function Pass Manager
    +     Dominator Set Construction
    +     Immediate Dominators Construction
    +     Global Common Subexpression Elimination
    + --  Immediate Dominators Construction
    + --  Global Common Subexpression Elimination
    +     Natural Loop Construction
    +     Loop Invariant Code Motion
    + --  Natural Loop Construction
    + --  Loop Invariant Code Motion
    +     Module Verifier
    + --  Dominator Set Construction
    + --  Module Verifier
    +   Bytecode Writer
    + --Bytecode Writer
    + 
    + +

    This output shows us when passes are constructed and when the analysis + results are known to be dead (prefixed with '--'). Here we see that + GCSE uses dominator and immediate dominator information to do its job. The LICM + pass uses natural loop information, which uses dominator sets, but not immediate + dominators. Because immediate dominators are no longer useful after the GCSE + pass, it is immediately destroyed. The dominator sets are then reused to + compute natural loop information, which is then used by the LICM pass.

    + +

    After the LICM pass, the module verifier runs (which is automatically added + by the 'opt' tool), which uses the dominator set to check that the + resultant LLVM code is well formed. After it finishes, the dominator set + information is destroyed, after being computed once, and shared by three + passes.

    + +

    Lets see how this changes when we run the Hello + World pass in between the two passes:

    + +
    + $ opt -load ../../../Debug/lib/Hello.so -gcse -hello -licm --debug-pass=Structure < hello.bc > /dev/null
    + Module Pass Manager
    +   Function Pass Manager
    +     Dominator Set Construction
    +     Immediate Dominators Construction
    +     Global Common Subexpression Elimination
    + --  Dominator Set Construction
    + --  Immediate Dominators Construction
    + --  Global Common Subexpression Elimination
    +     Hello World Pass
    + --  Hello World Pass
    +     Dominator Set Construction
    +     Natural Loop Construction
    +     Loop Invariant Code Motion
    + --  Natural Loop Construction
    + --  Loop Invariant Code Motion
    +     Module Verifier
    + --  Dominator Set Construction
    + --  Module Verifier
    +   Bytecode Writer
    + --Bytecode Writer
    + Hello: __main
    + Hello: puts
    + Hello: main
    + 
    + +

    Here we see that the Hello World pass has killed the + Dominator Set pass, even though it doesn't modify the code at all! To fix this, + we need to add the following getAnalysisUsage method to our pass:

    + +
    +     // We don't modify the program, so we preserve all analyses
    +     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    +       AU.setPreservesAll();
    +     }
    + 
    + +

    Now when we run our pass, we get this output:

    + +
    + $ opt -load ../../../Debug/lib/Hello.so -gcse -hello -licm --debug-pass=Structure < hello.bc > /dev/null
    + Pass Arguments:  -gcse -hello -licm
    + Module Pass Manager
    +   Function Pass Manager
    +     Dominator Set Construction
    +     Immediate Dominators Construction
    +     Global Common Subexpression Elimination
    + --  Immediate Dominators Construction
    + --  Global Common Subexpression Elimination
    +     Hello World Pass
    + --  Hello World Pass
    +     Natural Loop Construction
    +     Loop Invariant Code Motion
    + --  Loop Invariant Code Motion
    + --  Natural Loop Construction
    +     Module Verifier
    + --  Dominator Set Construction
    + --  Module Verifier
    +   Bytecode Writer
    + --Bytecode Writer
    + Hello: __main
    + Hello: puts
    + Hello: main
    + 
    + +

    Which shows that we don't accidentally invalidate dominator information + anymore, and therefore do not have to compute it twice.

    + +
    + + + + +
    + +
    +   virtual void releaseMemory();
    + 
    + +

    The PassManager automatically determines when to compute analysis + results, and how long to keep them around for. Because the lifetime of the pass + object itself is effectively the entire duration of the compilation process, we + need some way to free analysis results when they are no longer useful. The + releaseMemory virtual method is the way to do this.

    + +

    If you are writing an analysis or any other pass that retains a significant + amount of state (for use by another pass which "requires" your pass and uses the + getAnalysis method) you should implement + releaseMEmory to, well, release the memory allocated to maintain this + internal state. This method is called after the run* method for the + class, before the next call of run* in your pass.

    + +
    + + + + + +
    + +

    Unfortunately, using GDB with dynamically loaded passes is not as easy as it + should be. First of all, you can't set a breakpoint in a shared object that has + not been loaded yet, and second of all there are problems with inlined functions + in shared objects. Here are some suggestions to debugging your pass with + GDB.

    + +

    For sake of discussion, I'm going to assume that you are debugging a + transformation invoked by opt, although nothing described here depends + on that.

    + +
    + + + + +
    + +

    First thing you do is start gdb on the opt process:

    + +
    + $ gdb opt
    + GNU gdb 5.0
    + Copyright 2000 Free Software Foundation, Inc.
    + GDB is free software, covered by the GNU General Public License, and you are
    + welcome to change it and/or distribute copies of it under certain conditions.
    + Type "show copying" to see the conditions.
    + There is absolutely no warranty for GDB.  Type "show warranty" for details.
    + This GDB was configured as "sparc-sun-solaris2.6"...
    + (gdb)
    + 
    + +

    Note that opt has a lot of debugging information in it, so it takes + time to load. Be patient. Since we cannot set a breakpoint in our pass yet + (the shared object isn't loaded until runtime), we must execute the process, and + have it stop before it invokes our pass, but after it has loaded the shared + object. The most foolproof way of doing this is to set a breakpoint in + PassManager::run and then run the process with the arguments you + want:

    + +
    + (gdb) break PassManager::run
    + Breakpoint 1 at 0x2413bc: file Pass.cpp, line 70.
    + (gdb) run test.bc -load $(LLVMTOP)/llvm/Debug/lib/[libname].so -[passoption]
    + Starting program: opt test.bc -load $(LLVMTOP)/llvm/Debug/lib/[libname].so -[passoption]
    + Breakpoint 1, PassManager::run (this=0xffbef174, M=@0x70b298) at Pass.cpp:70
    + 70      bool PassManager::run(Module &M) { return PM->run(M); }
    + (gdb)
    + 
    + +

    Once the opt stops in the PassManager::run method you are + now free to set breakpoints in your pass so that you can trace through execution + or do other standard debugging stuff.

    + +
    + + + + +
    + +

    Once you have the basics down, there are a couple of problems that GDB has, + some with solutions, some without.

    + +
      +
    • Inline functions have bogus stack information. In general, GDB does a + pretty good job getting stack traces and stepping through inline functions. + When a pass is dynamically loaded however, it somehow completely loses this + capability. The only solution I know of is to de-inline a function (move it + from the body of a class to a .cpp file).
    • + +
    • Restarting the program breaks breakpoints. After following the information + above, you have succeeded in getting some breakpoints planted in your pass. Nex + thing you know, you restart the program (i.e., you type 'run' again), + and you start getting errors about breakpoints being unsettable. The only way I + have found to "fix" this problem is to delete the breakpoints that are + already set in your pass, run the program, and re-set the breakpoints once + execution stops in PassManager::run.
    • + +
    + +

    Hopefully these tips will help with common case debugging situations. If + you'd like to contribute some tips of your own, just contact Chris.

    + +
    + + + + + +
    + +

    Although the LLVM Pass Infrastructure is very capable as it stands, and does + some nifty stuff, there are things we'd like to add in the future. Here is + where we are going:

    + +
    + + + + +
    + +

    Multiple CPU machines are becoming more common and compilation can never be + fast enough: obviously we should allow for a multithreaded compiler. Because of + the semantics defined for passes above (specifically they cannot maintain state + across invocations of their run* methods), a nice clean way to + implement a multithreaded compiler would be for the PassManager class + to create multiple instances of each pass object, and allow the separate + instances to be hacking on different parts of the program at the same time.

    + +

    This implementation would prevent each of the passes from having to implement + multithreaded constructs, requiring only the LLVM core to have locking in a few + places (for global resources). Although this is a simple extension, we simply + haven't had time (or multiprocessor machines, thus a reason) to implement this. + Despite that, we have kept the LLVM passes SMP ready, and you should too.

    + +
    + + + + +
    + +

    Currently it is illegal for a ModulePass + to require a FunctionPass. This is because + there is only one instance of the FunctionPass object ever created, thus nowhere + to store information for all of the functions in the program at the same time. + Although this has come up a couple of times before, this has always been worked + around by factoring one big complicated pass into a global and an + interprocedural part, both of which are distinct. In the future, it would be + nice to have this though.

    + +

    Note that it is no problem for a FunctionPass to require the results of a ModulePass, only the other way around.

    + +
    + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + Chris Lattner
    + The LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + + + Index: llvm-www/releases/1.8/docs/doxygen.cfg.in diff -c /dev/null llvm-www/releases/1.8/docs/doxygen.cfg.in:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/doxygen.cfg.in Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,1230 ---- + # Doxyfile 1.4.4 + + # This file describes the settings to be used by the documentation system + # doxygen (www.doxygen.org) for a project + # + # All text after a hash (#) is considered a comment and will be ignored + # The format is: + # TAG = value [value, ...] + # For lists items can also be appended using: + # TAG += value [value, ...] + # Values that contain spaces should be placed between quotes (" ") + + #--------------------------------------------------------------------------- + # Project related configuration options + #--------------------------------------------------------------------------- + + # The PROJECT_NAME tag is a single word (or a sequence of words surrounded + # by quotes) that should identify the project. + + PROJECT_NAME = LLVM + + # The PROJECT_NUMBER tag can be used to enter a project or revision number. + # This could be handy for archiving the generated documentation or + # if some version control system is used. + + PROJECT_NUMBER = @PACKAGE_VERSION@ + + # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) + # base path where the generated documentation will be put. + # If a relative path is entered, it will be relative to the location + # where doxygen was started. If left blank the current directory will be used. + + OUTPUT_DIRECTORY = @abs_top_builddir@/docs/doxygen + + # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create + # 4096 sub-directories (in 2 levels) under the output directory of each output + # format and will distribute the generated files over these directories. + # Enabling this option can be useful when feeding doxygen a huge amount of + # source files, where putting all generated files in the same directory would + # otherwise cause performance problems for the file system. + + CREATE_SUBDIRS = NO + + # The OUTPUT_LANGUAGE tag is used to specify the language in which all + # documentation generated by doxygen is written. Doxygen will use this + # information to generate all constant output in the proper language. + # The default language is English, other supported languages are: + # Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, + # Dutch, Finnish, French, German, Greek, Hungarian, Italian, Japanese, + # Japanese-en (Japanese with English messages), Korean, Korean-en, Norwegian, + # Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, + # Swedish, and Ukrainian. + + OUTPUT_LANGUAGE = English + + # This tag can be used to specify the encoding used in the generated output. + # The encoding is not always determined by the language that is chosen, + # but also whether or not the output is meant for Windows or non-Windows users. + # In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES + # forces the Windows encoding (this is the default for the Windows binary), + # whereas setting the tag to NO uses a Unix-style encoding (the default for + # all platforms other than Windows). + + USE_WINDOWS_ENCODING = NO + + # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will + # include brief member descriptions after the members that are listed in + # the file and class documentation (similar to JavaDoc). + # Set to NO to disable this. + + BRIEF_MEMBER_DESC = YES + + # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend + # the brief description of a member or function before the detailed description. + # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the + # brief descriptions will be completely suppressed. + + REPEAT_BRIEF = YES + + # This tag implements a quasi-intelligent brief description abbreviator + # that is used to form the text in various listings. Each string + # in this list, if found as the leading text of the brief description, will be + # stripped from the text and the result after processing the whole list, is + # used as the annotated text. Otherwise, the brief description is used as-is. + # If left blank, the following values are used ("$name" is automatically + # replaced with the name of the entity): "The $name class" "The $name widget" + # "The $name file" "is" "provides" "specifies" "contains" + # "represents" "a" "an" "the" + + ABBREVIATE_BRIEF = + + # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then + # Doxygen will generate a detailed section even if there is only a brief + # description. + + ALWAYS_DETAILED_SEC = NO + + # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all + # inherited members of a class in the documentation of that class as if those + # members were ordinary class members. Constructors, destructors and assignment + # operators of the base classes will not be shown. + + INLINE_INHERITED_MEMB = NO + + # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full + # path before files name in the file list and in the header files. If set + # to NO the shortest path that makes the file name unique will be used. + + FULL_PATH_NAMES = NO + + # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag + # can be used to strip a user-defined part of the path. Stripping is + # only done if one of the specified strings matches the left-hand part of + # the path. The tag can be used to show relative paths in the file list. + # If left blank the directory from which doxygen is run is used as the + # path to strip. + + STRIP_FROM_PATH = ../.. + + # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of + # the path mentioned in the documentation of a class, which tells + # the reader which header file to include in order to use a class. + # If left blank only the name of the header file containing the class + # definition is used. Otherwise one should specify the include paths that + # are normally passed to the compiler using the -I flag. + + STRIP_FROM_INC_PATH = + + # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter + # (but less readable) file names. This can be useful is your file systems + # doesn't support long names like on DOS, Mac, or CD-ROM. + + SHORT_NAMES = NO + + # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen + # will interpret the first line (until the first dot) of a JavaDoc-style + # comment as the brief description. If set to NO, the JavaDoc + # comments will behave just like the Qt-style comments (thus requiring an + # explicit @brief command for a brief description. + + JAVADOC_AUTOBRIEF = NO + + # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen + # treat a multi-line C++ special comment block (i.e. a block of //! or /// + # comments) as a brief description. This used to be the default behaviour. + # The new default is to treat a multi-line C++ comment block as a detailed + # description. Set this tag to YES if you prefer the old behaviour instead. + + MULTILINE_CPP_IS_BRIEF = NO + + # If the DETAILS_AT_TOP tag is set to YES then Doxygen + # will output the detailed description near the top, like JavaDoc. + # If set to NO, the detailed description appears after the member + # documentation. + + DETAILS_AT_TOP = NO + + # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented + # member inherits the documentation from any documented member that it + # re-implements. + + INHERIT_DOCS = YES + + # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC + # tag is set to YES, then doxygen will reuse the documentation of the first + # member in the group (if any) for the other members of the group. By default + # all members of a group must be documented explicitly. + + DISTRIBUTE_GROUP_DOC = NO + + # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce + # a new page for each member. If set to NO, the documentation of a member will + # be part of the file/class/namespace that contains it. + + SEPARATE_MEMBER_PAGES = NO + + # The TAB_SIZE tag can be used to set the number of spaces in a tab. + # Doxygen uses this value to replace tabs by spaces in code fragments. + + TAB_SIZE = 2 + + # This tag can be used to specify a number of aliases that acts + # as commands in the documentation. An alias has the form "name=value". + # For example adding "sideeffect=\par Side Effects:\n" will allow you to + # put the command \sideeffect (or @sideeffect) in the documentation, which + # will result in a user-defined paragraph with heading "Side Effects:". + # You can put \n's in the value part of an alias to insert newlines. + + ALIASES = + + # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C + # sources only. Doxygen will then generate output that is more tailored for C. + # For instance, some of the names that are used will be different. The list + # of all members will be omitted, etc. + + OPTIMIZE_OUTPUT_FOR_C = NO + + # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources + # only. Doxygen will then generate output that is more tailored for Java. + # For instance, namespaces will be presented as packages, qualified scopes + # will look different, etc. + + OPTIMIZE_OUTPUT_JAVA = NO + + # Set the SUBGROUPING tag to YES (the default) to allow class member groups of + # the same type (for instance a group of public functions) to be put as a + # subgroup of that type (e.g. under the Public Functions section). Set it to + # NO to prevent subgrouping. Alternatively, this can be done per class using + # the \nosubgrouping command. + + SUBGROUPING = YES + + #--------------------------------------------------------------------------- + # Build related configuration options + #--------------------------------------------------------------------------- + + # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in + # documentation are documented, even if no documentation was available. + # Private class members and static file members will be hidden unless + # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + + EXTRACT_ALL = YES + + # If the EXTRACT_PRIVATE tag is set to YES all private members of a class + # will be included in the documentation. + + EXTRACT_PRIVATE = NO + + # If the EXTRACT_STATIC tag is set to YES all static members of a file + # will be included in the documentation. + + EXTRACT_STATIC = YES + + # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) + # defined locally in source files will be included in the documentation. + # If set to NO only classes defined in header files are included. + + EXTRACT_LOCAL_CLASSES = YES + + # This flag is only useful for Objective-C code. When set to YES local + # methods, which are defined in the implementation section but not in + # the interface are included in the documentation. + # If set to NO (the default) only methods in the interface are included. + + EXTRACT_LOCAL_METHODS = NO + + # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all + # undocumented members of documented classes, files or namespaces. + # If set to NO (the default) these members will be included in the + # various overviews, but no documentation section is generated. + # This option has no effect if EXTRACT_ALL is enabled. + + HIDE_UNDOC_MEMBERS = NO + + # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all + # undocumented classes that are normally visible in the class hierarchy. + # If set to NO (the default) these classes will be included in the various + # overviews. This option has no effect if EXTRACT_ALL is enabled. + + HIDE_UNDOC_CLASSES = NO + + # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all + # friend (class|struct|union) declarations. + # If set to NO (the default) these declarations will be included in the + # documentation. + + HIDE_FRIEND_COMPOUNDS = NO + + # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any + # documentation blocks found inside the body of a function. + # If set to NO (the default) these blocks will be appended to the + # function's detailed documentation block. + + HIDE_IN_BODY_DOCS = NO + + # The INTERNAL_DOCS tag determines if documentation + # that is typed after a \internal command is included. If the tag is set + # to NO (the default) then the documentation will be excluded. + # Set it to YES to include the internal documentation. + + INTERNAL_DOCS = NO + + # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate + # file names in lower-case letters. If set to YES upper-case letters are also + # allowed. This is useful if you have classes or files whose names only differ + # in case and if your file system supports case sensitive file names. Windows + # and Mac users are advised to set this option to NO. + + CASE_SENSE_NAMES = YES + + # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen + # will show members with their full class and namespace scopes in the + # documentation. If set to YES the scope will be hidden. + + HIDE_SCOPE_NAMES = NO + + # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen + # will put a list of the files that are included by a file in the documentation + # of that file. + + SHOW_INCLUDE_FILES = YES + + # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] + # is inserted in the documentation for inline members. + + INLINE_INFO = YES + + # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen + # will sort the (detailed) documentation of file and class members + # alphabetically by member name. If set to NO the members will appear in + # declaration order. + + SORT_MEMBER_DOCS = YES + + # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the + # brief documentation of file, namespace and class members alphabetically + # by member name. If set to NO (the default) the members will appear in + # declaration order. + + SORT_BRIEF_DOCS = NO + + # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be + # sorted by fully-qualified names, including namespaces. If set to + # NO (the default), the class list will be sorted only by class name, + # not including the namespace part. + # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. + # Note: This option applies only to the class list, not to the + # alphabetical list. + + SORT_BY_SCOPE_NAME = NO + + # The GENERATE_TODOLIST tag can be used to enable (YES) or + # disable (NO) the todo list. This list is created by putting \todo + # commands in the documentation. + + GENERATE_TODOLIST = YES + + # The GENERATE_TESTLIST tag can be used to enable (YES) or + # disable (NO) the test list. This list is created by putting \test + # commands in the documentation. + + GENERATE_TESTLIST = YES + + # The GENERATE_BUGLIST tag can be used to enable (YES) or + # disable (NO) the bug list. This list is created by putting \bug + # commands in the documentation. + + GENERATE_BUGLIST = YES + + # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or + # disable (NO) the deprecated list. This list is created by putting + # \deprecated commands in the documentation. + + GENERATE_DEPRECATEDLIST= YES + + # The ENABLED_SECTIONS tag can be used to enable conditional + # documentation sections, marked by \if sectionname ... \endif. + + ENABLED_SECTIONS = + + # The MAX_INITIALIZER_LINES tag determines the maximum number of lines + # the initial value of a variable or define consists of for it to appear in + # the documentation. If the initializer consists of more lines than specified + # here it will be hidden. Use a value of 0 to hide initializers completely. + # The appearance of the initializer of individual variables and defines in the + # documentation can be controlled using \showinitializer or \hideinitializer + # command in the documentation regardless of this setting. + + MAX_INITIALIZER_LINES = 30 + + # Set the SHOW_USED_FILES tag to NO to disable the list of files generated + # at the bottom of the documentation of classes and structs. If set to YES the + # list will mention the files that were used to generate the documentation. + + SHOW_USED_FILES = YES + + # If the sources in your project are distributed over multiple directories + # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy + # in the documentation. The default is YES. + + SHOW_DIRECTORIES = YES + + # The FILE_VERSION_FILTER tag can be used to specify a program or script that + # doxygen should invoke to get the current version for each file (typically from the + # version control system). Doxygen will invoke the program by executing (via + # popen()) the command , where is the value of + # the FILE_VERSION_FILTER tag, and is the name of an input file + # provided by doxygen. Whatever the progam writes to standard output + # is used as the file version. See the manual for examples. + + FILE_VERSION_FILTER = + + #--------------------------------------------------------------------------- + # configuration options related to warning and progress messages + #--------------------------------------------------------------------------- + + # The QUIET tag can be used to turn on/off the messages that are generated + # by doxygen. Possible values are YES and NO. If left blank NO is used. + + QUIET = NO + + # The WARNINGS tag can be used to turn on/off the warning messages that are + # generated by doxygen. Possible values are YES and NO. If left blank + # NO is used. + + WARNINGS = NO + + # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings + # for undocumented members. If EXTRACT_ALL is set to YES then this flag will + # automatically be disabled. + + WARN_IF_UNDOCUMENTED = NO + + # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for + # potential errors in the documentation, such as not documenting some + # parameters in a documented function, or documenting parameters that + # don't exist or using markup commands wrongly. + + WARN_IF_DOC_ERROR = YES + + # This WARN_NO_PARAMDOC option can be abled to get warnings for + # functions that are documented, but have no documentation for their parameters + # or return value. If set to NO (the default) doxygen will only warn about + # wrong or incomplete parameter documentation, but not about the absence of + # documentation. + + WARN_NO_PARAMDOC = NO + + # The WARN_FORMAT tag determines the format of the warning messages that + # doxygen can produce. The string should contain the $file, $line, and $text + # tags, which will be replaced by the file and line number from which the + # warning originated and the warning text. Optionally the format may contain + # $version, which will be replaced by the version of the file (if it could + # be obtained via FILE_VERSION_FILTER) + + WARN_FORMAT = + + # The WARN_LOGFILE tag can be used to specify a file to which warning + # and error messages should be written. If left blank the output is written + # to stderr. + + WARN_LOGFILE = + + #--------------------------------------------------------------------------- + # configuration options related to the input files + #--------------------------------------------------------------------------- + + # The INPUT tag can be used to specify the files and/or directories that contain + # documented source files. You may enter file names like "myfile.cpp" or + # directories like "/usr/src/myproject". Separate the files or directories + # with spaces. + + INPUT = @abs_top_srcdir@/include \ + @abs_top_srcdir@/lib \ + @abs_top_srcdir@/docs/doxygen.intro + + # If the value of the INPUT tag contains directories, you can use the + # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp + # and *.h) to filter out the source-files in the directories. If left + # blank the following patterns are tested: + # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx + # *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm + + FILE_PATTERNS = + + # The RECURSIVE tag can be used to turn specify whether or not subdirectories + # should be searched for input files as well. Possible values are YES and NO. + # If left blank NO is used. + + RECURSIVE = YES + + # The EXCLUDE tag can be used to specify files and/or directories that should + # excluded from the INPUT source files. This way you can easily exclude a + # subdirectory from a directory tree whose root is specified with the INPUT tag. + + EXCLUDE = + + # The EXCLUDE_SYMLINKS tag can be used select whether or not files or + # directories that are symbolic links (a Unix filesystem feature) are excluded + # from the input. + + EXCLUDE_SYMLINKS = NO + + # If the value of the INPUT tag contains directories, you can use the + # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude + # certain files from those directories. Note that the wildcards are matched + # against the file with absolute path, so to exclude all test directories + # for example use the pattern */test/* + + EXCLUDE_PATTERNS = + + # The EXAMPLE_PATH tag can be used to specify one or more files or + # directories that contain example code fragments that are included (see + # the \include command). + + EXAMPLE_PATH = @abs_top_srcdir@/examples + + # If the value of the EXAMPLE_PATH tag contains directories, you can use the + # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp + # and *.h) to filter out the source-files in the directories. If left + # blank all files are included. + + EXAMPLE_PATTERNS = + + # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be + # searched for input files to be used with the \include or \dontinclude + # commands irrespective of the value of the RECURSIVE tag. + # Possible values are YES and NO. If left blank NO is used. + + EXAMPLE_RECURSIVE = YES + + # The IMAGE_PATH tag can be used to specify one or more files or + # directories that contain image that are included in the documentation (see + # the \image command). + + IMAGE_PATH = @abs_top_srcdir@/docs/img + + # The INPUT_FILTER tag can be used to specify a program that doxygen should + # invoke to filter for each input file. Doxygen will invoke the filter program + # by executing (via popen()) the command , where + # is the value of the INPUT_FILTER tag, and is the name of an + # input file. Doxygen will then use the output that the filter program writes + # to standard output. If FILTER_PATTERNS is specified, this tag will be + # ignored. + + INPUT_FILTER = + + # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern + # basis. Doxygen will compare the file name with each pattern and apply the + # filter if there is a match. The filters are a list of the form: + # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further + # info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER + # is applied to all files. + + FILTER_PATTERNS = + + # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using + # INPUT_FILTER) will be used to filter the input files when producing source + # files to browse (i.e. when SOURCE_BROWSER is set to YES). + + FILTER_SOURCE_FILES = NO + + #--------------------------------------------------------------------------- + # configuration options related to source browsing + #--------------------------------------------------------------------------- + + # If the SOURCE_BROWSER tag is set to YES then a list of source files will + # be generated. Documented entities will be cross-referenced with these sources. + # Note: To get rid of all source code in the generated output, make sure also + # VERBATIM_HEADERS is set to NO. + + SOURCE_BROWSER = YES + + # Setting the INLINE_SOURCES tag to YES will include the body + # of functions and classes directly in the documentation. + + INLINE_SOURCES = NO + + # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct + # doxygen to hide any special comment blocks from generated source code + # fragments. Normal C and C++ comments will always remain visible. + + STRIP_CODE_COMMENTS = NO + + # If the REFERENCED_BY_RELATION tag is set to YES (the default) + # then for each documented function all documented + # functions referencing it will be listed. + + REFERENCED_BY_RELATION = YES + + # If the REFERENCES_RELATION tag is set to YES (the default) + # then for each documented function all documented entities + # called/used by that function will be listed. + + REFERENCES_RELATION = YES + + # If the USE_HTAGS tag is set to YES then the references to source code + # will point to the HTML generated by the htags(1) tool instead of doxygen + # built-in source browser. The htags tool is part of GNU's global source + # tagging system (see http://www.gnu.org/software/global/global.html). You + # will need version 4.8.6 or higher. + + USE_HTAGS = NO + + # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen + # will generate a verbatim copy of the header file for each class for + # which an include is specified. Set to NO to disable this. + + VERBATIM_HEADERS = YES + + #--------------------------------------------------------------------------- + # configuration options related to the alphabetical class index + #--------------------------------------------------------------------------- + + # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index + # of all compounds will be generated. Enable this if the project + # contains a lot of classes, structs, unions or interfaces. + + ALPHABETICAL_INDEX = YES + + # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then + # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns + # in which this list will be split (can be a number in the range [1..20]) + + COLS_IN_ALPHA_INDEX = 4 + + # In case all classes in a project start with a common prefix, all + # classes will be put under the same header in the alphabetical index. + # The IGNORE_PREFIX tag can be used to specify one or more prefixes that + # should be ignored while generating the index headers. + + IGNORE_PREFIX = llvm:: + + #--------------------------------------------------------------------------- + # configuration options related to the HTML output + #--------------------------------------------------------------------------- + + # If the GENERATE_HTML tag is set to YES (the default) Doxygen will + # generate HTML output. + + GENERATE_HTML = YES + + # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. + # If a relative path is entered the value of OUTPUT_DIRECTORY will be + # put in front of it. If left blank `html' will be used as the default path. + + HTML_OUTPUT = html + + # The HTML_FILE_EXTENSION tag can be used to specify the file extension for + # each generated HTML page (for example: .htm,.php,.asp). If it is left blank + # doxygen will generate files with .html extension. + + HTML_FILE_EXTENSION = .html + + # The HTML_HEADER tag can be used to specify a personal HTML header for + # each generated HTML page. If it is left blank doxygen will generate a + # standard header. + + HTML_HEADER = @abs_top_srcdir@/docs/doxygen.header + + # The HTML_FOOTER tag can be used to specify a personal HTML footer for + # each generated HTML page. If it is left blank doxygen will generate a + # standard footer. + + HTML_FOOTER = @abs_top_srcdir@/docs/doxygen.footer + + # The HTML_STYLESHEET tag can be used to specify a user-defined cascading + # style sheet that is used by each HTML page. It can be used to + # fine-tune the look of the HTML output. If the tag is left blank doxygen + # will generate a default style sheet. Note that doxygen will try to copy + # the style sheet file to the HTML output directory, so don't put your own + # stylesheet in the HTML output directory as well, or it will be erased! + + HTML_STYLESHEET = @abs_top_srcdir@/docs/doxygen.css + + # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, + # files or namespaces will be aligned in HTML using tables. If set to + # NO a bullet list will be used. + + HTML_ALIGN_MEMBERS = YES + + # If the GENERATE_HTMLHELP tag is set to YES, additional index files + # will be generated that can be used as input for tools like the + # Microsoft HTML help workshop to generate a compressed HTML help file (.chm) + # of the generated HTML documentation. + + GENERATE_HTMLHELP = NO + + # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can + # be used to specify the file name of the resulting .chm file. You + # can add a path in front of the file if the result should not be + # written to the html output directory. + + CHM_FILE = + + # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can + # be used to specify the location (absolute path including file name) of + # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run + # the HTML help compiler on the generated index.hhp. + + HHC_LOCATION = + + # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag + # controls if a separate .chi index file is generated (YES) or that + # it should be included in the master .chm file (NO). + + GENERATE_CHI = NO + + # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag + # controls whether a binary table of contents is generated (YES) or a + # normal table of contents (NO) in the .chm file. + + BINARY_TOC = NO + + # The TOC_EXPAND flag can be set to YES to add extra items for group members + # to the contents of the HTML help documentation and to the tree view. + + TOC_EXPAND = NO + + # The DISABLE_INDEX tag can be used to turn on/off the condensed index at + # top of each HTML page. The value NO (the default) enables the index and + # the value YES disables it. + + DISABLE_INDEX = NO + + # This tag can be used to set the number of enum values (range [1..20]) + # that doxygen will group on one line in the generated HTML documentation. + + ENUM_VALUES_PER_LINE = 4 + + # If the GENERATE_TREEVIEW tag is set to YES, a side panel will be + # generated containing a tree-like index structure (just like the one that + # is generated for HTML Help). For this to work a browser that supports + # JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, + # Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are + # probably better off using the HTML help feature. + + GENERATE_TREEVIEW = NO + + # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be + # used to set the initial width (in pixels) of the frame in which the tree + # is shown. + + TREEVIEW_WIDTH = 250 + + #--------------------------------------------------------------------------- + # configuration options related to the LaTeX output + #--------------------------------------------------------------------------- + + # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will + # generate Latex output. + + GENERATE_LATEX = NO + + # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. + # If a relative path is entered the value of OUTPUT_DIRECTORY will be + # put in front of it. If left blank `latex' will be used as the default path. + + LATEX_OUTPUT = + + # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be + # invoked. If left blank `latex' will be used as the default command name. + + LATEX_CMD_NAME = latex + + # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to + # generate index for LaTeX. If left blank `makeindex' will be used as the + # default command name. + + MAKEINDEX_CMD_NAME = makeindex + + # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact + # LaTeX documents. This may be useful for small projects and may help to + # save some trees in general. + + COMPACT_LATEX = NO + + # The PAPER_TYPE tag can be used to set the paper type that is used + # by the printer. Possible values are: a4, a4wide, letter, legal and + # executive. If left blank a4wide will be used. + + PAPER_TYPE = letter + + # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX + # packages that should be included in the LaTeX output. + + EXTRA_PACKAGES = + + # The LATEX_HEADER tag can be used to specify a personal LaTeX header for + # the generated latex document. The header should contain everything until + # the first chapter. If it is left blank doxygen will generate a + # standard header. Notice: only use this tag if you know what you are doing! + + LATEX_HEADER = + + # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated + # is prepared for conversion to pdf (using ps2pdf). The pdf file will + # contain links (just like the HTML output) instead of page references + # This makes the output suitable for online browsing using a pdf viewer. + + PDF_HYPERLINKS = NO + + # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of + # plain latex in the generated Makefile. Set this option to YES to get a + # higher quality PDF documentation. + + USE_PDFLATEX = NO + + # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. + # command to the generated LaTeX files. This will instruct LaTeX to keep + # running if errors occur, instead of asking the user for help. + # This option is also used when generating formulas in HTML. + + LATEX_BATCHMODE = NO + + # If LATEX_HIDE_INDICES is set to YES then doxygen will not + # include the index chapters (such as File Index, Compound Index, etc.) + # in the output. + + LATEX_HIDE_INDICES = NO + + #--------------------------------------------------------------------------- + # configuration options related to the RTF output + #--------------------------------------------------------------------------- + + # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output + # The RTF output is optimized for Word 97 and may not look very pretty with + # other RTF readers or editors. + + GENERATE_RTF = NO + + # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. + # If a relative path is entered the value of OUTPUT_DIRECTORY will be + # put in front of it. If left blank `rtf' will be used as the default path. + + RTF_OUTPUT = + + # If the COMPACT_RTF tag is set to YES Doxygen generates more compact + # RTF documents. This may be useful for small projects and may help to + # save some trees in general. + + COMPACT_RTF = NO + + # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated + # will contain hyperlink fields. The RTF file will + # contain links (just like the HTML output) instead of page references. + # This makes the output suitable for online browsing using WORD or other + # programs which support those fields. + # Note: wordpad (write) and others do not support links. + + RTF_HYPERLINKS = NO + + # Load stylesheet definitions from file. Syntax is similar to doxygen's + # config file, i.e. a series of assignments. You only have to provide + # replacements, missing definitions are set to their default value. + + RTF_STYLESHEET_FILE = + + # Set optional variables used in the generation of an rtf document. + # Syntax is similar to doxygen's config file. + + RTF_EXTENSIONS_FILE = + + #--------------------------------------------------------------------------- + # configuration options related to the man page output + #--------------------------------------------------------------------------- + + # If the GENERATE_MAN tag is set to YES (the default) Doxygen will + # generate man pages + + GENERATE_MAN = NO + + # The MAN_OUTPUT tag is used to specify where the man pages will be put. + # If a relative path is entered the value of OUTPUT_DIRECTORY will be + # put in front of it. If left blank `man' will be used as the default path. + + MAN_OUTPUT = + + # The MAN_EXTENSION tag determines the extension that is added to + # the generated man pages (default is the subroutine's section .3) + + MAN_EXTENSION = + + # If the MAN_LINKS tag is set to YES and Doxygen generates man output, + # then it will generate one additional man file for each entity + # documented in the real man page(s). These additional files + # only source the real man page, but without them the man command + # would be unable to find the correct page. The default is NO. + + MAN_LINKS = NO + + #--------------------------------------------------------------------------- + # configuration options related to the XML output + #--------------------------------------------------------------------------- + + # If the GENERATE_XML tag is set to YES Doxygen will + # generate an XML file that captures the structure of + # the code including all documentation. + + GENERATE_XML = NO + + # The XML_OUTPUT tag is used to specify where the XML pages will be put. + # If a relative path is entered the value of OUTPUT_DIRECTORY will be + # put in front of it. If left blank `xml' will be used as the default path. + + XML_OUTPUT = xml + + # The XML_SCHEMA tag can be used to specify an XML schema, + # which can be used by a validating XML parser to check the + # syntax of the XML files. + + XML_SCHEMA = + + # The XML_DTD tag can be used to specify an XML DTD, + # which can be used by a validating XML parser to check the + # syntax of the XML files. + + XML_DTD = + + # If the XML_PROGRAMLISTING tag is set to YES Doxygen will + # dump the program listings (including syntax highlighting + # and cross-referencing information) to the XML output. Note that + # enabling this will significantly increase the size of the XML output. + + XML_PROGRAMLISTING = YES + + #--------------------------------------------------------------------------- + # configuration options for the AutoGen Definitions output + #--------------------------------------------------------------------------- + + # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will + # generate an AutoGen Definitions (see autogen.sf.net) file + # that captures the structure of the code including all + # documentation. Note that this feature is still experimental + # and incomplete at the moment. + + GENERATE_AUTOGEN_DEF = NO + + #--------------------------------------------------------------------------- + # configuration options related to the Perl module output + #--------------------------------------------------------------------------- + + # If the GENERATE_PERLMOD tag is set to YES Doxygen will + # generate a Perl module file that captures the structure of + # the code including all documentation. Note that this + # feature is still experimental and incomplete at the + # moment. + + GENERATE_PERLMOD = NO + + # If the PERLMOD_LATEX tag is set to YES Doxygen will generate + # the necessary Makefile rules, Perl scripts and LaTeX code to be able + # to generate PDF and DVI output from the Perl module output. + + PERLMOD_LATEX = NO + + # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be + # nicely formatted so it can be parsed by a human reader. This is useful + # if you want to understand what is going on. On the other hand, if this + # tag is set to NO the size of the Perl module output will be much smaller + # and Perl will parse it just the same. + + PERLMOD_PRETTY = YES + + # The names of the make variables in the generated doxyrules.make file + # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. + # This is useful so different doxyrules.make files included by the same + # Makefile don't overwrite each other's variables. + + PERLMOD_MAKEVAR_PREFIX = + + #--------------------------------------------------------------------------- + # Configuration options related to the preprocessor + #--------------------------------------------------------------------------- + + # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will + # evaluate all C-preprocessor directives found in the sources and include + # files. + + ENABLE_PREPROCESSING = YES + + # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro + # names in the source code. If set to NO (the default) only conditional + # compilation will be performed. Macro expansion can be done in a controlled + # way by setting EXPAND_ONLY_PREDEF to YES. + + MACRO_EXPANSION = NO + + # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES + # then the macro expansion is limited to the macros specified with the + # PREDEFINED and EXPAND_AS_PREDEFINED tags. + + EXPAND_ONLY_PREDEF = NO + + # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files + # in the INCLUDE_PATH (see below) will be search if a #include is found. + + SEARCH_INCLUDES = YES + + # The INCLUDE_PATH tag can be used to specify one or more directories that + # contain include files that are not input files but should be processed by + # the preprocessor. + + INCLUDE_PATH = ../include + + # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard + # patterns (like *.h and *.hpp) to filter out the header-files in the + # directories. If left blank, the patterns specified with FILE_PATTERNS will + # be used. + + INCLUDE_FILE_PATTERNS = + + # The PREDEFINED tag can be used to specify one or more macro names that + # are defined before the preprocessor is started (similar to the -D option of + # gcc). The argument of the tag is a list of macros of the form: name + # or name=definition (no spaces). If the definition and the = are + # omitted =1 is assumed. To prevent a macro definition from being + # undefined via #undef or recursively expanded use the := operator + # instead of the = operator. + + PREDEFINED = + + # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then + # this tag can be used to specify a list of macro names that should be expanded. + # The macro definition that is found in the sources will be used. + # Use the PREDEFINED tag if you want to use a different macro definition. + + EXPAND_AS_DEFINED = + + # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then + # doxygen's preprocessor will remove all function-like macros that are alone + # on a line, have an all uppercase name, and do not end with a semicolon. Such + # function macros are typically used for boiler-plate code, and will confuse + # the parser if not removed. + + SKIP_FUNCTION_MACROS = YES + + #--------------------------------------------------------------------------- + # Configuration::additions related to external references + #--------------------------------------------------------------------------- + + # The TAGFILES option can be used to specify one or more tagfiles. + # Optionally an initial location of the external documentation + # can be added for each tagfile. The format of a tag file without + # this location is as follows: + # TAGFILES = file1 file2 ... + # Adding location for the tag files is done as follows: + # TAGFILES = file1=loc1 "file2 = loc2" ... + # where "loc1" and "loc2" can be relative or absolute paths or + # URLs. If a location is present for each tag, the installdox tool + # does not have to be run to correct the links. + # Note that each tag file must have a unique name + # (where the name does NOT include the path) + # If a tag file is not located in the directory in which doxygen + # is run, you must also specify the path to the tagfile here. + + TAGFILES = + + # When a file name is specified after GENERATE_TAGFILE, doxygen will create + # a tag file that is based on the input files it reads. + + GENERATE_TAGFILE = + + # If the ALLEXTERNALS tag is set to YES all external classes will be listed + # in the class index. If set to NO only the inherited external classes + # will be listed. + + ALLEXTERNALS = YES + + # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed + # in the modules index. If set to NO, only the current project's groups will + # be listed. + + EXTERNAL_GROUPS = YES + + # The PERL_PATH should be the absolute path and name of the perl script + # interpreter (i.e. the result of `which perl'). + + PERL_PATH = + + #--------------------------------------------------------------------------- + # Configuration options related to the dot tool + #--------------------------------------------------------------------------- + + # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will + # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base + # or super classes. Setting the tag to NO turns the diagrams off. Note that + # this option is superseded by the HAVE_DOT option below. This is only a + # fallback. It is recommended to install and use dot, since it yields more + # powerful graphs. + + CLASS_DIAGRAMS = YES + + # If set to YES, the inheritance and collaboration graphs will hide + # inheritance and usage relations if the target is undocumented + # or is not a class. + + HIDE_UNDOC_RELATIONS = NO + + # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is + # available from the path. This tool is part of Graphviz, a graph visualization + # toolkit from AT&T and Lucent Bell Labs. The other options in this section + # have no effect if this option is set to NO (the default) + + HAVE_DOT = YES + + # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen + # will generate a graph for each documented class showing the direct and + # indirect inheritance relations. Setting this tag to YES will force the + # the CLASS_DIAGRAMS tag to NO. + + CLASS_GRAPH = YES + + # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen + # will generate a graph for each documented class showing the direct and + # indirect implementation dependencies (inheritance, containment, and + # class references variables) of the class with other documented classes. + + COLLABORATION_GRAPH = YES + + # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen + # will generate a graph for groups, showing the direct groups dependencies + + GROUP_GRAPHS = YES + + # If the UML_LOOK tag is set to YES doxygen will generate inheritance and + # collaboration diagrams in a style similar to the OMG's Unified Modeling + # Language. + + UML_LOOK = NO + + # If set to YES, the inheritance and collaboration graphs will show the + # relations between templates and their instances. + + TEMPLATE_RELATIONS = YES + + # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT + # tags are set to YES then doxygen will generate a graph for each documented + # file showing the direct and indirect include dependencies of the file with + # other documented files. + + INCLUDE_GRAPH = YES + + # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and + # HAVE_DOT tags are set to YES then doxygen will generate a graph for each + # documented header file showing the documented files that directly or + # indirectly include this file. + + INCLUDED_BY_GRAPH = YES + + # If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will + # generate a call dependency graph for every global function or class method. + # Note that enabling this option will significantly increase the time of a run. + # So in most cases it will be better to enable call graphs for selected + # functions only using the \callgraph command. + + CALL_GRAPH = NO + + # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen + # will graphical hierarchy of all classes instead of a textual one. + + GRAPHICAL_HIERARCHY = YES + + # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES + # then doxygen will show the dependencies a directory has on other directories + # in a graphical way. The dependency relations are determined by the #include + # relations between the files in the directories. + + DIRECTORY_GRAPH = YES + + # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images + # generated by dot. Possible values are png, jpg, or gif + # If left blank png will be used. + + DOT_IMAGE_FORMAT = png + + # The tag DOT_PATH can be used to specify the path where the dot tool can be + # found. If left blank, it is assumed the dot tool can be found in the path. + + DOT_PATH = @DOT@ + + # The DOTFILE_DIRS tag can be used to specify one or more directories that + # contain dot files that are included in the documentation (see the + # \dotfile command). + + DOTFILE_DIRS = + + # The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width + # (in pixels) of the graphs generated by dot. If a graph becomes larger than + # this value, doxygen will try to truncate the graph, so that it fits within + # the specified constraint. Beware that most browsers cannot cope with very + # large images. + + MAX_DOT_GRAPH_WIDTH = 1024 + + # The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height + # (in pixels) of the graphs generated by dot. If a graph becomes larger than + # this value, doxygen will try to truncate the graph, so that it fits within + # the specified constraint. Beware that most browsers cannot cope with very + # large images. + + MAX_DOT_GRAPH_HEIGHT = 1024 + + # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the + # graphs generated by dot. A depth value of 3 means that only nodes reachable + # from the root by following a path via at most 3 edges will be shown. Nodes + # that lay further from the root node will be omitted. Note that setting this + # option to 1 or 2 may greatly reduce the computation time needed for large + # code bases. Also note that a graph may be further truncated if the graph's + # image dimensions are not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH + # and MAX_DOT_GRAPH_HEIGHT). If 0 is used for the depth value (the default), + # the graph is not depth-constrained. + + MAX_DOT_GRAPH_DEPTH = 0 + + # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent + # background. This is disabled by default, which results in a white background. + # Warning: Depending on the platform used, enabling this option may lead to + # badly anti-aliased labels on the edges of a graph (i.e. they become hard to + # read). + + DOT_TRANSPARENT = NO + + # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output + # files in one run (i.e. multiple -o and -T options on the command line). This + # makes dot run faster, but since only newer versions of dot (>1.8.10) + # support this, this feature is disabled by default. + + DOT_MULTI_TARGETS = NO + + # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will + # generate a legend page explaining the meaning of the various boxes and + # arrows in the dot generated graphs. + + GENERATE_LEGEND = YES + + # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will + # remove the intermediate dot files that are used to generate + # the various graphs. + + DOT_CLEANUP = YES + + #--------------------------------------------------------------------------- + # Configuration::additions related to the search engine + #--------------------------------------------------------------------------- + + # The SEARCHENGINE tag specifies whether or not a search engine should be + # used. If set to NO the values of all tags below this one will be ignored. + + SEARCHENGINE = NO Index: llvm-www/releases/1.8/docs/doxygen.css diff -c /dev/null llvm-www/releases/1.8/docs/doxygen.css:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/doxygen.css Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,378 ---- + BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { + font-family: Verdana,Geneva,Arial,Helvetica,sans-serif; + } + BODY,TD { + font-size: 90%; + } + H1 { + text-align: center; + font-size: 140%; + font-weight: bold; + } + H2 { + font-size: 120%; + font-style: italic; + } + H3 { + font-size: 100%; + } + CAPTION { font-weight: bold } + DIV.qindex { + width: 100%; + background-color: #eeeeff; + border: 1px solid #b0b0b0; + text-align: center; + margin: 2px; + padding: 2px; + line-height: 140%; + } + DIV.nav { + width: 100%; + background-color: #eeeeff; + border: 1px solid #b0b0b0; + text-align: center; + margin: 2px; + padding: 2px; + line-height: 140%; + } + DIV.navtab { + background-color: #eeeeff; + border: 1px solid #b0b0b0; + text-align: center; + margin: 2px; + margin-right: 15px; + padding: 2px; + } + TD.navtab { + font-size: 70%; + } + A.qindex { + text-decoration: none; + font-weight: bold; + color: #1A419D; + } + A.qindex:visited { + text-decoration: none; + font-weight: bold; + color: #1A419D + } + A.qindex:hover { + text-decoration: none; + background-color: #ddddff; + } + A.qindexHL { + text-decoration: none; + font-weight: bold; + background-color: #6666cc; + color: #ffffff; + border: 1px double #9295C2; + } + A.qindexHL:hover { + text-decoration: none; + background-color: #6666cc; + color: #ffffff; + } + A.qindexHL:visited { + text-decoration: none; background-color: #6666cc; color: #ffffff } + A.el { text-decoration: none; font-weight: bold } + A.elRef { font-weight: bold } + A.code:link { text-decoration: none; font-weight: normal; color: #0000FF} + A.code:visited { text-decoration: none; font-weight: normal; color: #0000FF} + A.codeRef:link { font-weight: normal; color: #0000FF} + A.codeRef:visited { font-weight: normal; color: #0000FF} + A:hover { text-decoration: none; background-color: #f2f2ff } + DL.el { margin-left: -1cm } + .fragment { + font-family: Fixed, monospace; + font-size: 95%; + } + PRE.fragment { + border: 1px solid #CCCCCC; + background-color: #f5f5f5; + margin-top: 4px; + margin-bottom: 4px; + margin-left: 2px; + margin-right: 8px; + padding-left: 6px; + padding-right: 6px; + padding-top: 4px; + padding-bottom: 4px; + } + DIV.ah { background-color: black; font-weight: bold; color: #ffffff; margin-bottom: 3px; margin-top: 3px } + TD.md { background-color: #F4F4FB; font-weight: bold; } + TD.mdPrefix { + background-color: #F4F4FB; + color: #606060; + font-size: 80%; + } + TD.mdname1 { background-color: #F4F4FB; font-weight: bold; color: #602020; } + TD.mdname { background-color: #F4F4FB; font-weight: bold; color: #602020; width: 600px; } + DIV.groupHeader { + margin-left: 16px; + margin-top: 12px; + margin-bottom: 6px; + font-weight: bold; + } + DIV.groupText { margin-left: 16px; font-style: italic; font-size: 90% } + BODY { + background: white; + color: black; + margin-right: 20px; + margin-left: 20px; + } + TD.indexkey { + background-color: #eeeeff; + font-weight: bold; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; + } + TD.indexvalue { + background-color: #eeeeff; + font-style: italic; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; + } + TR.memlist { + background-color: #f0f0f0; + } + P.formulaDsp { text-align: center; } + IMG.formulaDsp { } + IMG.formulaInl { vertical-align: middle; } + SPAN.keyword { color: #008000 } + SPAN.keywordtype { color: #604020 } + SPAN.keywordflow { color: #e08000 } + SPAN.comment { color: #800000 } + SPAN.preprocessor { color: #806020 } + SPAN.stringliteral { color: #002080 } + SPAN.charliteral { color: #008080 } + .mdTable { + border: 1px solid #868686; + background-color: #F4F4FB; + } + .mdRow { + padding: 8px 10px; + } + .mdescLeft { + padding: 0px 8px 4px 8px; + font-size: 80%; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; + } + .mdescRight { + padding: 0px 8px 4px 8px; + font-size: 80%; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; + } + .memItemLeft { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; + } + .memItemRight { + padding: 1px 8px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; + } + .memTemplItemLeft { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: none; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; + } + .memTemplItemRight { + padding: 1px 8px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: none; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; + } + .memTemplParams { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + color: #606060; + background-color: #FAFAFA; + font-size: 80%; + } + .search { color: #003399; + font-weight: bold; + } + FORM.search { + margin-bottom: 0px; + margin-top: 0px; + } + INPUT.search { font-size: 75%; + color: #000080; + font-weight: normal; + background-color: #eeeeff; + } + TD.tiny { font-size: 75%; + } + a { + color: #252E78; + } + a:visited { + color: #3D2185; + } + .dirtab { padding: 4px; + border-collapse: collapse; + border: 1px solid #b0b0b0; + } + TH.dirtab { background: #eeeeff; + font-weight: bold; + } + HR { height: 1px; + border: none; + border-top: 1px solid black; + } + + /* + * LLVM Modifications. + * Note: Everything above here is generated with "doxygen -w htlm" command. See + * "doxygen --help" for details. What follows are CSS overrides for LLVM + * specific formatting. We want to keep the above so it can be replaced with + * subsequent doxygen upgrades. + */ + + .footer { + font-size: 80%; + font-weight: bold; + text-align: center; + vertical-align: middle; + } + .title { + font-size: 25pt; + color: black; background: url("../img/lines.gif"); + font-weight: bold; + border-width: 1px; + border-style: solid none solid none; + text-align: center; + vertical-align: middle; + padding-left: 8pt; + padding-top: 1px; + padding-bottom: 2px + } + A:link { + cursor: pointer; + text-decoration: none; + font-weight: bolder; + } + A:visited { + cursor: pointer; + text-decoration: underline; + font-weight: bolder; + } + A:hover { + cursor: pointer; + text-decoration: underline; + font-weight: bolder; + } + A:active { + cursor: pointer; + text-decoration: underline; + font-weight: bolder; + font-style: italic; + } + H1 { + text-align: center; + font-size: 140%; + font-weight: bold; + } + H2 { + font-size: 120%; + font-style: italic; + } + H3 { + font-size: 100%; + } + A.qindex {} + A.qindexRef {} + A.el { text-decoration: none; font-weight: bold } + A.elRef { font-weight: bold } + A.code { text-decoration: none; font-weight: normal; color: #4444ee } + A.codeRef { font-weight: normal; color: #4444ee } Index: llvm-www/releases/1.8/docs/doxygen.footer diff -c /dev/null llvm-www/releases/1.8/docs/doxygen.footer:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/doxygen.footer Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,9 ---- +
    + + + Index: llvm-www/releases/1.8/docs/doxygen.header diff -c /dev/null llvm-www/releases/1.8/docs/doxygen.header:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/doxygen.header Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,9 ---- + + + + + + LLVM: $title + + +

    LLVM API Documentation

    Index: llvm-www/releases/1.8/docs/doxygen.intro diff -c /dev/null llvm-www/releases/1.8/docs/doxygen.intro:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/doxygen.intro Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,18 ---- + /// @mainpage Low Level Virtual Machine + /// + /// @section main_intro Introduction + /// Welcome to the Low Level Virtual Machine (LLVM). + /// + /// This documentation describes the @b internal software that makes + /// up LLVM, not the @b external use of LLVM. There are no instructions + /// here on how to use LLVM, only the APIs that make up the software. For usage + /// instructions, please see the programmer's guide or reference manual. + /// + /// @section main_caveat Caveat + /// This documentation is generated directly from the source code with doxygen. + /// Since LLVM is constantly under active development, what you're about to + /// read is out of date! However, it may still be useful since certain portions + /// of LLVM are very stable. + /// + /// @section main_changelog Change Log + /// - Original content written 12/30/2003 by Reid Spencer Index: llvm-www/releases/1.8/docs/index.html diff -c /dev/null llvm-www/releases/1.8/docs/index.html:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/index.html Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,265 ---- + + + + Documentation for the LLVM System + + + + +
    Documentation for the LLVM System
    + + + +
    +

    Written by The LLVM Team

    +
    + + + + + + + + + + + + + + + + + + + + + + + + +
      + +
    • Writing an LLVM Pass - Information + on how to write LLVM transformations and analyses.
    • + +
    • Writing an LLVM Backend - Information + on how to write LLVM backends for machine targets.
    • + +
    • The LLVM Target-Independent Code + Generator - The design and implementation of the LLVM code generator. + Useful if you are working on retargetting LLVM to a new architecture, designing + a new codegen pass, or enhancing existing components.
    • + +
    • TableGen Fundamentals - + Describes the TableGen tool, which is used heavily by the LLVM code + generator.
    • + +
    • Alias Analysis in LLVM - Information + on how to write a new alias analysis implementation or how to use existing + analyses.
    • + +
    • The Stacker Chronicles - This document + describes both the Stacker language and LLVM frontend, but also some details + about LLVM useful for those writing front-ends.
    • + +
    • Accurate Garbage Collection with + LLVM - The interfaces source-language compilers should use for compiling + GC'd programs.
    • + +
    • Source Level Debugging with + LLVM - This document describes the design and philosophy behind the LLVM + source-level debugger.
    • + +
    • Bugpoint - automatic bug finder and test-case + reducer description and usage information.
    • + +
    • Compiler Driver (llvmc) - This document + describes the design and configuration of the LLVM compiler driver tool, + llvmc.
    • + +
    • LLVM Bytecode File Format
    • + +
    • System Library - This document describes + the LLVM System Library (lib/System) and how to keep LLVM source code + portable
    • + +
    + + + + + + +
      +
    • The + LLVM Announcements List: This is a low volume list that provides important + announcements regarding LLVM. It gets email about once a month.
    • + +
    • The Developer's + List: This list is for people who want to be included in technical + discussions of LLVM. People post to this list when they have questions about + writing code for or using the LLVM tools. It is relatively low volume.
    • + +
    • The Bugs & + Patches Archive: This list gets emailed every time a bug is opened and + closed, and when people submit patches to be included in LLVM. It is higher + volume than the LLVMdev list.
    • + +
    • The CVS Commits + Archive: This list contains all commit messages that are made when LLVM + developers commit code changes to the CVS archive. It is useful for those who + want to stay on the bleeding edge of LLVM development. This list is very high + volume.
    • + +
    • The + Test Results Archive: A message is automatically sent to this list by every + active nightly tester when it completes. As such, this list gets email several + times each day, making it a high volume list.
    • + +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 05:56:40 $ +
    + Index: llvm-www/releases/1.8/docs/llvm.css diff -c /dev/null llvm-www/releases/1.8/docs/llvm.css:1.1 *** /dev/null Wed Aug 9 00:56:53 2006 --- llvm-www/releases/1.8/docs/llvm.css Wed Aug 9 00:56:40 2006 *************** *** 0 **** --- 1,84 ---- + /* + * LLVM documentation style sheet + */ + + /* Common styles */ + .body { color: black; background: white; margin: 0 0 0 0 } + + /* No borders on image links */ + a:link img, a:visited img {border-style: none} + + address img { float: right; width: 88px; height: 31px; } + address { clear: right; } + + TR, TD { border: 2px solid gray; padding: 4pt 4pt 2pt 2pt; } + TH { border: 2px solid gray; font-weight: bold; font-size: 105%; + color: black; background: url("img/lines.gif"); + font-family: "Georgia,Palatino,Times,Roman,SanSerif"; text-align:center; + vertical-align: middle; } + TABLE { text-align: center; border: 2px solid black; + border-collapse: collapse; margin-top: 1em; margin-left: 1em; + margin-right: 1em; margin-bottom: 1em; } + /* + * Documentation + */ + /* Common for title and header */ + .doc_title, .doc_section, .doc_subsection { + color: black; background: url("img/lines.gif"); + font-family: "Georgia,Palatino,Times,Roman,SanSerif"; font-weight: bold; + border-width: 1px; + border-style: solid none solid none; + text-align: center; + vertical-align: middle; + padding-left: 8pt; + padding-top: 1px; + padding-bottom: 2px + } + + .doc_title { text-align: left; font-size: 25pt } + .doc_section { text-align: center; font-size: 22pt; + margin: 20pt 0pt 5pt 0pt; } + .doc_subsection { width: 75%; + text-align: left; font-size: 12pt; padding: 4pt 4pt 4pt 4pt; + margin: 1.5em 0.5em 0.5em 0.5em } + + .doc_subsubsection { margin: 2.0em 0.5em 0.5em 0.5em; + font-weight: bold; font-style: oblique; + border-bottom: 1px solid #999999; font-size: 12pt; + width: 75%; } + .doc_author { text-align: left; font-weight: bold; padding-left: 20pt } + .doc_text { text-align: left; padding-left: 20pt; padding-right: 10pt } + + .doc_footer { text-align: left; padding: 0 0 0 0 } + + .doc_hilite { color: blue; font-weight: bold; } + + .doc_table { text-align: center; width: 90%; + padding: 1px 1px 1px 1px; border: 1px; } + + .doc_table_nw { text-align: center; border: 1px; + padding: 1px 1px 1px 1px; } + + .doc_warning { color: red; font-weight: bold } + + .doc_code { border: solid 1px gray; background: #eeeeee; + margin: 0 1em 0 1em; + padding: 0 1em 0 1em; + display:table; + } + .doc_notes { background: #fafafa; border: 1px solid #cecece; padding: 0.1em } + + TABLE.layout { text-align: left; border: none; border-collapse: collapse; + padding: 4px 4px 4px 4px; } + TR.layout { border: none; padding: 4pt 4pt 2pt 2pt; } + TD.layout { border: none; padding: 4pt 4pt 2pt 2pt; + vertical-align: top;} + TD.left { border: none; padding: 4pt 4pt 2pt 2pt; text-align: left; + vertical-align: top;} + TD.right { border: none; padding: 4pt 4pt 2pt 2pt; text-align: right; + vertical-align: top;} + TH.layout { border: none; font-weight: bold; font-size: 105%; + text-align:center; vertical-align: middle; } + + /* Left align table cell */ + .td_left { border: 2px solid gray; text-align: left; } From tbrethou at cs.uiuc.edu Wed Aug 9 00:59:58 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:59:58 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/CommandGuide/man/ Message-ID: <200608090559.k795xw48026375@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs/CommandGuide/man: --- Log message: Directory /var/cvs/llvm/llvm-www/releases/1.8/docs/CommandGuide/man added to the repository --- Diffs of the changes: (+0 -0) 0 files changed From tbrethou at cs.uiuc.edu Wed Aug 9 00:59:58 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:59:58 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/CommandGuide/html/ Message-ID: <200608090559.k795xw0Q026372@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs/CommandGuide/html: --- Log message: Directory /var/cvs/llvm/llvm-www/releases/1.8/docs/CommandGuide/html added to the repository --- Diffs of the changes: (+0 -0) 0 files changed From tbrethou at cs.uiuc.edu Wed Aug 9 00:59:58 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 00:59:58 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/CommandGuide/ps/ Message-ID: <200608090559.k795xwbt026378@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs/CommandGuide/ps: --- Log message: Directory /var/cvs/llvm/llvm-www/releases/1.8/docs/CommandGuide/ps added to the repository --- Diffs of the changes: (+0 -0) 0 files changed From tbrethou at cs.uiuc.edu Wed Aug 9 01:00:23 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 01:00:23 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/CommandGuide/Makefile analyze.pod bugpoint.pod gccas.pod gccld.pod index.html llc.pod lli.pod llvm-ar.pod llvm-as.pod llvm-bcanalyzer.pod llvm-config.pod llvm-db.pod llvm-dis.pod llvm-extract.pod llvm-ld.pod llvm-link.pod llvm-nm.pod llvm-prof.pod llvm-ranlib.pod llvm2cpp.pod llvmc.pod llvmgcc.pod llvmgxx.pod manpage.css opt.pod stkrc.pod tblgen.pod Message-ID: <200608090600.k7960N1k026473@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs/CommandGuide: Makefile added (r1.1) analyze.pod added (r1.1) bugpoint.pod added (r1.1) gccas.pod added (r1.1) gccld.pod added (r1.1) index.html added (r1.1) llc.pod added (r1.1) lli.pod added (r1.1) llvm-ar.pod added (r1.1) llvm-as.pod added (r1.1) llvm-bcanalyzer.pod added (r1.1) llvm-config.pod added (r1.1) llvm-db.pod added (r1.1) llvm-dis.pod added (r1.1) llvm-extract.pod added (r1.1) llvm-ld.pod added (r1.1) llvm-link.pod added (r1.1) llvm-nm.pod added (r1.1) llvm-prof.pod added (r1.1) llvm-ranlib.pod added (r1.1) llvm2cpp.pod added (r1.1) llvmc.pod added (r1.1) llvmgcc.pod added (r1.1) llvmgxx.pod added (r1.1) manpage.css added (r1.1) opt.pod added (r1.1) stkrc.pod added (r1.1) tblgen.pod added (r1.1) --- Log message: 1.8 docs --- Diffs of the changes: (+3928 -0) Makefile | 101 ++++++++++++ analyze.pod | 75 +++++++++ bugpoint.pod | 118 +++++++++++++++ gccas.pod | 76 +++++++++ gccld.pod | 175 ++++++++++++++++++++++ index.html | 166 +++++++++++++++++++++ llc.pod | 191 ++++++++++++++++++++++++ lli.pod | 97 ++++++++++++ llvm-ar.pod | 406 +++++++++++++++++++++++++++++++++++++++++++++++++++ llvm-as.pod | 77 +++++++++ llvm-bcanalyzer.pod | 315 ++++++++++++++++++++++++++++++++++++++++ llvm-config.pod | 131 ++++++++++++++++ llvm-db.pod | 16 ++ llvm-dis.pod | 60 +++++++ llvm-extract.pod | 63 ++++++++ llvm-ld.pod | 186 +++++++++++++++++++++++ llvm-link.pod | 74 +++++++++ llvm-nm.pod | 122 +++++++++++++++ llvm-prof.pod | 57 +++++++ llvm-ranlib.pod | 52 ++++++ llvm2cpp.pod | 209 ++++++++++++++++++++++++++ llvmc.pod | 407 ++++++++++++++++++++++++++++++++++++++++++++++++++++ llvmgcc.pod | 95 ++++++++++++ llvmgxx.pod | 95 ++++++++++++ manpage.css | 256 ++++++++++++++++++++++++++++++++ opt.pod | 97 ++++++++++++ stkrc.pod | 96 ++++++++++++ tblgen.pod | 115 ++++++++++++++ 28 files changed, 3928 insertions(+) Index: llvm-www/releases/1.8/docs/CommandGuide/Makefile diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/Makefile:1.1 *** /dev/null Wed Aug 9 01:00:20 2006 --- llvm-www/releases/1.8/docs/CommandGuide/Makefile Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,101 ---- + ##===- docs/CommandGuide/Makefile --------------------------*- Makefile -*-===## + # + # The LLVM Compiler Infrastructure + # + # This file was developed by the LLVM research group and is distributed under + # the University of Illinois Open Source License. See LICENSE.TXT for details. + # + ##===----------------------------------------------------------------------===## + + ifdef BUILD_FOR_WEBSITE + + # This special case is for keeping the CommandGuide on the LLVM web site + # up to date automatically as the documents are checked in. It must build + # the POD files to HTML only and keep them in the src directories. It must also + # build in an unconfigured tree, hence the ifdef. To use this, run + # make -s BUILD_FOR_WEBSITE=1 inside the cvs commit script. + + POD := $(wildcard *.pod) + HTML := $(patsubst %.pod, html/%.html, $(POD)) + MAN := $(patsubst %.pod, man/man1/%.1, $(POD)) + PS := $(patsubst %.pod, ps/%.ps, $(POD)) + + all: $(HTML) $(MAN) $(PS) + + .SUFFIXES: + .SUFFIXES: .html .pod .1 .ps + + html/%.html: %.pod + pod2html --css=manpage.css --htmlroot=. \ + --podpath=. --noindex --infile=$< --outfile=$@ --title=$* + + man/man1/%.1: %.pod + pod2man --release=CVS --center="LLVM Command Guide" $< $@ + + ps/%.ps: man/man1/%.1 + groff -Tps -man $< > $@ + + clean: + rm -f pod2htm*.*~~ $(HTML) $(MAN) $(PS) + + else + + LEVEL := ../.. + + include $(LEVEL)/Makefile.common + + POD := $(wildcard $(PROJ_SRC_DIR)/*.pod) + + EXTRA_DIST := $(POD) index.html + + HTML = $(patsubst $(PROJ_SRC_DIR)/%.pod, $(PROJ_OBJ_DIR)/%.html, $(POD)) + MAN = $(patsubst $(PROJ_SRC_DIR)/%.pod, $(PROJ_OBJ_DIR)/%.1, $(POD)) + PS = $(patsubst $(PROJ_SRC_DIR)/%.pod, $(PROJ_OBJ_DIR)/%.ps, $(POD)) + + .SUFFIXES: + .SUFFIXES: .html .pod .1 .ps + + $(HTML) : html/.dir man/.dir man/man1/.dir ps/.dir + + html: $(HTML) + + $(PROJ_OBJ_DIR)/%.html: %.pod + $(POD2HTML) --css=manpage.css --htmlroot=. --podpath=. \ + --noindex --infile=$< --outfile=$@ --title=$* + + $(PROJ_OBJ_DIR)/%.1: %.pod + $(POD2MAN) --release=$(LLVMVersion) \ + --center="LLVM Command Guide" $< $@ + + $(PROJ_OBJ_DIR)/%.ps: $(PROJ_OBJ_DIR)/%.1 + $(GROFF) -Tps -man $< > $@ + + clean-local:: + $(Verb) $(RM) -f pod2htm*.*~~ $(HTML) $(MAN) $(PS) + + HTML_DIR := $(PROJ_docsdir)/html/CommandGuide + MAN_DIR := $(PROJ_mandir)/man1 + PS_DIR := $(PROJ_docsdir)/ps + + install-local:: $(HTML) $(MAN) $(PS) + $(Echo) Installing HTML CommandGuide Documentation + $(Verb) $(MKDIR) $(HTML_DIR) + $(Verb) $(DataInstall) $(HTML) $(HTML_DIR) + $(Verb) $(DataInstall) $(PROJ_SRC_DIR)/index.html $(HTML_DIR) + $(Verb) $(DataInstall) $(PROJ_SRC_DIR)/manpage.css $(HTML_DIR) + $(Echo) Installing MAN CommandGuide Documentation + $(Verb) $(MKDIR) $(MAN_DIR) + $(Verb) $(DataInstall) $(MAN) $(MAN_DIR) + $(Echo) Installing PS CommandGuide Documentation + $(Verb) $(MKDIR) $(PS_DIR) + $(Verb) $(DataInstall) $(PS) $(PS_DIR) + + uninstall-local:: + $(Echo) Uninstalling Documentation + $(Verb) $(RM) -rf $(LLVM_DOCSDIR) + + printvars:: + $(Echo) "POD : " '$(POD)' + $(Echo) "HTML : " '$(HTML)' + + endif Index: llvm-www/releases/1.8/docs/CommandGuide/analyze.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/analyze.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/analyze.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,75 ---- + =pod + + =head1 NAME + + analyze - LLVM program analyzer + + =head1 SYNOPSIS + + B [I] [I] + + =head1 DESCRIPTION + + The B command performs various analysis of LLVM assembly + code or bytecode. It will usually print the results on standard + output, but in a few cases, it will print output to standard error + or generate a file with the analysis output, which is usually done + when the output is meant for another program. + + If filename is omitted or is I<->, B reads its input from + standard input. It first attempts to interpret its input as LLVM + bytecode. If it encounters an error, it then attempts to parse the + input as LLVM assembly language. + + =head1 OPTIONS + + =over + + =item B<-help> + + Print a summary of command line options. + + =item B<-q> + + Quiet mode. With this option, analysis pass names are not printed. + + =item B<-load> I + + Load the specified dynamic object with name I. This file + should contain additional analysis passes that register themselves + with the B program after being loaded. + + After being loaded, additional command line options are made + available for running the passes made available by I. Use + B I B<-help> to see the new list of available + analysis passes. + + =item B<-profile-info-file> I + + Specify the name of the file loaded by the -profile-loader option. + + =item B<-stats> + + Print statistics. + + =item B<-time-passes> + + Record the amount of time needed for each pass and print it to standard + error. + + =back + + =head1 EXIT STATUS + + If B succeeds, it will exit with 0. Otherwise, if an error + occurs, it will exit with a non-zero value. + + =head1 SEE ALSO + + L + + =head1 AUTHORS + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/bugpoint.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/bugpoint.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/bugpoint.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,118 ---- + =pod + + =head1 NAME + + bugpoint - automatic test case reduction tool + + =head1 SYNOPSIS + + B [I] [I] [I] B<--args> + I + + =head1 DESCRIPTION + + B narrows down the source of problems in LLVM tools and passes. It + can be used to debug three types of failures: optimizer crashes, miscompilations + by optimizers, or bad native code generation (including problems in the static + and JIT compilers). It aims to reduce large test cases to small, useful ones. + For more information on the design and inner workings of B, as well as + advice for using bugpoint, see F in the LLVM + distribution. + + =head1 OPTIONS + + =over + + =item B<--additional-so> F + + Load the dynamic shared object F into the test program whenever it is + run. This is useful if you are debugging programs which depend on non-LLVM + libraries (such as the X or curses libraries) to run. + + =item B<--args> I + + Pass all arguments specified after -args to the test program whenever it runs. + Note that if any of the I start with a '-', you should use: + + bugpoint [bugpoint args] --args -- [program args] + + The "--" right after the B<--args> option tells B to consider any + options starting with C<-> to be part of the B<--args> option, not as options to + B itself. + + =item B<--tool-args> I + + Pass all arguments specified after --tool-args to the LLVM tool under test + (B, B, etc.) whenever it runs. You should use this option in the + following way: + + bugpoint [bugpoint args] --tool-args -- [tool args] + + The "--" right after the B<--tool-args> option tells B to consider any + options starting with C<-> to be part of the B<--tool-args> option, not as + options to B itself. (See B<--args>, above.) + + =item B<--check-exit-code>=I<{true,false}> + + Assume a non-zero exit code or core dump from the test program is a failure. + Defaults to true. + + =item B<--disable-{dce,simplifycfg}> + + Do not run the specified passes to clean up and reduce the size of the test + program. By default, B uses these passes internally when attempting to + reduce test programs. If you're trying to find a bug in one of these passes, + B may crash. + + =item B<--help> + + Print a summary of command line options. + + =item B<--input> F + + Open F and redirect the standard input of the test program, whenever + it runs, to come from that file. + + =item B<--load> F + + Load the dynamic object F into B itself. This object should + register new optimization passes. Once loaded, the object will add new command + line options to enable various optimizations. To see the new complete list of + optimizations, use the B<--help> and B<--load> options together; for example: + + bugpoint --load myNewPass.so --help + + =item B<--output> F + + Whenever the test program produces output on its standard output stream, it + should match the contents of F (the "reference output"). If you + do not use this option, B will attempt to generate a reference output + by compiling the program with the C backend and running it. + + =item B<--profile-info-file> F + + Profile file loaded by B<--profile-loader>. + + =item B<--run-{int,jit,llc,cbe}> + + Whenever the test program is compiled, B should generate code for it + using the specified code generator. These options allow you to choose the + interpreter, the JIT compiler, the static native code compiler, or the C + backend, respectively. + + =back + + =head1 EXIT STATUS + + If B succeeds in finding a problem, it will exit with 0. Otherwise, + if an error occurs, it will exit with a non-zero value. + + =head1 SEE ALSO + + L, L + + =head1 AUTHOR + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/gccas.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/gccas.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/gccas.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,76 ---- + =pod + + =head1 NAME + + gccas - optimizing LLVM assembler + + =head1 SYNOPSIS + + B [I] I + + =head1 DESCRIPTION + + The B utility takes an LLVM assembly file generated by the + L or L front-ends and converts + it into an LLVM bytecode file. It is primarily used by the GCC + front end, and as such, attempts to mimic the interface provided + by the default system assembler so that it can act as a "drop-in" + replacement. + + B performs a number of optimizations on the input program, + including but not limited to: promotion of stack values to SSA + registers; elimination of dead globals, function arguments, code, + and types; tail-call elimination; loop-invariant code motion; global + common-subexpression elimination; and sparse conditional constant + propagation. + + =head1 OPTIONS + + =over + + =item B<--help> + + Print a summary of command line options. + + =item B<-o> F + + Specify the name of the output file which will hold the assembled bytecode. + + =item B<--disable-inlining> + + Disable the inlining pass. By default, it is enabled. + + =item B<--disable-opt> + + Disable all assembler-time optimization passes. + + =item B<--stats> + + Print statistics. + + =item B<--time-passes> + + Record the amount of time needed for each pass and print it to standard + error. + + =item B<--verify> + + Verify each pass result. + + =back + + =head1 EXIT STATUS + + If B succeeds, it will exit with an exit status of 0. + Otherwise, if an error occurs, it will exit with a non-zero exit + status. + + =head1 SEE ALSO + + L, L + + =head1 AUTHORS + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/gccld.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/gccld.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/gccld.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,175 ---- + =pod + + =head1 NAME + + gccld - optimizing LLVM linker + + =head1 SYNOPSIS + + B [I] I + + =head1 DESCRIPTION + + The B utility takes a set of LLVM bytecode files and links them + together into a single LLVM bytecode file. The output bytecode file can be + another bytecode library or an executable bytecode program. Using additional + options, B is able to produce native code executables. + + The B utility is primarily used by the L and + L front-ends, and as such, attempts to mimic the interface + provided by the default system linker so that it can act as a ``drop-in'' + replacement. + + The B tool performs a small set of interprocedural, post-link + optimizations on the program. + + =head2 Search Order + + When looking for objects specified on the command line, B will search for + the object first in the current directory and then in the directory specified by + the B environment variable. If it cannot find the object, + it fails. + + When looking for a library specified with the B<-l> option, B first + attempts to load a file with that name from the current directory. If that + fails, it looks for libI.bc, libI.a, or libI.I, in that order, in each directory added to the library search + path with the B<-L> option. These directories are searched in the order they + were specified. If the library cannot be located, then B looks in the + directory specified by the B environment variable. If it + does not find a library there, it fails. + + The shared library extension may be I<.so>, I<.dyld>, I<.dll>, or something + different, depending upon the system. + + The B<-L> option is global. It does not matter where it is specified in the + list of command line arguments; the directory is simply added to the search path + and is applied to all libraries, preceding or succeeding, in the command line. + + =head2 Link order + + All object files are linked first in the order they were specified on the + command line. All library files are linked next. Some libraries may not be + linked into the object program; see below. + + =head2 Library Linkage + + Object files and static bytecode objects are always linked into the output + file. Library archives (.a files) load only the objects within the archive + that define symbols needed by the output file. Hence, libraries should be + listed after the object files and libraries which need them; otherwise, the + library may not be linked in, and the dependent library will not have its + undefined symbols defined. + + =head2 Native code generation + + The B program has limited support for native code generation, when + using the B<-native> or B<-native-cbe> options. + + =head1 OPTIONS + + =over + + =item B<-help> + + Print a summary of command line options. + + =item B<-o> I + + Specify the output filename which will hold the linked bytecode. + + =item B<-stats> + + Print statistics. + + =item B<-time-passes> + + Record the amount of time needed for each pass and print it to standard + error. + + =item B<-verify> + + Verify each pass result. + + =item B<-disable-opt> + + Disable all link-time optimization passes. + + =item B<-disable-inlining> + + Do not run the inliner pass. + + =item B<-L>I + + Add directory to the list of directories to search when looking for + libraries. + + =item B<-disable-internalize> + + Do not mark all symbols as internal. + + =item B<-internalize-public-api-file> I + + Preserve the list of symbol names in the file filename. + + =item B<-internalize-public-api-list> I + + Preserve the symbol names in list. + + =item B<-l>I + + Specify libraries to include when linking the output file. When linking, + B will first attempt to load a file with the pathname B. If + that fails, it will then attempt to load libI.bc, libI.a, and + libI.I, in that order. + + =item B<-link-as-library> + + Link the .bc files together as a library, not an executable. + + =item B<-native> + + Generate a native machine code executable. + + When generating native executables, B first checks for a bytecode + version of the library and links it in, if necessary. If the library is + missing, B skips it. Then, B links in the same + libraries as native code. + + In this way, B should be able to link in optimized bytecode + subsets of common libraries and then link in any part of the library that + hasn't been converted to bytecode. + + =item B<-native-cbe> + + Generate a native machine code executable with the LLVM C backend. + + This option is identical to the B<-native> option, but uses the + C backend to generate code for the program instead of an LLVM native + code generator. + + =item B<-s> + + Strip symbol information from the generated executable. + + =item B<-v> + + Print information about actions taken. + + =back + + =head1 EXIT STATUS + + If B succeeds, it will exit with an exit status of 0. + Otherwise, if an error occurs, it will exit with a non-zero exit + status. + + =head1 SEE ALSO + + L, L + + =head1 AUTHORS + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/index.html diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/index.html:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/index.html Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,166 ---- + + + + LLVM Command Guide + + + + +
    + LLVM Command Guide +
    + +
    + +

    These documents are HTML versions of the man pages + for all of the LLVM tools. These pages describe how to use the LLVM commands + and what their options are. Note that these pages do not describe all of the + options available for all tools. To get a complete listing, pass the + --help (general options) or --help-hidden (general+debugging + options) arguments to the tool you are interested in.

    + +
    + + + + + +
    + +
      + +
    • llvm-as - + assemble a human-readable .ll file into bytecode
    • + +
    • llvm-dis - + disassemble a bytecode file into a human-readable .ll file
    • + +
    • opt - + run a series of LLVM-to-LLVM optimizations on a bytecode file
    • + +
    • llc - + generate native machine code for a bytecode file
    • + +
    • lli - + directly run a program compiled to bytecode using a JIT compiler or + interpreter
    • + +
    • llvm-link - + link several bytecode files into one
    • + +
    • analyze - + run LLVM analyses on a bytecode file and print the results
    • + +
    • llvm-ar - + archive bytecode files
    • + +
    • llvm-ranlib - + create an index for archives made with llvm-ar
    • + +
    • llvm-nm - + print out the names and types of symbols in a bytecode file
    • + +
    • llvm-prof - + format raw `llvmprof.out' data into a human-readable report
    • + +
    • llvmc - + generic and configurable compiler driver
    • + +
    • llvm-ld - + general purpose linker with loadable runtime optimization support
    • + +
    • llvm-config - + print out LLVM compilation options, libraries, etc. as configured.
    • + +
    • llvm2cpp - convert LLVM assembly + into the corresponding LLVM C++ API calls to produce it
    • +
    + +
    + + + + + +
    +
      + +
    • llvmgcc - + GCC-based C front-end for LLVM + +
    • llvmg++ - + GCC-based C++ front-end for LLVM
    • + +
    • gccas - + compile-time optimizer used by llvm-g++ and llvm-gcc
    • + +
    • gccld - + linker and link-time optimizer used by llvm-g++ and llvm-gcc
    • + +
    • stkrc - + front-end compiler for the Stacker + language
    • + +
    + +
    + + + + + + +
    + +
      + +
    • bugpoint - + automatic test-case reducer
    • + +
    • llvm-extract - + extract a function from an LLVM bytecode file
    • + +
    • llvm-bcanalyzer - + bytecode analyzer (analyzes the binary encoding itself, not the program it + represents)
    • + +
    +
    + + + + + +
    +
      + +
    • tblgen - + target description reader and generator
    • + +
    +
    + + + +
    +
    + Valid CSS! + Valid HTML 4.01! + + LLVM Compiler Infrastructure
    + Last modified: $Date: 2006/08/09 06:00:10 $ +
    + + + Index: llvm-www/releases/1.8/docs/CommandGuide/llc.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/llc.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/llc.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,191 ---- + =pod + + =head1 NAME + + llc - LLVM static compiler + + =head1 SYNOPSIS + + B [I] [I] + + =head1 DESCRIPTION + + The B command compiles LLVM bytecode into assembly language for a + specified architecture. The assembly language output can then be passed through + a native assembler and linker to generate a native executable. + + The choice of architecture for the output assembly code is automatically + determined from the input bytecode file, unless the B<-march> option is used to + override the default. + + =head1 OPTIONS + + If I is - or omitted, B reads LLVM bytecode from standard input. + Otherwise, it will read LLVM bytecode from I. + + If the B<-o> option is omitted, then B will send its output to standard + output if the input is from standard input. If the B<-o> option specifies -, + then the output will also be sent to standard output. + + If no B<-o> option is specified and an input file other than - is specified, + then B creates the output filename by taking the input filename, + removing any existing F<.bc> extension, and adding a F<.s> suffix. + + Other B options are as follows: + + =head2 End-user Options + + =over + + =item B<--help> + + Print a summary of command line options. + + =item B<-f> + + Overwrite output files. By default, B will refuse to overwrite + an output file which already exists. + + =item B<-mtriple>=I + + Override the target triple specified in the input bytecode file with the + specified string. + + =item B<-march>=I + + Specify the architecture for which to generate assembly, overriding the target + encoded in the bytecode file. See the output of B for a list of + valid architectures. By default this is inferred from the target triple or + autodetected to the current architecture. + + =item B<-mcpu>=I + + Specify a specific chip in the current architecture to generate code for. + By default this is inferred from the target triple and autodetected to + the current architecture. For a list of available CPUs, use: + B /dev/null | llc -march=xyz -mcpu=help> + + =item B<-mattr>=I + + Override or control specific attributes of the target, such as whether SIMD + operations are enabled or not. The default set of attributes is set by the + current CPU. For a list of available attributes, use: + B /dev/null | llc -march=xyz -mattr=help> + + =item B<--disable-fp-elim> + + Disable frame pointer elimination optimization. + + =item B<--disable-excess-fp-precision> + + Disable optimizations that may produce excess precision for floating point. + Note that this option can dramatically slow down code on some systems + (e.g. X86). + + =item B<--enable-unsafe-fp-math> + + Enable optimizations that make unsafe assumptions about IEEE math (e.g. that + addition is associative) or may not work for all input ranges. These + optimizations allow the code generator to make use of some instructions which + would otherwise not be usable (such as fsin on X86). + + =item B<--enable-correct-eh-support> + + Instruct the B pass to insert code for correct exception handling + support. This is expensive and is by default omitted for efficiency. + + =item B<--stats> + + Print statistics recorded by code-generation passes. + + =item B<--time-passes> + + Record the amount of time needed for each pass and print a report to standard + error. + + =item B<--load>=F + + Dynamically load F (a path to a dynamically shared object) that + implements an LLVM target. This will permit the target name to be used with the + B<-march> option so that code can be generated for that target. + + =back + + =head2 Tuning/Configuration Options + + =over + + =item B<--print-machineinstrs> + + Print generated machine code between compilation phases (useful for debugging). + + =item B<--regalloc>=I + + Specify the register allocator to use. The default I is I. + Valid register allocators are: + + =over + + =item I + + Very simple "always spill" register allocator + + =item I + + Local register allocator + + =item I + + Linear scan global register allocator + + =item I + + Iterative scan global register allocator + + =back + + =item B<--spiller>=I + + Specify the spiller to use for register allocators that support it. Currently + this option is used only by the linear scan register allocator. The default + I is I. Valid spillers are: + + =over + + =item I + + Simple spiller + + =item I + + Local spiller + + =back + + =back + + =head2 Intel IA-32-specific Options + + =over + + =item B<--x86-asm-syntax=att|intel> + + Specify whether to emit assembly code in AT&T syntax (the default) or intel + syntax. + + =back + + =head1 EXIT STATUS + + If B succeeds, it will exit with 0. Otherwise, if an error occurs, + it will exit with a non-zero value. + + =head1 SEE ALSO + + L + + =head1 AUTHORS + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/lli.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/lli.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/lli.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,97 ---- + =pod + + =head1 NAME + + lli - directly execute programs from LLVM bytecode + + =head1 SYNOPSIS + + B [I] [I] [I] + + =head1 DESCRIPTION + + B directly executes programs in LLVM bytecode format. It takes a program + in LLVM bytecode format and executes it using a just-in-time compiler, if one is + available for the current architecture, or an interpreter. B takes all of + the same code generator options as L, but they are only effective when + B is using the just-in-time compiler. + + If I is not specified, then B reads the LLVM bytecode for the + program from standard input. + + The optional I specified on the command line are passed to the program as + arguments. + + =head1 OPTIONS + + =over + + =item B<-help> + + Print a summary of command line options. + + =item B<-stats> + + Print statistics from the code-generation passes. This is only meaningful for + the just-in-time compiler, at present. + + =item B<-time-passes> + + Record the amount of time needed for each code-generation pass and print it to + standard error. + + =item B<-mtriple>=I + + Override the target triple specified in the input bytecode file with the + specified string. This may result in a crash if you pick an + architecture which is not compatible with the current system. + + =item B<-march>=I + + Specify the architecture for which to generate assembly, overriding the target + encoded in the bytecode file. See the output of B for a list of + valid architectures. By default this is inferred from the target triple or + autodetected to the current architecture. + + =item B<-mcpu>=I + + Specify a specific chip in the current architecture to generate code for. + By default this is inferred from the target triple and autodetected to + the current architecture. For a list of available CPUs, use: + B /dev/null | llc -march=xyz -mcpu=help> + + =item B<-mattr>=I + + Override or control specific attributes of the target, such as whether SIMD + operations are enabled or not. The default set of attributes is set by the + current CPU. For a list of available attributes, use: + B /dev/null | llc -march=xyz -mattr=help> + + =item B<-force-interpreter>=I<{false,true}> + + If set to true, use the interpreter even if a just-in-time compiler is available + for this architecture. Defaults to false. + + =item B<-f>=I + + Call the function named I to start the program. Note: The + function is assumed to have the C signature C I C<(int, + char **, char **)>. If you try to use this option to call a function of + incompatible type, undefined behavior may result. Defaults to C
    . + + =back + + =head1 EXIT STATUS + + If B fails to load the program, it will exit with an exit code of 1. + Otherwise, it will return the exit code of the program it executes. + + =head1 SEE ALSO + + L + + =head1 AUTHOR + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/llvm-ar.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/llvm-ar.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/llvm-ar.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,406 ---- + =pod + + =head1 NAME + + llvm-ar - LLVM archiver + + =head1 SYNOPSIS + + B [-]{dmpqrtx}[Rabfikouz] [relpos] [count] [files...] + + + =head1 DESCRIPTION + + The B command is similar to the common Unix utility, C. It + archives several files together into a single file. The intent for this is + to produce archive libraries by LLVM bytecode that can be linked into an + LLVM program. However, the archive can contain any kind of file. By default, + B generates a symbol table that makes linking faster because + only the symbol table needs to be consulted, not each individual file member + of the archive. + + The B command can be used to I both SVR4 and BSD style archive + files. However, it cannot be used to write them. While the B command + produces files that are I identical to the format used by other C + implementations, it has two significant departures in order to make the + archive appropriate for LLVM. The first departure is that B only + uses BSD4.4 style long path names (stored immediately after the header) and + never contains a string table for long names. The second departure is that the + symbol table is formated for efficient construction of an in-memory data + structure that permits rapid (red-black tree) lookups. Consequently, archives + produced with B usually won't be readable or editable with any + C implementation or useful for linking. Using the C modifier to flatten + file names will make the archive readable by other C implementations + but not for linking because the symbol table format for LLVM is unique. If an + SVR4 or BSD style archive is used with the C (replace) or C (quick + update) operations, the archive will be reconstructed in LLVM format. This + means that the string table will be dropped (in deference to BSD 4.4 long names) + and an LLVM symbol table will be added (by default). The system symbol table + will be retained. + + Here's where B departs from previous C implementations: + + =over + + =item I + + Since B is intended to archive bytecode files, the symbol table + won't make much sense to anything but LLVM. Consequently, the symbol table's + format has been simplified. It consists simply of a sequence of pairs + of a file member index number as an LSB 4byte integer and a null-terminated + string. + + =item I + + Some C implementations (SVR4) use a separate file member to record long + path names (> 15 characters). B takes the BSD 4.4 and Mac OS X + approach which is to simply store the full path name immediately preceding + the data for the file. The path name is null terminated and may contain the + slash (/) character. + + =item I + + B can compress the members of an archive to save space. The + compression used depends on what's available on the platform and what choices + the LLVM Compressor utility makes. It generally favors bzip2 but will select + between "no compression" or bzip2 depending on what makes sense for the + file's content. + + =item I + + Most C implementations do not recurse through directories but simply + ignore directories if they are presented to the program in the F + option. B, however, can recurse through directory structures and + add all the files under a directory, if requested. + + =item I + + When B prints out the verbose table of contents (C option), it + precedes the usual output with a character indicating the basic kind of + content in the file. A blank means the file is a regular file. A 'Z' means + the file is compressed. A 'B' means the file is an LLVM bytecode file. An + 'S' means the file is the symbol table. + + =back + + =head1 OPTIONS + + The options to B are compatible with other C implementations. + However, there are a few modifiers (F) that are not found in other + Cs. The options to B specify a single basic operation to + perform on the archive, a variety of modifiers for that operation, the + name of the archive file, and an optional list of file names. These options + are used to determine how B should process the archive file. + + The Operations and Modifiers are explained in the sections below. The minimal + set of options is at least one operator and the name of the archive. Typically + archive files end with a C<.a> suffix, but this is not required. Following + the F comes a list of F that indicate the specific members + of the archive to operate on. If the F option is not specified, it + generally means either "none" or "all" members, depending on the operation. + + =head2 Operations + + =over + + =item d + + Delete files from the archive. No modifiers are applicable to this operation. + The F options specify which members should be removed from the + archive. It is not an error if a specified file does not appear in the archive. + If no F are specified, the archive is not modified. + + =item m[abi] + + Move files from one location in the archive to another. The F, F, and + F modifiers apply to this operation. The F will all be moved + to the location given by the modifiers. If no modifiers are used, the files + will be moved to the end of the archive. If no F are specified, the + archive is not modified. + + =item p[k] + + Print files to the standard output. The F modifier applies to this + operation. This operation simply prints the F indicated to the + standard output. If no F are specified, the entire archive is printed. + Printing bytecode files is ill-advised as they might confuse your terminal + settings. The F

    operation is used. This modifier defeats the default and allows the + bytecode members to be printed. + + =item [N] + + This option is ignored by B but provided for compatibility. + + =item [o] + + When extracting files, this option will cause B to preserve the + original modification times of the files it writes. + + =item [P] + + use full path names when matching + + =item [R] + + This modifier instructions the F option to recursively process directories. + Without F, directories are ignored and only those F that refer to + files will be added to the archive. When F is used, any directories specified + with F will be scanned (recursively) to find files to be added to the + archive. Any file whose name begins with a dot will not be added. + + =item [u] + + When replacing existing files in the archive, only replace those files that have + a time stamp than the time stamp of the member in the archive. + + =item [z] + + When inserting or replacing any file in the archive, compress the file first. + This + modifier is safe to use when (previously) compressed bytecode files are added to + the archive; the compressed bytecode files will not be doubly compressed. + + =back + + =head2 Modifiers (generic) + + The modifiers below may be applied to any operation. + + =over + + =item [c] + + For all operations, B will always create the archive if it doesn't + exist. Normally, B will print a warning message indicating that the + archive is being created. Using this modifier turns off that warning. + + =item [s] + + This modifier requests that an archive index (or symbol table) be added to the + archive. This is the default mode of operation. The symbol table will contain + all the externally visible functions and global variables defined by all the + bytecode files in the archive. Using this modifier is more efficient that using + L which also creates the symbol table. + + =item [S] + + This modifier is the opposite of the F modifier. It instructs B to + not build the symbol table. If both F and F are used, the last modifier to + occur in the options will prevail. + + =item [v] + + This modifier instructs B to be verbose about what it is doing. Each + editing operation taken against the archive will produce a line of output saying + what is being done. + + =back + + =head1 STANDARDS + + The B utility is intended to provide a superset of the IEEE Std 1003.2 + (POSIX.2) functionality for C. B can read both SVR4 and BSD4.4 (or + Mac OS X) archives. If the C modifier is given to the C or C operations + then B will write SVR4 compatible archives. Without this modifier, + B will write BSD4.4 compatible archives that have long names + immediately after the header and indicated using the "#1/ddd" notation for the + name in the header. + + =head1 FILE FORMAT + + The file format for LLVM Archive files is similar to that of BSD 4.4 or Mac OSX + archive files. In fact, except for the symbol table, the C commands on those + operating systems should be able to read LLVM archive files. The details of the + file format follow. + + Each archive begins with the archive magic number which is the eight printable + characters "!\n" where \n represents the newline character (0x0A). + Following the magic number, the file is composed of even length members that + begin with an archive header and end with a \n padding character if necessary + (to make the length even). Each file member is composed of a header (defined + below), an optional newline-terminated "long file name" and the contents of + the file. + + The fields of the header are described in the items below. All fields of the + header contain only ASCII characters, are left justified and are right padded + with space characters. + + =over + + =item name - char[16] + + This field of the header provides the name of the archive member. If the name is + longer than 15 characters or contains a slash (/) character, then this field + contains C<#1/nnn> where C provides the length of the name and the C<#1/> + is literal. In this case, the actual name of the file is provided in the C + bytes immediately following the header. If the name is 15 characters or less, it + is contained directly in this field and terminated with a slash (/) character. + + =item date - char[12] + + This field provides the date of modification of the file in the form of a + decimal encoded number that provides the number of seconds since the epoch + (since 00:00:00 Jan 1, 1970) per Posix specifications. + + =item uid - char[6] + + This field provides the user id of the file encoded as a decimal ASCII string. + This field might not make much sense on non-Unix systems. On Unix, it is the + same value as the st_uid field of the stat structure returned by the stat(2) + operating system call. + + =item gid - char[6] + + This field provides the group id of the file encoded as a decimal ASCII string. + This field might not make much sense on non-Unix systems. On Unix, it is the + same value as the st_gid field of the stat structure returned by the stat(2) + operating system call. + + =item mode - char[8] + + This field provides the access mode of the file encoded as an octal ASCII + string. This field might not make much sense on non-Unix systems. On Unix, it + is the same value as the st_mode field of the stat structure returned by the + stat(2) operating system call. + + =item size - char[10] + + This field provides the size of the file, in bytes, encoded as a decimal ASCII + string. If the size field is negative (starts with a minus sign, 0x02D), then + the archive member is stored in compressed form. The first byte of the archive + member's data indicates the compression type used. A value of 0 (0x30) indicates + that no compression was used. A value of 2 (0x32) indicates that bzip2 + compression was used. + + =item fmag - char[2] + + This field is the archive file member magic number. Its content is always the + two characters back tick (0x60) and newline (0x0A). This provides some measure + utility in identifying archive files that have been corrupted. + + =back + + The LLVM symbol table has the special name "#_LLVM_SYM_TAB_#". It is presumed + that no regular archive member file will want this name. The LLVM symbol table + is simply composed of a sequence of triplets: byte offset, length of symbol, + and the symbol itself. Symbols are not null or newline terminated. Here are + the details on each of these items: + + =over + + =item offset - vbr encoded 32-bit integer + + The offset item provides the offset into the archive file where the bytecode + member is stored that is associated with the symbol. The offset value is 0 + based at the start of the first "normal" file member. To derive the actual + file offset of the member, you must add the number of bytes occupied by the file + signature (8 bytes) and the symbol tables. The value of this item is encoded + using variable bit rate encoding to reduce the size of the symbol table. + Variable bit rate encoding uses the high bit (0x80) of each byte to indicate + if there are more bytes to follow. The remaining 7 bits in each byte carry bits + from the value. The final byte does not have the high bit set. + + =item length - vbr encoded 32-bit integer + + The length item provides the length of the symbol that follows. Like this + I item, the length is variable bit rate encoded. + + =item symbol - character array + + The symbol item provides the text of the symbol that is associated with the + I. The symbol is not terminated by any character. Its length is provided + by the I field. Note that is allowed (but unwise) to use non-printing + characters (even 0x00) in the symbol. This allows for multiple encodings of + symbol names. + + =back + + =head1 EXIT STATUS + + If B succeeds, it will exit with 0. A usage error, results + in an exit code of 1. A hard (file system typically) error results in an + exit code of 2. Miscellaneous or unknown errors result in an + exit code of 3. + + =head1 SEE ALSO + + L, L + + =head1 AUTHORS + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/llvm-as.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/llvm-as.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/llvm-as.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,77 ---- + =pod + + =head1 NAME + + llvm-as - LLVM assembler + + =head1 SYNOPSIS + + B [I] [I] + + =head1 DESCRIPTION + + B is the LLVM assembler. It reads a file containing human-readable + LLVM assembly language, translates it to LLVM bytecode, and writes the result + into a file or to standard output. + + If F is omitted or is C<->, then B reads its input from + standard input. + + If an output file is not specified with the B<-o> option, then + B sends its output to a file or standard output by following + these rules: + + =over + + =item * + + If the input is standard input, then the output is standard output. + + =item * + + If the input is a file that ends with C<.ll>, then the output file is of + the same name, except that the suffix is changed to C<.bc>. + + =item * + + If the input is a file that does not end with the C<.ll> suffix, then the + output file has the same name as the input file, except that the C<.bc> + suffix is appended. + + =back + + =head1 OPTIONS + + =over + + =item B<-f> + + Force overwrite. Normally, B will refuse to overwrite an + output file that already exists. With this option, B + will overwrite the output file and replace it with new bytecode. + + =item B<--help> + + Print a summary of command line options. + + =item B<-o> F + + Specify the output file name. If F is C<->, then B + sends its output to standard output. + + =back + + =head1 EXIT STATUS + + If B succeeds, it will exit with 0. Otherwise, if an error + occurs, it will exit with a non-zero value. + + =head1 SEE ALSO + + L, L + + =head1 AUTHORS + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/llvm-bcanalyzer.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/llvm-bcanalyzer.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/llvm-bcanalyzer.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,315 ---- + =pod + + =head1 NAME + + llvm-bcanalyzer - LLVM bytecode analyzer + + =head1 SYNOPSIS + + B [I] [F] + + =head1 DESCRIPTION + + The B command is a small utility for analyzing bytecode files. + The tool reads a bytecode file (such as generated with the B tool) and + produces a statistical report on the contents of the byteocde file. The tool + can also dump a low level but human readable version of the bytecode file. + This tool is probably not of much interest or utility except for those working + directly with the bytecode file format. Most LLVM users can just ignore + this tool. + + If F is omitted or is C<->, then B reads its input + from standard input. This is useful for combining the tool into a pipeline. + Output is written to the standard output. + + =head1 OPTIONS + + =over + + =item B<-nodetails> + + Causes B to abbreviate its output by writing out only a module + level summary. The details for individual functions are not displayed. + + =item B<-dump> + + Causes B to dump the bytecode in a human readable format. This + format is significantly different from LLVM assembly and provides details about + the encoding of the bytecode file. + + =item B<-verify> + + Causes B to verify the module produced by reading the + bytecode. This ensures that the statistics generated are based on a consistent + module. + + =item B<--help> + + Print a summary of command line options. + + =back + + =head1 EXIT STATUS + + If B succeeds, it will exit with 0. Otherwise, if an error + occurs, it will exit with a non-zero value, usually 1. + + =head1 SUMMARY OUTPUT DEFINITIONS + + The following items are always printed by llvm-bcanalyzer. They comprize the + summary output. + + =over + + =item B + + This just provides the name of the module for which bytecode analysis is being + generated. + + =item B + + The bytecode version (not LLVM version) of the file read by the analyzer. + + =item B + + The size, in bytes, of the entire bytecode file. + + =item B + + The size, in bytes, of the module block. Percentage is relative to File Size. + + =item B + + The size, in bytes, of all the function blocks. Percentage is relative to File + Size. + + =item B + + The size, in bytes, of the Global Types Pool. Percentage is relative to File + Size. This is the size of the definitions of all types in the bytecode file. + + =item B + + The size, in bytes, of the Constant Pool Blocks Percentage is relative to File + Size. + + =item B + + Ths size, in bytes, of the Global Variable Definitions and their initializers. + Percentage is relative to File Size. + + =item B + + The size, in bytes, of all the instruction lists in all the functions. + Percentage is relative to File Size. Note that this value is also included in + the Function Bytes. + + =item B + + The size, in bytes, of all the compaction tables in all the functions. + Percentage is relative to File Size. Note that this value is also included in + the Function Bytes. + + =item B + + The size, in bytes, of all the symbol tables in all the functions. Percentage is + relative to File Size. Note that this value is also included in the Function + Bytes. + + =item B + + The size, in bytes, of the list of dependent libraries in the module. Percentage + is relative to File Size. Note that this value is also included in the Module + Global Bytes. + + =item B + + The total number of blocks of any kind in the bytecode file. + + =item B + + The total number of function definitions in the bytecode file. + + =item B + + The total number of types defined in the Global Types Pool. + + =item B + + The total number of constants (of any type) defined in the Constant Pool. + + =item B + + The total number of basic blocks defined in all functions in the bytecode file. + + =item B + + The total number of instructions defined in all functions in the bytecode file. + + =item B + + The total number of long instructions defined in all functions in the bytecode + file. Long instructions are those taking greater than 4 bytes. Typically long + instructions are GetElementPtr with several indices, PHI nodes, and calls to + functions with large numbers of arguments. + + =item B + + The total number of operands used in all instructions in the bytecode file. + + =item B + + The total number of compaction tables in all functions in the bytecode file. + + =item B + + The total number of symbol tables in all functions in the bytecode file. + + =item B + + The total number of dependent libraries found in the bytecode file. + + =item B + + The total size of the instructions in all functions in the bytecode file. + + =item B + + The average number of bytes per instruction across all functions in the bytecode + file. This value is computed by dividing Total Instruction Size by Number Of + Instructions. + + =item B + + The maximum value used for a type's slot number. Larger slot number values take + more bytes to encode. + + =item B + + The maximum value used for a value's slot number. Larger slot number values take + more bytes to encode. + + =item B + + The average size of a Value definition (of any type). This is computed by + dividing File Size by the total number of values of any type. + + =item B + + The average size of a global definition (constants and global variables). + + =item B + + The average number of bytes per function definition. This is computed by + dividing Function Bytes by Number Of Functions. + + =item B<# of VBR 32-bit Integers> + + The total number of 32-bit integers encoded using the Variable Bit Rate + encoding scheme. + + =item B<# of VBR 64-bit Integers> + + The total number of 64-bit integers encoded using the Variable Bit Rate encoding + scheme. + + =item B<# of VBR Compressed Bytes> + + The total number of bytes consumed by the 32-bit and 64-bit integers that use + the Variable Bit Rate encoding scheme. + + =item B<# of VBR Expanded Bytes> + + The total number of bytes that would have been consumed by the 32-bit and 64-bit + integers had they not been compressed with the Variable Bit Rage encoding + scheme. + + =item B + + The total number of bytes saved by using the Variable Bit Rate encoding scheme. + The percentage is relative to # of VBR Expanded Bytes. + + =back + + =head1 DETAILED OUTPUT DEFINITIONS + + The following definitions occur only if the -nodetails option was not given. + The detailed output provides additional information on a per-function basis. + + =over + + =item B + + The type signature of the function. + + =item B + + The total number of bytes in the function's block. + + =item B + + The number of basic blocks defined by the function. + + =item B + + The number of instructions defined by the function. + + =item B + + The number of instructions using the long instruction format in the function. + + =item B + + The number of operands used by all instructions in the function. + + =item B + + The number of bytes consumed by instructions in the function. + + =item B + + The average number of bytes consumed by the instructions in the funtion. This + value is computed by dividing Instruction Size by Instructions. + + =item B + + The average number of bytes used by the function per instruction. This value is + computed by dividing Byte Size by Instructions. Note that this is not the same + as Average Instruction Size. It computes a number relative to the total function + size not just the size of the instruction list. + + =item B + + The total number of 32-bit integers found in this function (for any use). + + =item B + + The total number of 64-bit integers found in this function (for any use). + + =item B + + The total number of bytes in this function consumed by the 32-bit and 64-bit + integers that use the Variable Bit Rate encoding scheme. + + =item B + + The total number of bytes in this function that would have been consumed by + the 32-bit and 64-bit integers had they not been compressed with the Variable + Bit Rate encoding scheme. + + =item B + + The total number of bytes saved in this function by using the Variable Bit + Rate encoding scheme. The percentage is relative to # of VBR Expanded Bytes. + + =back + + =head1 SEE ALSO + + L, L + + =head1 AUTHORS + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/llvm-config.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/llvm-config.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/llvm-config.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,131 ---- + =pod + + =head1 NAME + + llvm-config - Print LLVM compilation options + + =head1 SYNOPSIS + + B I

    :I=I + + This option instructs B to accept I as the value for configuration + item I in the section named I
    . This is a quick way to override + a configuration item on the command line without resorting to changing the + configuration files. + + =item B<--config-only-from> F + + This option tells B to skip the normal processing of configuration + files and only configure from the contents of the F directory. Multiple + B<--config-only-from> options may be given in which case the directories are + read in the order given on the command line. + + =item B<--emit-raw-code> + + No optimization is done whatsoever. The compilers invoked by B with + this option given will be instructed to produce raw, unoptimized code. This + option is useful only to front end language developers and therefore does not + participate in the list of B<-O> options. This is distinctly different from + the B<-O0> option (a synonym for B<-O1>) because those optimizations will + reduce code size to make compilation faster. With B<--emit-raw-code>, only + the full raw code produced by the compiler will be generated. + + =back + + + =head1 EXIT STATUS + + If B succeeds, it will exit with 0. Otherwise, if an error + occurs, it will exit with a non-zero value and no compilation actions + will be taken. If one of the compilation tools returns a non-zero + status, pending actions will be discarded and B will return the + same result code as the failing compilation tool. + + =head1 SEE ALSO + + L, L, L, L, + L, L + + =head1 AUTHORS + + Maintained by the LLVM Team (L). + + =cut Index: llvm-www/releases/1.8/docs/CommandGuide/llvmgcc.pod diff -c /dev/null llvm-www/releases/1.8/docs/CommandGuide/llvmgcc.pod:1.1 *** /dev/null Wed Aug 9 01:00:23 2006 --- llvm-www/releases/1.8/docs/CommandGuide/llvmgcc.pod Wed Aug 9 01:00:10 2006 *************** *** 0 **** --- 1,95 ---- + =pod + + =head1 NAME + + llvm-gcc - LLVM C front-end + + =head1 SYNOPSIS + + B [I] I + + =head1 DESCRIPTION + + The B command is the LLVM C front end. It is a modified + version of gcc that takes C programs and compiles them into LLVM + bytecode or assembly language, depending upon the options. + + Unless the B<-S> option is specified, B will use the + L program to perform some optimizations and create an + LLVM bytecode file. Unless the B<-c> option is specified, B + will also use the L program to perform further + optimizations and link the resulting bytecode file(s) with support + libraries to create an executable program. + + Being derived from the GNU Compiler Collection, B has many + of gcc's features and accepts most of gcc's options. It handles a + number of gcc's extensions to the C programming language. + + =head1 OPTIONS + + =over + + =item B<--help> + + Print a summary of command line options. + + =item B<-S> + + Do not generate an LLVM bytecode file. Rather, compile the source + file into an LLVM assembly language file. + + =item B<-c> + + Do not generate a linked executable. Rather, compile the source + file into an LLVM bytecode file. This bytecode file can then be + linked with other bytecode files later on to generate a full LLVM + executable. + + =item B<-o> I + + Specify the output file to be I. + + =item B<-I> I + + Add a directory to the header file search path. This option can be + repeated. + + =item B<-L> I + + Add I to the library search path. This option can be + repeated. + + =item B<-l>I + + Link in the library libI.[bc | a | so]. This library should + be a bytecode library. + + =item B<-Wa,>I @@ -68,22 +68,22 @@
  3. LLVM source code (4.5M)
  4. LLVM Test Suite (11.3M)
  5. -
  6. GCC 3.4 Front End +
  7. LLVM-GCC 3.4 Front End Binaries for Linux/x86 (6.1M)
  8. -
  9. GCC 3.4 Front End +
  10. LLVM-GCC 3.4 Front End Binaries for MacOS X/PowerPC (6.3M)
  11. -
  12. GCC 3.4 Front End Source Code +
  13. LLVM-GCC 3.4 Front End Source Code (28.9M)
  14. -
  15. GCC 4 Front End +
  16. LLVM-GCC 4 Front End Binaries for MacOS X/x86 (53.3M)
  17. -
  18. GCC 4 Front End +
  19. LLVM-GCC 4 Front End Binaries for MacOS X/PowerPC (52.4M)
  20. -
  21. GCC 4 Front End +
  22. LLVM-GCC 4 Front End Source Code (43.6M)
  23. @@ -106,16 +106,16 @@
  24. LLVM Test Suite (9.6M)
  25. -
  26. GCC Front End +
  27. LLVM-GCC Front End Binaries for Linux/x86 (6.2M)
  28. -
  29. GCC Front End +
  30. LLVM-GCC Front End Binaries for Solaris/Sparc (6.7M)
  31. -
  32. GCC Front End +
  33. LLVM-GCC Front End Binaries for MacOS X/PowerPC (6.4M)
  34. -
  35. GCC Front End Source Code +
  36. LLVM-GCC Front End Source Code (28.9M)
  37. @@ -135,16 +135,16 @@
  38. LLVM Test Suite (9.6M)
  39. -
  40. GCC Front End +
  41. LLVM-GCC Front End Binaries for Linux/x86 (6.2M)
  42. -
  43. GCC Front End +
  44. LLVM-GCC Front End Binaries for Solaris/Sparc (6.6M)
  45. -
  46. GCC Front End +
  47. LLVM-GCC Front End Binaries for MacOS X/PowerPC (6.7M)
  48. -
  49. GCC Front End Source Code +
  50. LLVM-GCC Front End Source Code (29.0M)
  51. @@ -165,16 +165,16 @@
  52. LLVM Test Suite (8.0M)
  53. -
  54. GCC Front End +
  55. LLVM-GCC Front End Binaries for Linux/x86 (6.2M)
  56. -
  57. GCC Front End +
  58. LLVM-GCC Front End Binaries for Solaris/Sparc (6.6M)
  59. -
  60. GCC Front End +
  61. LLVM-GCC Front End Binaries for MacOS X/PowerPC (7.0M)
  62. -
  63. GCC Front End Source Code +
  64. LLVM-GCC Front End Source Code (30.0M)
  65. @@ -192,23 +192,23 @@

    Contributed by users:

    @@ -226,16 +226,16 @@ @@ -253,19 +253,19 @@ @@ -283,16 +283,16 @@ From tbrethou at cs.uiuc.edu Wed Aug 9 01:03:46 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 01:03:46 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/index.html Message-ID: <200608090603.k7963kAV026614@zion.cs.uiuc.edu> Changes in directory llvm-www/releases: index.html updated: 1.28 -> 1.29 --- Log message: Adding 1.8 release --- Diffs of the changes: (+3 -0) index.html | 3 +++ 1 files changed, 3 insertions(+) Index: llvm-www/releases/index.html diff -u llvm-www/releases/index.html:1.28 llvm-www/releases/index.html:1.29 --- llvm-www/releases/index.html:1.28 Thu Apr 20 02:20:49 2006 +++ llvm-www/releases/index.html Wed Aug 9 01:03:33 2006 @@ -39,6 +39,8 @@
    • Always - Anonymous CVS access; release notes.
    • +
    • 9 Aug 2006 - 1.8 release download; release notes.
    • 20 Apr 2006 - 1.7 release download; release notes.
    • 08 Nov 2005 - 1.6 release download;
    • Current LLVM documentation
    • +
    • Documentation for LLVM 1.8
    • Documentation for LLVM 1.7
    • Documentation for LLVM 1.6
    • Documentation for LLVM 1.5
    • From tbrethou at cs.uiuc.edu Wed Aug 9 01:06:24 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 01:06:24 -0500 Subject: [llvm-commits] CVS: llvm-www/www-index.html Message-ID: <200608090606.k7966OOa026681@zion.cs.uiuc.edu> Changes in directory llvm-www: www-index.html updated: 1.128 -> 1.129 --- Log message: 1.8 release --- Diffs of the changes: (+2 -2) www-index.html | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-) Index: llvm-www/www-index.html diff -u llvm-www/www-index.html:1.128 llvm-www/www-index.html:1.129 --- llvm-www/www-index.html:1.128 Thu Apr 27 18:10:40 2006 +++ llvm-www/www-index.html Wed Aug 9 01:06:12 2006 @@ -102,9 +102,9 @@
      Latest LLVM Release!
      -

      April 20, 2006: LLVM 1.7 is now available +

      August 9, 2006: LLVM 1.8 is now available for download! LLVM is publicly available under an open source License. Also, you might want to + href="releases/1.8/LICENSE.TXT">License. Also, you might want to check out the new features in CVS that will appear in the next LLVM release. If you want them early, download LLVM through From tbrethou at cs.uiuc.edu Wed Aug 9 01:15:20 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 01:15:20 -0500 Subject: [llvm-commits] CVS: llvm-www/header.incl Message-ID: <200608090615.k796FKWU026907@zion.cs.uiuc.edu> Changes in directory llvm-www: header.incl updated: 1.47 -> 1.48 --- Log message: Adding 1.8 release --- Diffs of the changes: (+1 -0) header.incl | 1 + 1 files changed, 1 insertion(+) Index: llvm-www/header.incl diff -u llvm-www/header.incl:1.47 llvm-www/header.incl:1.48 --- llvm-www/header.incl:1.47 Wed Jul 19 12:51:33 2006 +++ llvm-www/header.incl Wed Aug 9 01:15:08 2006 @@ -65,6 +65,7 @@ Status Updates

      + Aug 9, 2006
      Apr 20, 2006
      Nov 8, 2005
      May 18, 2005
      From lattner at cs.uiuc.edu Wed Aug 9 01:19:17 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Wed, 9 Aug 2006 01:19:17 -0500 Subject: [llvm-commits] CVS: llvm-www/header.incl Message-ID: <200608090619.k796JHh3027045@zion.cs.uiuc.edu> Changes in directory llvm-www: header.incl updated: 1.48 -> 1.49 --- Log message: Version bump --- Diffs of the changes: (+2 -2) header.incl | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-) Index: llvm-www/header.incl diff -u llvm-www/header.incl:1.48 llvm-www/header.incl:1.49 --- llvm-www/header.incl:1.48 Wed Aug 9 01:15:08 2006 +++ llvm-www/header.incl Wed Aug 9 01:19:03 2006 @@ -37,7 +37,7 @@ Download!
      Download now: -LLVM 1.7
      +LLVM 1.8

      Try the
      @@ -45,7 +45,7 @@
      View the open-source
      -license +license

      From rafael.espindola at gmail.com Wed Aug 9 08:16:06 2006 From: rafael.espindola at gmail.com (Rafael Espindola) Date: Wed, 9 Aug 2006 08:16:06 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/ARM/ARMRegisterInfo.cpp Message-ID: <200608091316.k79DG6E2017015@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/ARM: ARMRegisterInfo.cpp updated: 1.11 -> 1.12 --- Log message: fix the loading of the link register in emitepilogue --- Diffs of the changes: (+3 -1) ARMRegisterInfo.cpp | 4 +++- 1 files changed, 3 insertions(+), 1 deletion(-) Index: llvm/lib/Target/ARM/ARMRegisterInfo.cpp diff -u llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.11 llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.12 --- llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.11 Tue Aug 8 15:35:03 2006 +++ llvm/lib/Target/ARM/ARMRegisterInfo.cpp Wed Aug 9 08:15:47 2006 @@ -129,6 +129,8 @@ // entry to the current function. This eliminates the need for add/sub // brackets around call sites. NumBytes += MFI->getMaxCallFrameSize(); + } else { + NumBytes += 4; } MFI->setStackSize(NumBytes); @@ -149,7 +151,7 @@ int NumBytes = (int) MFI->getStackSize(); //ldr lr, [sp] - BuildMI(MBB, MBBI, ARM::ldr, 2, ARM::R14).addImm(0).addReg(ARM::R13); + BuildMI(MBB, MBBI, ARM::ldr, 2, ARM::R14).addImm(NumBytes - 4).addReg(ARM::R13); //add sp, sp, #NumBytes BuildMI(MBB, MBBI, ARM::addri, 2, ARM::R13).addReg(ARM::R13).addImm(NumBytes); } From rspencer at reidspencer.com Wed Aug 9 11:18:33 2006 From: rspencer at reidspencer.com (Reid Spencer) Date: Wed, 09 Aug 2006 09:18:33 -0700 Subject: [llvm-commits] CVS: llvm/autoconf/m4/libtool.m4 In-Reply-To: <200608090539.k795d8ND025661@zion.cs.uiuc.edu> References: <200608090539.k795d8ND025661@zion.cs.uiuc.edu> Message-ID: <1155140313.2707.346.camel@bashful.x10sys.com> Could you please make a note of this in the autoconf/README.TXT file. These deviations from the standard libtool need to be documented so they can be applied in the next update of libtool. Thanks, Reid. On Wed, 2006-08-09 at 00:39 -0500, Evan Cheng wrote: > > Changes in directory llvm/autoconf/m4: > > libtool.m4 updated: 1.7 -> 1.8 > --- > Log message: > > Recover the lost diff between 1.5 and 1.6. > > --- > Diffs of the changes: (+1 -1) > > libtool.m4 | 2 +- > 1 files changed, 1 insertion(+), 1 deletion(-) > > > Index: llvm/autoconf/m4/libtool.m4 > diff -u llvm/autoconf/m4/libtool.m4:1.7 llvm/autoconf/m4/libtool.m4:1.8 > --- llvm/autoconf/m4/libtool.m4:1.7 Fri Aug 4 13:18:08 2006 > +++ llvm/autoconf/m4/libtool.m4 Wed Aug 9 00:38:51 2006 > @@ -2234,7 +2234,7 @@ > case $host_os in > darwin*) > if test "$GCC" = yes; then > - reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' > + reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r $compiler_flags -o $output$reload_objs' > else > reload_cmds='$LD$reload_flag -o $output$reload_objs' > fi > > > > _______________________________________________ > llvm-commits mailing list > llvm-commits at cs.uiuc.edu > http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits From tbrethou at cs.uiuc.edu Wed Aug 9 11:24:26 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 11:24:26 -0500 Subject: [llvm-commits] [release_18] CVS: llvm/utils/TableGen/DAGISelEmitter.cpp Message-ID: <200608091624.k79GOQSx023420@zion.cs.uiuc.edu> Changes in directory llvm/utils/TableGen: DAGISelEmitter.cpp updated: 1.226 -> 1.226.2.1 --- Log message: Merging in from mainline --- Diffs of the changes: (+398 -503) DAGISelEmitter.cpp | 901 +++++++++++++++++++++++------------------------------ 1 files changed, 398 insertions(+), 503 deletions(-) Index: llvm/utils/TableGen/DAGISelEmitter.cpp diff -u llvm/utils/TableGen/DAGISelEmitter.cpp:1.226 llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.1 --- llvm/utils/TableGen/DAGISelEmitter.cpp:1.226 Wed Jul 26 18:06:27 2006 +++ llvm/utils/TableGen/DAGISelEmitter.cpp Wed Aug 9 11:24:13 2006 @@ -1829,9 +1829,22 @@ // If this node is commutative, consider the commuted order. if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) { assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!"); + // Don't count children which are actually register references. + unsigned NC = 0; + for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) { + TreePatternNode *Child = N->getChild(i); + if (Child->isLeaf()) + if (DefInit *DI = dynamic_cast(Child->getLeafValue())) { + Record *RR = DI->getDef(); + if (RR->isSubClassOf("Register")) + continue; + } + NC++; + } // Consider the commuted order. - CombineChildVariants(N, ChildVariants[1], ChildVariants[0], - OutVariants, ISE); + if (NC == 2) + CombineChildVariants(N, ChildVariants[1], ChildVariants[0], + OutVariants, ISE); } } @@ -2106,8 +2119,6 @@ // Names of all the folded nodes which produce chains. std::vector > FoldedChains; std::set Duplicates; - /// These nodes are being marked "in-flight" so they cannot be folded. - std::vector InflightNodes; /// GeneratedCode - This is the buffer that we emit code to. The first bool /// indicates whether this is an exit predicate (something that should be @@ -2123,7 +2134,6 @@ std::vector &TargetVTs; std::string ChainName; - bool DoReplace; unsigned TmpNo; unsigned OpcNo; unsigned VTNo; @@ -2154,11 +2164,10 @@ std::vector > &gc, std::set > &gd, std::vector &to, - std::vector &tv, - bool dorep) + std::vector &tv) : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr), GeneratedCode(gc), GeneratedDecl(gd), TargetOpcodes(to), TargetVTs(tv), - DoReplace(dorep), TmpNo(0), OpcNo(0), VTNo(0) {} + TmpNo(0), OpcNo(0), VTNo(0) {} /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo /// if the match fails. At this point, we already know that the opcode for N @@ -2225,24 +2234,14 @@ bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE); bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE); bool EmittedUseCheck = false; - bool EmittedSlctedCheck = false; if (HasChain) { if (NodeHasChain) OpNo = 1; if (!isRoot) { const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator()); - // Not in flight? - emitCheck("InFlightSet.count(" + RootName + ".Val) == 0"); // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); EmittedUseCheck = true; - // hasOneUse() check is not strong enough. If the original node has - // already been selected, it may have been replaced with another. - for (unsigned j = 0; j != CInfo.getNumResults(); j++) - emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + - "))"); - - EmittedSlctedCheck = true; if (NodeHasChain) { // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node // has a chain use. @@ -2280,14 +2279,8 @@ PInfo.hasProperty(SDNodeInfo::SDNPHasChain) || PInfo.hasProperty(SDNodeInfo::SDNPInFlag) || PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag)) - if (PInfo.getNumOperands() > 1) { - emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName + - ".Val)"); - } else { - emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" + - "isNonImmUse(" + ParentName + ".Val, " + RootName + - ".Val))"); - } + emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName + + ".Val)"); } } @@ -2317,12 +2310,6 @@ // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); } - if (!EmittedSlctedCheck) - // hasOneUse() check is not strong enough. If the original node has - // already been selected, it may have been replaced with another. - for (unsigned j = 0; j < CInfo.getNumResults(); j++) - emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + - "))"); } for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) { @@ -2479,30 +2466,14 @@ for (unsigned i = 0; i < NumRes; ++i) emitDecl("CPTmp" + utostr(i+ResNo)); - std::string Code = "bool Match = " + Fn + "(" + Val; + std::string Code = Fn + "(" + Val; for (unsigned i = 0; i < NumRes; i++) Code += ", CPTmp" + utostr(i + ResNo); - emitCode(Code + ");"); - if (InflightNodes.size()) { - // Remove the in-flight nodes if the ComplexPattern does not match! - emitCode("if (!Match) {"); - for (std::vector::iterator AI = InflightNodes.begin(), - AE = InflightNodes.end(); AI != AE; ++AI) - emitCode(" SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " + - *AI + ".Val);"); - emitCode("}"); - } + emitCheck(Code + ")"); - emitCheck("Match"); - - for (unsigned i = 0; i < NumRes; ++i) { - emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, CPTmp" + - utostr(i+ResNo) + ".Val);"); - InflightNodes.push_back("CPTmp" + utostr(i+ResNo)); - } for (unsigned i = 0; i < NumRes; ++i) { emitDecl("Tmp" + utostr(i+ResNo)); - emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" + + emitCode("AddToQueue(Tmp" + utostr(i+ResNo) + ", CPTmp" + utostr(i+ResNo) + ");"); } @@ -2514,12 +2485,12 @@ if (LikeLeaf) emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";"); else { - emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");"); - } - - if (isRoot && N->isLeaf()) { - emitCode("Result = Tmp" + utostr(ResNo) + ";"); - emitCode("return;"); + emitCode("AddToQueue(Tmp" + utostr(ResNo) + ", " + Val + ");"); + if (isRoot && N->isLeaf()) { + emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); + emitCode("Result = Tmp" + utostr(ResNo) + ";"); + emitCode("return;"); + } } } // Add Tmp to VariableMap, so that we don't multiply select this @@ -2614,22 +2585,6 @@ } } - // Make sure these operands which would be selected won't be folded while - // the isel traverses the DAG upward. - for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) { - TreePatternNode *Child = EmitOrder[i].second; - if (!Child->getName().empty()) { - std::string &Val = VariableMap[Child->getName()]; - assert(!Val.empty() && - "Variable referenced but not defined and not caught earlier!"); - if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) { - emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, " + - Val + ".Val);"); - InflightNodes.push_back(Val); - } - } - } - // Emit all of the operands. std::vector > NumTemps(EmitOrder.size()); for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) { @@ -2649,20 +2604,12 @@ // Emit all the chain and CopyToReg stuff. bool ChainEmitted = NodeHasChain; if (NodeHasChain) - emitCode("Select(" + ChainName + ", " + ChainName + ");"); + emitCode("AddToQueue(" + ChainName + ", " + ChainName + ");"); if (NodeHasInFlag || HasImpInputs) EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true); if (NodeHasOptInFlag) { emitCode("if (HasInFlag)"); - emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));"); - } - - if (isRoot) { - // The operands have been selected. Remove them from InFlightSet. - for (std::vector::iterator AI = InflightNodes.begin(), - AE = InflightNodes.end(); AI != AE; ++AI) - emitCode("SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " + - *AI + ".Val);"); + emitCode(" AddToQueue(InFlag, N.getOperand(N.getNumOperands()-1));"); } unsigned NumResults = Inst.getNumResults(); @@ -2714,7 +2661,7 @@ emitCode("for (unsigned i = 2, e = N.getNumOperands(); " "i != e; ++i) {"); emitCode(" SDOperand VarOp(0, 0);"); - emitCode(" Select(VarOp, N.getOperand(i));"); + emitCode(" AddToQueue(VarOp, N.getOperand(i));"); emitCode(" Ops.push_back(VarOp);"); emitCode("}"); } @@ -2736,7 +2683,7 @@ } if (HasVarOps) - Code += ", Ops"; + Code += ", &Ops[0], Ops.size()"; else if (NodeHasOptInFlag) Code = "HasInFlag ? " + Code + ", InFlag) : " + Code; @@ -2757,50 +2704,35 @@ return std::make_pair(1, ResNo); for (unsigned i = 0; i < NumResults; i++) - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + - utostr(i) + ", ResNode, " + utostr(i) + ");"); + emitCode("ReplaceUses(SDOperand(N.Val, " + + utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));"); if (NodeHasOutFlag) emitCode("InFlag = SDOperand(ResNode, " + utostr(NumResults + (unsigned)NodeHasChain) + ");"); if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) { - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " - "0, ResNode, 0);"); + emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));"); NumResults = 1; } - if (InputHasChain) { - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + - utostr(PatResults) + ", " + ChainName + ".Val, " + - ChainName + ".ResNo" + ");"); - if (DoReplace) - emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " + - utostr(PatResults) + ", " + ChainName + ".Val, " + - ChainName + ".ResNo" + ");"); - } + if (InputHasChain) + emitCode("ReplaceUses(SDOperand(N.Val, " + + utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, " + + ChainName + ".ResNo" + "));"); if (FoldedChains.size() > 0) { std::string Code; for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " + + emitCode("ReplaceUses(SDOperand(" + FoldedChains[j].first + ".Val, " + - utostr(FoldedChains[j].second) + ", ResNode, " + - utostr(NumResults) + ");"); - - for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) { - std::string Code = - FoldedChains[j].first + ".Val, " + - utostr(FoldedChains[j].second) + ", "; - emitCode("AddHandleReplacement(" + Code + "ResNode, " + - utostr(NumResults) + ");"); - } + utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " + + utostr(NumResults) + "));"); } if (NodeHasOutFlag) - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + - utostr(PatResults + (unsigned)InputHasChain) + - ", InFlag.Val, InFlag.ResNo);"); + emitCode("ReplaceUses(SDOperand(N.Val, " + + utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);"); // User does not expect the instruction would produce a chain! bool AddedChain = NodeHasChain && !InputHasChain; @@ -2857,8 +2789,7 @@ if (NodeHasInFlag || HasImpInputs) Code += ", InFlag"; emitCode(Code + ");"); - emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo" - ", ResNode, 0);"); + emitCode(" ReplaceUses(N, SDOperand(ResNode, 0));"); emitCode(" Result = SDOperand(ResNode, 0);"); emitCode("}"); } @@ -2876,9 +2807,7 @@ emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName() + "(Tmp" + utostr(OpVal) + ".Val);"); if (isRoot) { - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val," - "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" + - utostr(ResNo) + ".ResNo);"); + emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); emitCode("Result = Tmp" + utostr(ResNo) + ";"); emitCode("return;"); } @@ -2895,13 +2824,15 @@ /// 'Pat' may be missing types. If we find an unresolved type to add a check /// for, this returns true otherwise false if Pat has all types. bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other, - const std::string &Prefix) { + const std::string &Prefix, bool isRoot = false) { // Did we find one? if (Pat->getExtTypes() != Other->getExtTypes()) { // Move a type over from 'other' to 'pat'. Pat->setTypes(Other->getExtTypes()); - emitCheck(Prefix + ".Val->getValueType(0) == " + - getName(Pat->getTypeNum(0))); + // The top level node type is checked outside of the select function. + if (!isRoot) + emitCheck(Prefix + ".Val->getValueType(0) == " + + getName(Pat->getTypeNum(0))); return true; } @@ -2940,7 +2871,7 @@ if (RR->isSubClassOf("Register")) { MVT::ValueType RVT = getRegisterValueType(RR, T); if (RVT == MVT::Flag) { - emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");"); + emitCode("AddToQueue(InFlag, " + RootName + utostr(OpNo) + ");"); } else { if (!ChainEmitted) { emitDecl("Chain"); @@ -2948,7 +2879,7 @@ ChainName = "Chain"; ChainEmitted = true; } - emitCode("Select(" + RootName + utostr(OpNo) + ", " + + emitCode("AddToQueue(" + RootName + utostr(OpNo) + ", " + RootName + utostr(OpNo) + ");"); emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName + ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) + @@ -2963,7 +2894,7 @@ } if (HasInFlag) - emitCode("Select(InFlag, " + RootName + + emitCode("AddToQueue(InFlag, " + RootName + ".getOperand(" + utostr(OpNo) + "));"); } @@ -3009,13 +2940,11 @@ std::vector > &GeneratedCode, std::set > &GeneratedDecl, std::vector &TargetOpcodes, - std::vector &TargetVTs, - bool DoReplace) { + std::vector &TargetVTs) { PatternCodeEmitter Emitter(*this, Pattern.getPredicates(), Pattern.getSrcPattern(), Pattern.getDstPattern(), GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs, - DoReplace); + TargetOpcodes, TargetVTs); // Emit the matcher, capturing named arguments in VariableMap. bool FoundChain = false; @@ -3055,7 +2984,7 @@ // Insert a check for an unresolved type and add it to the tree. If we find // an unresolved type to add a check for, this returns true and we iterate, // otherwise we are done. - } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N")); + } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true)); Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/); delete Pat; @@ -3142,7 +3071,9 @@ OS << std::string(Indent, ' ') << "// Pattern complexity = " << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity << " cost = " - << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n"; + << getResultPatternCost(Pattern.getDstPattern(), *this) + << " size = " + << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n"; } EmitPatterns(Other, Indent, OS); return; @@ -3240,7 +3171,12 @@ } } } - + + // For each opcode, there might be multiple select functions, one per + // ValueType of the node (or its first operand if it doesn't produce a + // non-chain result. + std::map > OpcodeVTMap; + // Emit one Select_* method for each top-level opcode. We do this instead of // emitting one giant switch statement to support compilers where this will // result in the recursive functions taking less stack space. @@ -3249,223 +3185,245 @@ E = PatternsByOpcode.end(); PBOI != E; ++PBOI) { const std::string &OpName = PBOI->first->getName(); const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first); - bool OptSlctOrder = - (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) && - OpcodeInfo.getNumResults() > 0); - std::vector &Patterns = PBOI->second; - assert(!Patterns.empty() && "No patterns but map has entry?"); - + std::vector &PatternsOfOp = PBOI->second; + assert(!PatternsOfOp.empty() && "No patterns but map has entry?"); + // We want to emit all of the matching code now. However, we want to emit // the matches in order of minimal cost. Sort the patterns so the least // cost one is at the start. - std::stable_sort(Patterns.begin(), Patterns.end(), + std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(), PatternSortingPredicate(*this)); - typedef std::vector > CodeList; - typedef std::vector >::iterator CodeListI; - - std::vector > CodeForPatterns; - std::vector > PatternOpcodes; - std::vector > PatternVTs; - std::vector > > PatternDecls; - std::set > AllGenDecls; - for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { - CodeList GeneratedCode; - std::set > GeneratedDecl; - std::vector TargetOpcodes; - std::vector TargetVTs; - GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs, OptSlctOrder); - for (std::set >::iterator - si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) - AllGenDecls.insert(*si); - CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode)); - PatternDecls.push_back(GeneratedDecl); - PatternOpcodes.push_back(TargetOpcodes); - PatternVTs.push_back(TargetVTs); + // Split them into groups by type. + std::map > PatternsByType; + for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) { + PatternToMatch *Pat = PatternsOfOp[i]; + TreePatternNode *SrcPat = Pat->getSrcPattern(); + if (OpcodeInfo.getNumResults() == 0 && SrcPat->getNumChildren() > 0) + SrcPat = SrcPat->getChild(0); + MVT::ValueType VT = SrcPat->getTypeNum(0); + std::map >::iterator TI = + PatternsByType.find(VT); + if (TI != PatternsByType.end()) + TI->second.push_back(Pat); + else { + std::vector PVec; + PVec.push_back(Pat); + PatternsByType.insert(std::make_pair(VT, PVec)); + } } + + for (std::map >::iterator + II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE; + ++II) { + MVT::ValueType OpVT = II->first; + std::vector &Patterns = II->second; + typedef std::vector > CodeList; + typedef std::vector >::iterator CodeListI; - // Scan the code to see if all of the patterns are reachable and if it is - // possible that the last one might not match. - bool mightNotMatch = true; - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - mightNotMatch = false; - - for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) { - if (GeneratedCode[j].first) { // predicate. - mightNotMatch = true; - break; - } + std::vector > CodeForPatterns; + std::vector > PatternOpcodes; + std::vector > PatternVTs; + std::vector > > PatternDecls; + std::set > AllGenDecls; + for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { + CodeList GeneratedCode; + std::set > GeneratedDecl; + std::vector TargetOpcodes; + std::vector TargetVTs; + GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, + TargetOpcodes, TargetVTs); + for (std::set >::iterator + si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) + AllGenDecls.insert(*si); + CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode)); + PatternDecls.push_back(GeneratedDecl); + PatternOpcodes.push_back(TargetOpcodes); + PatternVTs.push_back(TargetVTs); } + + // Scan the code to see if all of the patterns are reachable and if it is + // possible that the last one might not match. + bool mightNotMatch = true; + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + mightNotMatch = false; + + for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) { + if (GeneratedCode[j].first) { // predicate. + mightNotMatch = true; + break; + } + } - // If this pattern definitely matches, and if it isn't the last one, the - // patterns after it CANNOT ever match. Error out. - if (mightNotMatch == false && i != CodeForPatterns.size()-1) { - std::cerr << "Pattern '"; - CodeForPatterns[i+1].first->getSrcPattern()->print(OS); - std::cerr << "' is impossible to select!\n"; - exit(1); - } - } - - // Factor target node emission code (emitted by EmitResultCode) into - // separate functions. Uniquing and share them among all instruction - // selection routines. - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - std::vector &TargetOpcodes = PatternOpcodes[i]; - std::vector &TargetVTs = PatternVTs[i]; - std::set > Decls = PatternDecls[i]; - int CodeSize = (int)GeneratedCode.size(); - int LastPred = -1; - for (int j = CodeSize-1; j >= 0; --j) { - if (GeneratedCode[j].first) { - LastPred = j; - break; + // If this pattern definitely matches, and if it isn't the last one, the + // patterns after it CANNOT ever match. Error out. + if (mightNotMatch == false && i != CodeForPatterns.size()-1) { + std::cerr << "Pattern '"; + CodeForPatterns[i+1].first->getSrcPattern()->print(std::cerr); + std::cerr << "' is impossible to select!\n"; + exit(1); } } - std::string CalleeDecls; - std::string CalleeCode = "(SDOperand &Result, SDOperand &N"; - std::string CallerCode = "(Result, N"; - for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) { - CalleeCode += ", unsigned Opc" + utostr(j); - CallerCode += ", " + TargetOpcodes[j]; - } - for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) { - CalleeCode += ", MVT::ValueType VT" + utostr(j); - CallerCode += ", " + TargetVTs[j]; - } - for (std::set >::iterator - I = Decls.begin(), E = Decls.end(); I != E; ++I) { - std::string Name = I->second; - if (I->first == 0) { - if (Name == "InFlag" || - (Name.size() > 3 && - Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) { - CalleeDecls += " SDOperand " + Name + "(0, 0);\n"; - continue; + // Factor target node emission code (emitted by EmitResultCode) into + // separate functions. Uniquing and share them among all instruction + // selection routines. + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + std::vector &TargetOpcodes = PatternOpcodes[i]; + std::vector &TargetVTs = PatternVTs[i]; + std::set > Decls = PatternDecls[i]; + int CodeSize = (int)GeneratedCode.size(); + int LastPred = -1; + for (int j = CodeSize-1; j >= 0; --j) { + if (GeneratedCode[j].first) { + LastPred = j; + break; } - CalleeCode += ", SDOperand &" + Name; - CallerCode += ", " + Name; - } else if (I->first == 1) { - if (Name == "ResNode") { - CalleeDecls += " SDNode *" + Name + " = NULL;\n"; - continue; + } + + std::string CalleeDecls; + std::string CalleeCode = "(SDOperand &Result, const SDOperand &N"; + std::string CallerCode = "(Result, N"; + for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) { + CalleeCode += ", unsigned Opc" + utostr(j); + CallerCode += ", " + TargetOpcodes[j]; + } + for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) { + CalleeCode += ", MVT::ValueType VT" + utostr(j); + CallerCode += ", " + TargetVTs[j]; + } + for (std::set >::iterator + I = Decls.begin(), E = Decls.end(); I != E; ++I) { + std::string Name = I->second; + if (I->first == 0) { + if (Name == "InFlag" || + (Name.size() > 3 && + Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) { + CalleeDecls += " SDOperand " + Name + "(0, 0);\n"; + continue; + } + CalleeCode += ", SDOperand &" + Name; + CallerCode += ", " + Name; + } else if (I->first == 1) { + if (Name == "ResNode") { + CalleeDecls += " SDNode *" + Name + " = NULL;\n"; + continue; + } + CalleeCode += ", SDNode *" + Name; + CallerCode += ", " + Name; + } else { + CalleeCode += ", bool " + Name; + CallerCode += ", " + Name; } - CalleeCode += ", SDNode *" + Name; - CallerCode += ", " + Name; - } else { - CalleeCode += ", bool " + Name; - CallerCode += ", " + Name; } - } - CallerCode += ");"; - CalleeCode += ") "; - // Prevent emission routines from being inlined to reduce selection - // routines stack frame sizes. - CalleeCode += "NOINLINE "; - CalleeCode += "{\n" + CalleeDecls; - for (int j = LastPred+1; j < CodeSize; ++j) - CalleeCode += " " + GeneratedCode[j].second + '\n'; - for (int j = LastPred+1; j < CodeSize; ++j) - GeneratedCode.pop_back(); - CalleeCode += "}\n"; - - // Uniquing the emission routines. - unsigned EmitFuncNum; - std::map::iterator EFI = - EmitFunctions.find(CalleeCode); - if (EFI != EmitFunctions.end()) { - EmitFuncNum = EFI->second; - } else { - EmitFuncNum = EmitFunctions.size(); - EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum)); - OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode; - } - - // Replace the emission code within selection routines with calls to the - // emission functions. - CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode; - GeneratedCode.push_back(std::make_pair(false, CallerCode)); - GeneratedCode.push_back(std::make_pair(false, "return;")); - } - - // Print function. - OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n"; - if (OptSlctOrder) { - OS << " if (N.ResNo == " << OpcodeInfo.getNumResults() - << " && N.getValue(0).hasOneUse()) {\n" - << " SDOperand Dummy = " - << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " - << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, " - << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" - << " Result = Dummy;\n" - << " return;\n" - << " }\n"; - } - - // Print all declarations. - for (std::set >::iterator - I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I) - if (I->first == 0) - OS << " SDOperand " << I->second << "(0, 0);\n"; - else if (I->first == 1) - OS << " SDNode *" << I->second << " = NULL;\n"; - else - OS << " bool " << I->second << " = false;\n"; + CallerCode += ");"; + CalleeCode += ") "; + // Prevent emission routines from being inlined to reduce selection + // routines stack frame sizes. + CalleeCode += "NOINLINE "; + CalleeCode += "{\n" + CalleeDecls; + for (int j = LastPred+1; j < CodeSize; ++j) + CalleeCode += " " + GeneratedCode[j].second + '\n'; + for (int j = LastPred+1; j < CodeSize; ++j) + GeneratedCode.pop_back(); + CalleeCode += "}\n"; + + // Uniquing the emission routines. + unsigned EmitFuncNum; + std::map::iterator EFI = + EmitFunctions.find(CalleeCode); + if (EFI != EmitFunctions.end()) { + EmitFuncNum = EFI->second; + } else { + EmitFuncNum = EmitFunctions.size(); + EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum)); + OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode; + } + + // Replace the emission code within selection routines with calls to the + // emission functions. + CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode; + GeneratedCode.push_back(std::make_pair(false, CallerCode)); + GeneratedCode.push_back(std::make_pair(false, "return;")); + } + + // Print function. + std::string OpVTStr = (OpVT != MVT::isVoid && OpVT != MVT::iPTR) + ? getEnumName(OpVT).substr(5) : "" ; + std::map >::iterator OpVTI = + OpcodeVTMap.find(OpName); + if (OpVTI == OpcodeVTMap.end()) { + std::vector VTSet; + VTSet.push_back(OpVTStr); + OpcodeVTMap.insert(std::make_pair(OpName, VTSet)); + } else + OpVTI->second.push_back(OpVTStr); - // Loop through and reverse all of the CodeList vectors, as we will be - // accessing them from their logical front, but accessing the end of a - // vector is more efficient. - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - std::reverse(GeneratedCode.begin(), GeneratedCode.end()); - } + OS << "void Select_" << OpName << (OpVTStr != "" ? "_" : "") + << OpVTStr << "(SDOperand &Result, const SDOperand &N) {\n"; + + // Print all declarations. + for (std::set >::iterator + I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I) + if (I->first == 0) + OS << " SDOperand " << I->second << "(0, 0);\n"; + else if (I->first == 1) + OS << " SDNode *" << I->second << " = NULL;\n"; + else + OS << " bool " << I->second << " = false;\n"; + + // Loop through and reverse all of the CodeList vectors, as we will be + // accessing them from their logical front, but accessing the end of a + // vector is more efficient. + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + std::reverse(GeneratedCode.begin(), GeneratedCode.end()); + } - // Next, reverse the list of patterns itself for the same reason. - std::reverse(CodeForPatterns.begin(), CodeForPatterns.end()); + // Next, reverse the list of patterns itself for the same reason. + std::reverse(CodeForPatterns.begin(), CodeForPatterns.end()); - // Emit all of the patterns now, grouped together to share code. - EmitPatterns(CodeForPatterns, 2, OS); + // Emit all of the patterns now, grouped together to share code. + EmitPatterns(CodeForPatterns, 2, OS); - // If the last pattern has predicates (which could fail) emit code to catch - // the case where nothing handles a pattern. - if (mightNotMatch) { - OS << " std::cerr << \"Cannot yet select: \";\n"; - if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" && - OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" && - OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") { - OS << " N.Val->dump(CurDAG);\n"; - } else { - OS << " unsigned iid = cast(N.getOperand(" - "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n" - << " std::cerr << \"intrinsic %\"<< " - "Intrinsic::getName((Intrinsic::ID)iid);\n"; + // If the last pattern has predicates (which could fail) emit code to catch + // the case where nothing handles a pattern. + if (mightNotMatch) { + OS << " std::cerr << \"Cannot yet select: \";\n"; + if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" && + OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" && + OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") { + OS << " N.Val->dump(CurDAG);\n"; + } else { + OS << " unsigned iid = cast(N.getOperand(" + "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n" + << " std::cerr << \"intrinsic %\"<< " + "Intrinsic::getName((Intrinsic::ID)iid);\n"; + } + OS << " std::cerr << '\\n';\n" + << " abort();\n"; } - OS << " std::cerr << '\\n';\n" - << " abort();\n"; + OS << "}\n\n"; } - OS << "}\n\n"; } // Emit boilerplate. OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n" << " std::vector Ops(N.Val->op_begin(), N.Val->op_end());\n" - << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n" + << " AddToQueue(Ops[0], N.getOperand(0)); // Select the chain.\n\n" << " // Select the flag operand.\n" << " if (Ops.back().getValueType() == MVT::Flag)\n" - << " Select(Ops.back(), Ops.back());\n" + << " AddToQueue(Ops.back(), Ops.back());\n" << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n" << " std::vector VTs;\n" << " VTs.push_back(MVT::Other);\n" << " VTs.push_back(MVT::Flag);\n" - << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n" + << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], " + "Ops.size());\n" + << " ReplaceUses(SDOperand(N.Val, 0), New);\n" + << " ReplaceUses(SDOperand(N.Val, 1), SDOperand(New.Val, 1));\n" << " Result = New.getValue(N.ResNo);\n" << " return;\n" << "}\n\n"; @@ -3478,11 +3436,6 @@ << " Result = N;\n" << " return; // Already selected.\n" << " }\n\n" - << " std::map::iterator CGMI = CodeGenMap.find(N);\n" - << " if (CGMI != CodeGenMap.end()) {\n" - << " Result = CGMI->second;\n" - << " return;\n" - << " }\n\n" << " switch (N.getOpcode()) {\n" << " default: break;\n" << " case ISD::EntryToken: // These leaves remain the same.\n" @@ -3499,96 +3452,18 @@ << " }\n" << " case ISD::AssertSext:\n" << " case ISD::AssertZext: {\n" - << " SDOperand Tmp0;\n" - << " Select(Tmp0, N.getOperand(0));\n" - << " if (!N.Val->hasOneUse())\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " - << "Tmp0.Val, Tmp0.ResNo);\n" - << " Result = Tmp0;\n" + << " AddToQueue(Result, N.getOperand(0));\n" + << " ReplaceUses(N, Result);\n" << " return;\n" << " }\n" << " case ISD::TokenFactor:\n" - << " if (N.getNumOperands() == 2) {\n" - << " SDOperand Op0, Op1;\n" - << " Select(Op0, N.getOperand(0));\n" - << " Select(Op1, N.getOperand(1));\n" - << " Result = \n" - << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " - << "Result.Val, Result.ResNo);\n" - << " } else {\n" - << " std::vector Ops;\n" - << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" - << " SDOperand Val;\n" - << " Select(Val, N.getOperand(i));\n" - << " Ops.push_back(Val);\n" - << " }\n" - << " Result = \n" - << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " - << "Result.Val, Result.ResNo);\n" - << " }\n" - << " return;\n" - << " case ISD::CopyFromReg: {\n" - << " SDOperand Chain;\n" - << " Select(Chain, N.getOperand(0));\n" - << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" - << " MVT::ValueType VT = N.Val->getValueType(0);\n" - << " if (N.Val->getNumValues() == 2) {\n" - << " if (Chain == N.getOperand(0)) {\n" - << " Result = N; // No change\n" - << " return;\n" - << " }\n" - << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "New.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " - << "New.Val, 1);\n" - << " Result = New.getValue(N.ResNo);\n" - << " return;\n" - << " } else {\n" - << " SDOperand Flag;\n" - << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n" - << " if (Chain == N.getOperand(0) &&\n" - << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n" - << " Result = N; // No change\n" - << " return;\n" - << " }\n" - << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "New.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " - << "New.Val, 1);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, " - << "New.Val, 2);\n" - << " Result = New.getValue(N.ResNo);\n" - << " return;\n" - << " }\n" - << " }\n" + << " case ISD::CopyFromReg:\n" << " case ISD::CopyToReg: {\n" - << " SDOperand Chain;\n" - << " Select(Chain, N.getOperand(0));\n" - << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" - << " SDOperand Val;\n" - << " Select(Val, N.getOperand(2));\n" - << " Result = N;\n" - << " if (N.Val->getNumValues() == 1) {\n" - << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n" - << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "Result.Val, 0);\n" - << " } else {\n" - << " SDOperand Flag(0, 0);\n" - << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n" - << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n" - << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n" - << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "Result.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " - << "Result.Val, 1);\n" - << " Result = Result.getValue(N.ResNo);\n" + << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" + << " SDOperand Dummy;\n" + << " AddToQueue(Dummy, N.getOperand(i));\n" << " }\n" + << " Result = N;\n" << " return;\n" << " }\n" << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n"; @@ -3600,9 +3475,48 @@ CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end(); PBOI != E; ++PBOI) { const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first); - OS << " case " << OpcodeInfo.getEnumName() << ": " - << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ') - << "Select_" << PBOI->first->getName() << "(Result, N); return;\n"; + const std::string &OpName = PBOI->first->getName(); + // Potentially multiple versions of select for this opcode. One for each + // ValueType of the node (or its first true operand if it doesn't produce a + // result. + std::map >::iterator OpVTI = + OpcodeVTMap.find(OpName); + std::vector &OpVTs = OpVTI->second; + OS << " case " << OpcodeInfo.getEnumName() << ": {\n"; + if (OpVTs.size() == 1) { + std::string &VTStr = OpVTs[0]; + OS << " Select_" << OpName + << (VTStr != "" ? "_" : "") << VTStr << "(Result, N);\n"; + } else { + if (OpcodeInfo.getNumResults()) + OS << " MVT::ValueType NVT = N.Val->getValueType(0);\n"; + else if (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain)) + OS << " MVT::ValueType NVT = (N.getNumOperands() > 1) ?" + << " N.getOperand(1).Val->getValueType(0) : MVT::isVoid;\n"; + else + OS << " MVT::ValueType NVT = (N.getNumOperands() > 0) ?" + << " N.getOperand(0).Val->getValueType(0) : MVT::isVoid;\n"; + int ElseCase = -1; + bool First = true; + for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) { + std::string &VTStr = OpVTs[i]; + if (VTStr == "") { + ElseCase = i; + continue; + } + OS << (First ? " if" : " else if") + << " (NVT == MVT::" << VTStr << ")\n" + << " Select_" << OpName + << "_" << VTStr << "(Result, N);\n"; + First = false; + } + if (ElseCase != -1) + OS << " else\n" << " Select_" << OpName << "(Result, N);\n"; + else + OS << " else\n" << " break;\n"; + } + OS << " return;\n"; + OS << " }\n"; } OS << " } // end of big switch.\n\n" @@ -3633,112 +3547,93 @@ OS << "#if defined(__GNUC__) && \\\n"; OS << " ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))\n"; OS << "#define NOINLINE __attribute__((noinline))\n"; + OS << "#else\n"; + OS << "#define NOINLINE\n"; OS << "#endif\n\n"; - OS << "// Instance var to keep track of multiply used nodes that have \n" - << "// already been selected.\n" - << "std::map CodeGenMap;\n"; - - OS << "// Instance var to keep track of mapping of chain generating nodes\n" - << "// and their place handle nodes.\n"; - OS << "std::map HandleMap;\n"; - OS << "// Instance var to keep track of mapping of place handle nodes\n" - << "// and their replacement nodes.\n"; - OS << "std::map ReplaceMap;\n"; - OS << "// Keep track of nodes that are currently being selecte and therefore\n" - << "// should not be folded.\n"; - OS << "std::set InFlightSet;\n"; + OS << "// Instruction selector priority queue:\n" + << "std::vector ISelQueue;\n"; + OS << "/// Keep track of nodes which have already been added to queue.\n" + << "unsigned char *ISelQueued;\n"; + OS << "/// Keep track of nodes which have already been selected.\n" + << "unsigned char *ISelSelected;\n"; + OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n" + << "std::vector ISelKilled;\n\n"; + + OS << "/// Sorting functions for the selection queue.\n" + << "struct isel_sort : public std::binary_function" + << " {\n" + << " bool operator()(const SDNode* left, const SDNode* right) " + << "const {\n" + << " return (left->getNodeId() > right->getNodeId());\n" + << " }\n" + << "};\n\n"; - OS << "\n"; - OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, " - << "std::set &Visited) {\n"; - OS << " if (found || !Visited.insert(Use).second) return;\n"; - OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n"; - OS << " SDNode *N = Use->getOperand(i).Val;\n"; - OS << " if (N != Def) {\n"; - OS << " findNonImmUse(N, Def, found, Visited);\n"; - OS << " } else {\n"; - OS << " found = true;\n"; - OS << " break;\n"; - OS << " }\n"; - OS << " }\n"; + OS << "inline void setQueued(int Id) {\n"; + OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n"; OS << "}\n"; - - OS << "\n"; - OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n"; - OS << " std::set Visited;\n"; - OS << " bool found = false;\n"; - OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n"; - OS << " SDNode *N = Use->getOperand(i).Val;\n"; - OS << " if (N != Def) {\n"; - OS << " findNonImmUse(N, Def, found, Visited);\n"; - OS << " if (found) break;\n"; - OS << " }\n"; - OS << " }\n"; - OS << " return found;\n"; + OS << "inline bool isQueued(int Id) {\n"; + OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n"; OS << "}\n"; - - OS << "\n"; - OS << "// AddHandleReplacement - Note the pending replacement node for a\n" - << "// handle node in ReplaceMap.\n"; - OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, " - << "unsigned RNum) {\n"; - OS << " SDOperand N(H, HNum);\n"; - OS << " std::map::iterator HMI = HandleMap.find(N);\n"; - OS << " if (HMI != HandleMap.end()) {\n"; - OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n"; - OS << " HandleMap.erase(N);\n"; - OS << " }\n"; + OS << "inline void setSelected(int Id) {\n"; + OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n"; OS << "}\n"; - - OS << "\n"; - OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n"; - OS << "// handles.Some handles do not yet have replacements because the\n"; - OS << "// nodes they replacements have only dead readers.\n"; - OS << "void SelectDanglingHandles() {\n"; - OS << " for (std::map::iterator I = " - << "HandleMap.begin(),\n" - << " E = HandleMap.end(); I != E; ++I) {\n"; - OS << " SDOperand N = I->first;\n"; - OS << " SDOperand R;\n"; - OS << " Select(R, N.getValue(0));\n"; - OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n"; + OS << "inline bool isSelected(int Id) {\n"; + OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n"; + OS << "}\n\n"; + + OS << "inline void AddToQueue(SDOperand &Result, SDOperand N) {\n"; + OS << " Result = N;\n"; + OS << " int Id = N.Val->getNodeId();\n"; + OS << " if (Id != -1 && !isQueued(Id)) {\n"; + OS << " ISelQueue.push_back(N.Val);\n"; + OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; + OS << " setQueued(Id);\n"; OS << " }\n"; - OS << "}\n"; - OS << "\n"; - OS << "// ReplaceHandles - Replace all the handles with the real target\n"; - OS << "// specific nodes.\n"; - OS << "void ReplaceHandles() {\n"; - OS << " for (std::map::iterator I = " - << "ReplaceMap.begin(),\n" - << " E = ReplaceMap.end(); I != E; ++I) {\n"; - OS << " SDOperand From = I->first;\n"; - OS << " SDOperand To = I->second;\n"; - OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), " - << "E = From.Val->use_end(); UI != E; ++UI) {\n"; - OS << " SDNode *Use = *UI;\n"; - OS << " std::vector Ops;\n"; - OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n"; - OS << " SDOperand O = Use->getOperand(i);\n"; - OS << " if (O.Val == From.Val)\n"; - OS << " Ops.push_back(To);\n"; - OS << " else\n"; - OS << " Ops.push_back(O);\n"; - OS << " }\n"; - OS << " SDOperand U = SDOperand(Use, 0);\n"; - OS << " CurDAG->UpdateNodeOperands(U, Ops);\n"; - OS << " }\n"; + OS << "}\n\n"; + + OS << "inline void RemoveKilled() {\n"; +OS << " unsigned NumKilled = ISelKilled.size();\n"; + OS << " if (NumKilled) {\n"; + OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n"; + OS << " SDNode *Temp = ISelKilled[i];\n"; + OS << " std::remove(ISelQueue.begin(), ISelQueue.end(), Temp);\n"; + OS << " };\n"; + OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; + OS << " ISelKilled.clear();\n"; OS << " }\n"; - OS << "}\n"; + OS << "}\n\n"; + + OS << "inline void ReplaceUses(SDOperand F, SDOperand T) {\n"; + OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n"; + OS << " setSelected(F.Val->getNodeId());\n"; + OS << " RemoveKilled();\n"; + OS << "}\n\n"; - OS << "\n"; OS << "// SelectRoot - Top level entry to DAG isel.\n"; - OS << "SDOperand SelectRoot(SDOperand N) {\n"; + OS << "SDOperand SelectRoot(SDOperand Root) {\n"; + OS << " SelectRootInit();\n"; + OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n"; + OS << " ISelQueued = new unsigned char[NumBytes];\n"; + OS << " ISelSelected = new unsigned char[NumBytes];\n"; + OS << " memset(ISelQueued, 0, NumBytes);\n"; + OS << " memset(ISelSelected, 0, NumBytes);\n"; + OS << "\n"; OS << " SDOperand ResNode;\n"; - OS << " Select(ResNode, N);\n"; - OS << " SelectDanglingHandles();\n"; - OS << " ReplaceHandles();\n"; - OS << " ReplaceMap.clear();\n"; + OS << " Select(ResNode, Root);\n"; + OS << " while (!ISelQueue.empty()) {\n"; + OS << " SDOperand Tmp;\n"; + OS << " SDNode *Node = ISelQueue.front();\n"; + OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; + OS << " ISelQueue.pop_back();\n"; + OS << " if (!isSelected(Node->getNodeId()))\n"; + OS << " Select(Tmp, SDOperand(Node, 0));\n"; + OS << " }\n"; + OS << "\n"; + OS << " delete[] ISelQueued;\n"; + OS << " ISelQueued = NULL;\n"; + OS << " delete[] ISelSelected;\n"; + OS << " ISelSelected = NULL;\n"; OS << " return ResNode;\n"; OS << "}\n"; From lattner at cs.uiuc.edu Wed Aug 9 11:32:44 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Wed, 9 Aug 2006 11:32:44 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/docs/ReleaseNotes.html Message-ID: <200608091632.k79GWiqL023794@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8/docs: ReleaseNotes.html updated: 1.1 -> 1.2 --- Log message: Updates from the list. --- Diffs of the changes: (+7 -7) ReleaseNotes.html | 14 +++++++------- 1 files changed, 7 insertions(+), 7 deletions(-) Index: llvm-www/releases/1.8/docs/ReleaseNotes.html diff -u llvm-www/releases/1.8/docs/ReleaseNotes.html:1.1 llvm-www/releases/1.8/docs/ReleaseNotes.html:1.2 --- llvm-www/releases/1.8/docs/ReleaseNotes.html:1.1 Wed Aug 9 00:56:40 2006 +++ llvm-www/releases/1.8/docs/ReleaseNotes.html Wed Aug 9 11:32:30 2006 @@ -109,7 +109,7 @@
      -

      The loop optimizer passes now uses "Loop-Closed SSA Form", which makes it +

      The loop optimizer passes now use "Loop-Closed SSA Form", which makes it easier to update SSA form as loop transformations change the code. An immediate benefit of this is that the loop unswitching pass can now unswitch loops in more cases. @@ -168,10 +168,10 @@

    • The PowerPC backend now pattern matches the 'rlwimi' instruction more aggressively.
    • Most of LLVM is now built with "-pedantic", ensuring better portability - to more C++ Compilers.
    • + to more C++ compilers.
    • The PowerPC backend now includes initial 64-bit support. The JIT is not complete, and the static compiler has a couple of known bugs, but support - is mostly in place. LLVM 1.9 will include completed PPC-64 support.
    • + is mostly in place. LLVM 1.9 will include complete PPC-64 support.
    @@ -251,7 +251,7 @@ components, please contact us on the LLVMdev list.

      -
    • The -cee pass is known to be buggy, and may be removed in in a +
    • The -cee pass is known to be buggy, and may be removed in a future release.
    • The IA64 code generator is experimental.
    • The Alpha JIT is experimental.
    • @@ -336,7 +336,7 @@ support for floating point data types of any size other than 32 and 64 bits. -
    • The following Unix system functionality has not been tested and may not +
    • The following Unix system features have not been tested and may not work:
      1. sigsetjmp, siglongjmp - These are not turned into the @@ -537,7 +537,7 @@ problem probably cannot be fixed.
      2. Zero arg vararg functions are not -supported. This should not affect LLVM produced by the C or C++ +supported. This should not affect programs produced by the C or C++ frontends.
      3. The C backend does not correctly implement the The LLVM Compiler Infrastructure
        - Last modified: $Date: 2006/08/09 05:56:40 $ + Last modified: $Date: 2006/08/09 16:32:30 $ From tbrethou at cs.uiuc.edu Wed Aug 9 11:33:27 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 11:33:27 -0500 Subject: [llvm-commits] [release_18] CVS: llvm/utils/TableGen/DAGISelEmitter.cpp Message-ID: <200608091633.k79GXRYF023854@zion.cs.uiuc.edu> Changes in directory llvm/utils/TableGen: DAGISelEmitter.cpp updated: 1.226.2.1 -> 1.226.2.2 --- Log message: Merge in correct version from mainline --- Diffs of the changes: (+246 -127) DAGISelEmitter.cpp | 373 ++++++++++++++++++++++++++++++++++------------------- 1 files changed, 246 insertions(+), 127 deletions(-) Index: llvm/utils/TableGen/DAGISelEmitter.cpp diff -u llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.1 llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.2 --- llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.1 Wed Aug 9 11:24:13 2006 +++ llvm/utils/TableGen/DAGISelEmitter.cpp Wed Aug 9 11:33:15 2006 @@ -2134,6 +2134,7 @@ std::vector &TargetVTs; std::string ChainName; + bool DoReplace; unsigned TmpNo; unsigned OpcNo; unsigned VTNo; @@ -2164,10 +2165,11 @@ std::vector > &gc, std::set > &gd, std::vector &to, - std::vector &tv) + std::vector &tv, + bool dorep) : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr), GeneratedCode(gc), GeneratedDecl(gd), TargetOpcodes(to), TargetVTs(tv), - TmpNo(0), OpcNo(0), VTNo(0) {} + DoReplace(dorep), TmpNo(0), OpcNo(0), VTNo(0) {} /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo /// if the match fails. At this point, we already know that the opcode for N @@ -2234,6 +2236,7 @@ bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE); bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE); bool EmittedUseCheck = false; + bool EmittedSlctedCheck = false; if (HasChain) { if (NodeHasChain) OpNo = 1; @@ -2242,6 +2245,13 @@ // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); EmittedUseCheck = true; + // hasOneUse() check is not strong enough. If the original node has + // already been selected, it may have been replaced with another. + for (unsigned j = 0; j != CInfo.getNumResults(); j++) + emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + + "))"); + + EmittedSlctedCheck = true; if (NodeHasChain) { // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node // has a chain use. @@ -2310,6 +2320,12 @@ // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); } + if (!EmittedSlctedCheck) + // hasOneUse() check is not strong enough. If the original node has + // already been selected, it may have been replaced with another. + for (unsigned j = 0; j < CInfo.getNumResults(); j++) + emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + + "))"); } for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) { @@ -2473,7 +2489,7 @@ for (unsigned i = 0; i < NumRes; ++i) { emitDecl("Tmp" + utostr(i+ResNo)); - emitCode("AddToQueue(Tmp" + utostr(i+ResNo) + ", CPTmp" + + emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" + utostr(i+ResNo) + ");"); } @@ -2485,12 +2501,12 @@ if (LikeLeaf) emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";"); else { - emitCode("AddToQueue(Tmp" + utostr(ResNo) + ", " + Val + ");"); - if (isRoot && N->isLeaf()) { - emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); - emitCode("Result = Tmp" + utostr(ResNo) + ";"); - emitCode("return;"); - } + emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");"); + } + + if (isRoot && N->isLeaf()) { + emitCode("Result = Tmp" + utostr(ResNo) + ";"); + emitCode("return;"); } } // Add Tmp to VariableMap, so that we don't multiply select this @@ -2604,12 +2620,12 @@ // Emit all the chain and CopyToReg stuff. bool ChainEmitted = NodeHasChain; if (NodeHasChain) - emitCode("AddToQueue(" + ChainName + ", " + ChainName + ");"); + emitCode("Select(" + ChainName + ", " + ChainName + ");"); if (NodeHasInFlag || HasImpInputs) EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true); if (NodeHasOptInFlag) { emitCode("if (HasInFlag)"); - emitCode(" AddToQueue(InFlag, N.getOperand(N.getNumOperands()-1));"); + emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));"); } unsigned NumResults = Inst.getNumResults(); @@ -2661,7 +2677,7 @@ emitCode("for (unsigned i = 2, e = N.getNumOperands(); " "i != e; ++i) {"); emitCode(" SDOperand VarOp(0, 0);"); - emitCode(" AddToQueue(VarOp, N.getOperand(i));"); + emitCode(" Select(VarOp, N.getOperand(i));"); emitCode(" Ops.push_back(VarOp);"); emitCode("}"); } @@ -2683,7 +2699,7 @@ } if (HasVarOps) - Code += ", &Ops[0], Ops.size()"; + Code += ", Ops"; else if (NodeHasOptInFlag) Code = "HasInFlag ? " + Code + ", InFlag) : " + Code; @@ -2704,35 +2720,50 @@ return std::make_pair(1, ResNo); for (unsigned i = 0; i < NumResults; i++) - emitCode("ReplaceUses(SDOperand(N.Val, " + - utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));"); + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + + utostr(i) + ", ResNode, " + utostr(i) + ");"); if (NodeHasOutFlag) emitCode("InFlag = SDOperand(ResNode, " + utostr(NumResults + (unsigned)NodeHasChain) + ");"); if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) { - emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));"); + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + "0, ResNode, 0);"); NumResults = 1; } - if (InputHasChain) - emitCode("ReplaceUses(SDOperand(N.Val, " + - utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, " + - ChainName + ".ResNo" + "));"); + if (InputHasChain) { + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + + utostr(PatResults) + ", " + ChainName + ".Val, " + + ChainName + ".ResNo" + ");"); + if (DoReplace) + emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " + + utostr(PatResults) + ", " + ChainName + ".Val, " + + ChainName + ".ResNo" + ");"); + } if (FoldedChains.size() > 0) { std::string Code; for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) - emitCode("ReplaceUses(SDOperand(" + + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " + FoldedChains[j].first + ".Val, " + - utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " + - utostr(NumResults) + "));"); + utostr(FoldedChains[j].second) + ", ResNode, " + + utostr(NumResults) + ");"); + + for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) { + std::string Code = + FoldedChains[j].first + ".Val, " + + utostr(FoldedChains[j].second) + ", "; + emitCode("AddHandleReplacement(" + Code + "ResNode, " + + utostr(NumResults) + ");"); + } } if (NodeHasOutFlag) - emitCode("ReplaceUses(SDOperand(N.Val, " + - utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);"); + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + + utostr(PatResults + (unsigned)InputHasChain) + + ", InFlag.Val, InFlag.ResNo);"); // User does not expect the instruction would produce a chain! bool AddedChain = NodeHasChain && !InputHasChain; @@ -2789,7 +2820,8 @@ if (NodeHasInFlag || HasImpInputs) Code += ", InFlag"; emitCode(Code + ");"); - emitCode(" ReplaceUses(N, SDOperand(ResNode, 0));"); + emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo" + ", ResNode, 0);"); emitCode(" Result = SDOperand(ResNode, 0);"); emitCode("}"); } @@ -2807,7 +2839,9 @@ emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName() + "(Tmp" + utostr(OpVal) + ".Val);"); if (isRoot) { - emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val," + "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" + + utostr(ResNo) + ".ResNo);"); emitCode("Result = Tmp" + utostr(ResNo) + ";"); emitCode("return;"); } @@ -2871,7 +2905,7 @@ if (RR->isSubClassOf("Register")) { MVT::ValueType RVT = getRegisterValueType(RR, T); if (RVT == MVT::Flag) { - emitCode("AddToQueue(InFlag, " + RootName + utostr(OpNo) + ");"); + emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");"); } else { if (!ChainEmitted) { emitDecl("Chain"); @@ -2879,7 +2913,7 @@ ChainName = "Chain"; ChainEmitted = true; } - emitCode("AddToQueue(" + RootName + utostr(OpNo) + ", " + + emitCode("Select(" + RootName + utostr(OpNo) + ", " + RootName + utostr(OpNo) + ");"); emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName + ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) + @@ -2894,7 +2928,7 @@ } if (HasInFlag) - emitCode("AddToQueue(InFlag, " + RootName + + emitCode("Select(InFlag, " + RootName + ".getOperand(" + utostr(OpNo) + "));"); } @@ -2940,11 +2974,13 @@ std::vector > &GeneratedCode, std::set > &GeneratedDecl, std::vector &TargetOpcodes, - std::vector &TargetVTs) { + std::vector &TargetVTs, + bool DoReplace) { PatternCodeEmitter Emitter(*this, Pattern.getPredicates(), Pattern.getSrcPattern(), Pattern.getDstPattern(), GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs); + TargetOpcodes, TargetVTs, + DoReplace); // Emit the matcher, capturing named arguments in VariableMap. bool FoundChain = false; @@ -3071,9 +3107,7 @@ OS << std::string(Indent, ' ') << "// Pattern complexity = " << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity << " cost = " - << getResultPatternCost(Pattern.getDstPattern(), *this) - << " size = " - << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n"; + << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n"; } EmitPatterns(Other, Indent, OS); return; @@ -3185,6 +3219,9 @@ E = PatternsByOpcode.end(); PBOI != E; ++PBOI) { const std::string &OpName = PBOI->first->getName(); const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first); + bool OptSlctOrder = + (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) && + OpcodeInfo.getNumResults() > 0); std::vector &PatternsOfOp = PBOI->second; assert(!PatternsOfOp.empty() && "No patterns but map has entry?"); @@ -3232,7 +3269,7 @@ std::vector TargetOpcodes; std::vector TargetVTs; GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs); + TargetOpcodes, TargetVTs, OptSlctOrder); for (std::set >::iterator si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) AllGenDecls.insert(*si); @@ -3363,6 +3400,19 @@ OS << "void Select_" << OpName << (OpVTStr != "" ? "_" : "") << OpVTStr << "(SDOperand &Result, const SDOperand &N) {\n"; + if (OptSlctOrder) { + OS << " if (N.ResNo == " << OpcodeInfo.getNumResults() + << " && N.getValue(0).hasOneUse()) {\n" + << " SDOperand Dummy = " + << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, " + << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" + << " Result = Dummy;\n" + << " return;\n" + << " }\n"; + } // Print all declarations. for (std::set >::iterator @@ -3412,18 +3462,17 @@ // Emit boilerplate. OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n" << " std::vector Ops(N.Val->op_begin(), N.Val->op_end());\n" - << " AddToQueue(Ops[0], N.getOperand(0)); // Select the chain.\n\n" + << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n" << " // Select the flag operand.\n" << " if (Ops.back().getValueType() == MVT::Flag)\n" - << " AddToQueue(Ops.back(), Ops.back());\n" + << " Select(Ops.back(), Ops.back());\n" << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n" << " std::vector VTs;\n" << " VTs.push_back(MVT::Other);\n" << " VTs.push_back(MVT::Flag);\n" - << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], " - "Ops.size());\n" - << " ReplaceUses(SDOperand(N.Val, 0), New);\n" - << " ReplaceUses(SDOperand(N.Val, 1), SDOperand(New.Val, 1));\n" + << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n" << " Result = New.getValue(N.ResNo);\n" << " return;\n" << "}\n\n"; @@ -3436,6 +3485,11 @@ << " Result = N;\n" << " return; // Already selected.\n" << " }\n\n" + << " std::map::iterator CGMI = CodeGenMap.find(N);\n" + << " if (CGMI != CodeGenMap.end()) {\n" + << " Result = CGMI->second;\n" + << " return;\n" + << " }\n\n" << " switch (N.getOpcode()) {\n" << " default: break;\n" << " case ISD::EntryToken: // These leaves remain the same.\n" @@ -3452,18 +3506,96 @@ << " }\n" << " case ISD::AssertSext:\n" << " case ISD::AssertZext: {\n" - << " AddToQueue(Result, N.getOperand(0));\n" - << " ReplaceUses(N, Result);\n" + << " SDOperand Tmp0;\n" + << " Select(Tmp0, N.getOperand(0));\n" + << " if (!N.Val->hasOneUse())\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " + << "Tmp0.Val, Tmp0.ResNo);\n" + << " Result = Tmp0;\n" << " return;\n" << " }\n" << " case ISD::TokenFactor:\n" - << " case ISD::CopyFromReg:\n" - << " case ISD::CopyToReg: {\n" - << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" - << " SDOperand Dummy;\n" - << " AddToQueue(Dummy, N.getOperand(i));\n" + << " if (N.getNumOperands() == 2) {\n" + << " SDOperand Op0, Op1;\n" + << " Select(Op0, N.getOperand(0));\n" + << " Select(Op1, N.getOperand(1));\n" + << " Result = \n" + << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " + << "Result.Val, Result.ResNo);\n" + << " } else {\n" + << " std::vector Ops;\n" + << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" + << " SDOperand Val;\n" + << " Select(Val, N.getOperand(i));\n" + << " Ops.push_back(Val);\n" + << " }\n" + << " Result = \n" + << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " + << "Result.Val, Result.ResNo);\n" << " }\n" + << " return;\n" + << " case ISD::CopyFromReg: {\n" + << " SDOperand Chain;\n" + << " Select(Chain, N.getOperand(0));\n" + << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" + << " MVT::ValueType VT = N.Val->getValueType(0);\n" + << " if (N.Val->getNumValues() == 2) {\n" + << " if (Chain == N.getOperand(0)) {\n" + << " Result = N; // No change\n" + << " return;\n" + << " }\n" + << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " + << "New.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " + << "New.Val, 1);\n" + << " Result = New.getValue(N.ResNo);\n" + << " return;\n" + << " } else {\n" + << " SDOperand Flag;\n" + << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n" + << " if (Chain == N.getOperand(0) &&\n" + << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n" + << " Result = N; // No change\n" + << " return;\n" + << " }\n" + << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " + << "New.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " + << "New.Val, 1);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, " + << "New.Val, 2);\n" + << " Result = New.getValue(N.ResNo);\n" + << " return;\n" + << " }\n" + << " }\n" + << " case ISD::CopyToReg: {\n" + << " SDOperand Chain;\n" + << " Select(Chain, N.getOperand(0));\n" + << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" + << " SDOperand Val;\n" + << " Select(Val, N.getOperand(2));\n" << " Result = N;\n" + << " if (N.Val->getNumValues() == 1) {\n" + << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n" + << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " + << "Result.Val, 0);\n" + << " } else {\n" + << " SDOperand Flag(0, 0);\n" + << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n" + << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n" + << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n" + << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " + << "Result.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " + << "Result.Val, 1);\n" + << " Result = Result.getValue(N.ResNo);\n" + << " }\n" << " return;\n" << " }\n" << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n"; @@ -3547,93 +3679,80 @@ OS << "#if defined(__GNUC__) && \\\n"; OS << " ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))\n"; OS << "#define NOINLINE __attribute__((noinline))\n"; - OS << "#else\n"; - OS << "#define NOINLINE\n"; OS << "#endif\n\n"; - OS << "// Instruction selector priority queue:\n" - << "std::vector ISelQueue;\n"; - OS << "/// Keep track of nodes which have already been added to queue.\n" - << "unsigned char *ISelQueued;\n"; - OS << "/// Keep track of nodes which have already been selected.\n" - << "unsigned char *ISelSelected;\n"; - OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n" - << "std::vector ISelKilled;\n\n"; - - OS << "/// Sorting functions for the selection queue.\n" - << "struct isel_sort : public std::binary_function" - << " {\n" - << " bool operator()(const SDNode* left, const SDNode* right) " - << "const {\n" - << " return (left->getNodeId() > right->getNodeId());\n" - << " }\n" - << "};\n\n"; + OS << "// Instance var to keep track of multiply used nodes that have \n" + << "// already been selected.\n" + << "std::map CodeGenMap;\n"; + + OS << "// Instance var to keep track of mapping of chain generating nodes\n" + << "// and their place handle nodes.\n"; + OS << "std::map HandleMap;\n"; + OS << "// Instance var to keep track of mapping of place handle nodes\n" + << "// and their replacement nodes.\n"; + OS << "std::map ReplaceMap;\n"; - OS << "inline void setQueued(int Id) {\n"; - OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n"; - OS << "}\n"; - OS << "inline bool isQueued(int Id) {\n"; - OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n"; - OS << "}\n"; - OS << "inline void setSelected(int Id) {\n"; - OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n"; - OS << "}\n"; - OS << "inline bool isSelected(int Id) {\n"; - OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n"; - OS << "}\n\n"; - - OS << "inline void AddToQueue(SDOperand &Result, SDOperand N) {\n"; - OS << " Result = N;\n"; - OS << " int Id = N.Val->getNodeId();\n"; - OS << " if (Id != -1 && !isQueued(Id)) {\n"; - OS << " ISelQueue.push_back(N.Val);\n"; - OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; - OS << " setQueued(Id);\n"; + OS << "\n"; + OS << "// AddHandleReplacement - Note the pending replacement node for a\n" + << "// handle node in ReplaceMap.\n"; + OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, " + << "unsigned RNum) {\n"; + OS << " SDOperand N(H, HNum);\n"; + OS << " std::map::iterator HMI = HandleMap.find(N);\n"; + OS << " if (HMI != HandleMap.end()) {\n"; + OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n"; + OS << " HandleMap.erase(N);\n"; OS << " }\n"; - OS << "}\n\n"; + OS << "}\n"; - OS << "inline void RemoveKilled() {\n"; -OS << " unsigned NumKilled = ISelKilled.size();\n"; - OS << " if (NumKilled) {\n"; - OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n"; - OS << " SDNode *Temp = ISelKilled[i];\n"; - OS << " std::remove(ISelQueue.begin(), ISelQueue.end(), Temp);\n"; - OS << " };\n"; - OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; - OS << " ISelKilled.clear();\n"; + OS << "\n"; + OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n"; + OS << "// handles.Some handles do not yet have replacements because the\n"; + OS << "// nodes they replacements have only dead readers.\n"; + OS << "void SelectDanglingHandles() {\n"; + OS << " for (std::map::iterator I = " + << "HandleMap.begin(),\n" + << " E = HandleMap.end(); I != E; ++I) {\n"; + OS << " SDOperand N = I->first;\n"; + OS << " SDOperand R;\n"; + OS << " Select(R, N.getValue(0));\n"; + OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n"; OS << " }\n"; - OS << "}\n\n"; - - OS << "inline void ReplaceUses(SDOperand F, SDOperand T) {\n"; - OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n"; - OS << " setSelected(F.Val->getNodeId());\n"; - OS << " RemoveKilled();\n"; - OS << "}\n\n"; - - OS << "// SelectRoot - Top level entry to DAG isel.\n"; - OS << "SDOperand SelectRoot(SDOperand Root) {\n"; - OS << " SelectRootInit();\n"; - OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n"; - OS << " ISelQueued = new unsigned char[NumBytes];\n"; - OS << " ISelSelected = new unsigned char[NumBytes];\n"; - OS << " memset(ISelQueued, 0, NumBytes);\n"; - OS << " memset(ISelSelected, 0, NumBytes);\n"; + OS << "}\n"; OS << "\n"; - OS << " SDOperand ResNode;\n"; - OS << " Select(ResNode, Root);\n"; - OS << " while (!ISelQueue.empty()) {\n"; - OS << " SDOperand Tmp;\n"; - OS << " SDNode *Node = ISelQueue.front();\n"; - OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; - OS << " ISelQueue.pop_back();\n"; - OS << " if (!isSelected(Node->getNodeId()))\n"; - OS << " Select(Tmp, SDOperand(Node, 0));\n"; + OS << "// ReplaceHandles - Replace all the handles with the real target\n"; + OS << "// specific nodes.\n"; + OS << "void ReplaceHandles() {\n"; + OS << " for (std::map::iterator I = " + << "ReplaceMap.begin(),\n" + << " E = ReplaceMap.end(); I != E; ++I) {\n"; + OS << " SDOperand From = I->first;\n"; + OS << " SDOperand To = I->second;\n"; + OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), " + << "E = From.Val->use_end(); UI != E; ++UI) {\n"; + OS << " SDNode *Use = *UI;\n"; + OS << " std::vector Ops;\n"; + OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n"; + OS << " SDOperand O = Use->getOperand(i);\n"; + OS << " if (O.Val == From.Val)\n"; + OS << " Ops.push_back(To);\n"; + OS << " else\n"; + OS << " Ops.push_back(O);\n"; + OS << " }\n"; + OS << " SDOperand U = SDOperand(Use, 0);\n"; + OS << " CurDAG->UpdateNodeOperands(U, Ops);\n"; + OS << " }\n"; OS << " }\n"; + OS << "}\n"; + OS << "\n"; - OS << " delete[] ISelQueued;\n"; - OS << " ISelQueued = NULL;\n"; - OS << " delete[] ISelSelected;\n"; - OS << " ISelSelected = NULL;\n"; + OS << "// SelectRoot - Top level entry to DAG isel.\n"; + OS << "SDOperand SelectRoot(SDOperand N) {\n"; + OS << " SDOperand ResNode;\n"; + OS << " Select(ResNode, N);\n"; + OS << " SelectDanglingHandles();\n"; + OS << " ReplaceHandles();\n"; + OS << " ReplaceMap.clear();\n"; OS << " return ResNode;\n"; OS << "}\n"; From rafael.espindola at gmail.com Wed Aug 9 11:41:26 2006 From: rafael.espindola at gmail.com (Rafael Espindola) Date: Wed, 9 Aug 2006 11:41:26 -0500 Subject: [llvm-commits] CVS: llvm/test/Regression/CodeGen/ARM/vargs.ll Message-ID: <200608091641.k79GfQBd024168@zion.cs.uiuc.edu> Changes in directory llvm/test/Regression/CodeGen/ARM: vargs.ll updated: 1.1 -> 1.2 --- Log message: fix the spill code --- Diffs of the changes: (+3 -2) vargs.ll | 5 +++-- 1 files changed, 3 insertions(+), 2 deletions(-) Index: llvm/test/Regression/CodeGen/ARM/vargs.ll diff -u llvm/test/Regression/CodeGen/ARM/vargs.ll:1.1 llvm/test/Regression/CodeGen/ARM/vargs.ll:1.2 --- llvm/test/Regression/CodeGen/ARM/vargs.ll:1.1 Tue Aug 8 08:02:29 2006 +++ llvm/test/Regression/CodeGen/ARM/vargs.ll Wed Aug 9 11:41:12 2006 @@ -1,4 +1,4 @@ -; RUN: llvm-as < %s | llc -march=arm +; RUN: llvm-as < %s | llc -march=arm %str = internal constant [43 x sbyte] c"Hello World %d %d %d %d %d %d %d %d %d %d\0A\00" ; <[43 x sbyte]*> [#uses=1] implementation ; Functions: @@ -6,7 +6,8 @@ int %main() { entry: %tmp = call int (sbyte*, ...)* %printf( sbyte* getelementptr ([43 x sbyte]* %str, int 0, uint 0), int 1, int 2, int 3, int 4, int 5, int 6, int 7, int 8, int 9, int 10 ) ; [#uses=0] - ret int 0 + %tmp2 = call int (sbyte*, ...)* %printf( sbyte* getelementptr ([43 x sbyte]* %str, int 0, uint 0), int 10, int 9, int 8, int 7, int 6, int 5, int 4, int 3, int 2, int 1 ) ; [#uses=0] + ret int 11 } declare int %printf(sbyte*, ...) From rafael.espindola at gmail.com Wed Aug 9 11:41:28 2006 From: rafael.espindola at gmail.com (Rafael Espindola) Date: Wed, 9 Aug 2006 11:41:28 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp ARMRegisterInfo.cpp Message-ID: <200608091641.k79GfS8V024175@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/ARM: ARMISelDAGToDAG.cpp updated: 1.24 -> 1.25 ARMRegisterInfo.cpp updated: 1.12 -> 1.13 --- Log message: fix the spill code --- Diffs of the changes: (+15 -7) ARMISelDAGToDAG.cpp | 6 ++++++ ARMRegisterInfo.cpp | 16 +++++++++------- 2 files changed, 15 insertions(+), 7 deletions(-) Index: llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp diff -u llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp:1.24 llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp:1.25 --- llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp:1.24 Tue Aug 8 08:02:29 2006 +++ llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp Wed Aug 9 11:41:12 2006 @@ -148,6 +148,12 @@ Ops.push_back(Chain); Ops.push_back(Callee); + // Add argument registers to the end of the list so that they are known live + // into the call. + for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) + Ops.push_back(DAG.getRegister(RegsToPass[i].first, + RegsToPass[i].second.getValueType())); + unsigned CallOpc = ARMISD::CALL; if (InFlag.Val) Ops.push_back(InFlag); Index: llvm/lib/Target/ARM/ARMRegisterInfo.cpp diff -u llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.12 llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.13 --- llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.12 Wed Aug 9 08:15:47 2006 +++ llvm/lib/Target/ARM/ARMRegisterInfo.cpp Wed Aug 9 11:41:12 2006 @@ -31,9 +31,8 @@ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned SrcReg, int FI, const TargetRegisterClass *RC) const { - // On the order of operands here: think "[FI + 0] = SrcReg". assert (RC == ARM::IntRegsRegisterClass); - BuildMI(MBB, I, ARM::str, 3).addFrameIndex(FI).addImm(0).addReg(SrcReg); + BuildMI(MBB, I, ARM::str, 3).addReg(SrcReg).addImm(0).addFrameIndex(FI); } void ARMRegisterInfo:: @@ -41,7 +40,7 @@ unsigned DestReg, int FI, const TargetRegisterClass *RC) const { assert (RC == ARM::IntRegsRegisterClass); - BuildMI(MBB, I, ARM::ldr, 2, DestReg).addFrameIndex(FI).addImm(0); + BuildMI(MBB, I, ARM::ldr, 2, DestReg).addImm(0).addFrameIndex(FI); } void ARMRegisterInfo::copyRegToReg(MachineBasicBlock &MBB, @@ -81,7 +80,8 @@ MachineBasicBlock &MBB = *MI.getParent(); MachineFunction &MF = *MBB.getParent(); - assert (MI.getOpcode() == ARM::ldr); + assert (MI.getOpcode() == ARM::ldr || + MI.getOpcode() == ARM::str); unsigned FrameIdx = 2; unsigned OffIdx = 1; @@ -93,6 +93,11 @@ unsigned StackSize = MF.getFrameInfo()->getStackSize(); + // + if (Offset < 0) + Offset -= 4; + // + Offset += StackSize; assert (Offset >= 0); @@ -121,9 +126,6 @@ MachineFrameInfo *MFI = MF.getFrameInfo(); int NumBytes = (int) MFI->getStackSize(); - //hack - assert(NumBytes == 0); - if (MFI->hasCalls()) { // We reserve argument space for call sites in the function immediately on // entry to the current function. This eliminates the need for add/sub From tbrethou at cs.uiuc.edu Wed Aug 9 11:41:33 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 11:41:33 -0500 Subject: [llvm-commits] CVS: llvm/utils/TableGen/DAGISelEmitter.cpp Message-ID: <200608091641.k79GfX0h024189@zion.cs.uiuc.edu> Changes in directory llvm/utils/TableGen: DAGISelEmitter.cpp updated: 1.238 -> 1.239 --- Log message: Reverting back to original 1.8 version so I can manually merge in patch. --- Diffs of the changes: (+503 -398) DAGISelEmitter.cpp | 901 +++++++++++++++++++++++++++++------------------------ 1 files changed, 503 insertions(+), 398 deletions(-) Index: llvm/utils/TableGen/DAGISelEmitter.cpp diff -u llvm/utils/TableGen/DAGISelEmitter.cpp:1.238 llvm/utils/TableGen/DAGISelEmitter.cpp:1.239 --- llvm/utils/TableGen/DAGISelEmitter.cpp:1.238 Mon Aug 7 21:23:42 2006 +++ llvm/utils/TableGen/DAGISelEmitter.cpp Wed Aug 9 11:41:21 2006 @@ -1829,22 +1829,9 @@ // If this node is commutative, consider the commuted order. if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) { assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!"); - // Don't count children which are actually register references. - unsigned NC = 0; - for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) { - TreePatternNode *Child = N->getChild(i); - if (Child->isLeaf()) - if (DefInit *DI = dynamic_cast(Child->getLeafValue())) { - Record *RR = DI->getDef(); - if (RR->isSubClassOf("Register")) - continue; - } - NC++; - } // Consider the commuted order. - if (NC == 2) - CombineChildVariants(N, ChildVariants[1], ChildVariants[0], - OutVariants, ISE); + CombineChildVariants(N, ChildVariants[1], ChildVariants[0], + OutVariants, ISE); } } @@ -2119,6 +2106,8 @@ // Names of all the folded nodes which produce chains. std::vector > FoldedChains; std::set Duplicates; + /// These nodes are being marked "in-flight" so they cannot be folded. + std::vector InflightNodes; /// GeneratedCode - This is the buffer that we emit code to. The first bool /// indicates whether this is an exit predicate (something that should be @@ -2134,6 +2123,7 @@ std::vector &TargetVTs; std::string ChainName; + bool DoReplace; unsigned TmpNo; unsigned OpcNo; unsigned VTNo; @@ -2164,10 +2154,11 @@ std::vector > &gc, std::set > &gd, std::vector &to, - std::vector &tv) + std::vector &tv, + bool dorep) : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr), GeneratedCode(gc), GeneratedDecl(gd), TargetOpcodes(to), TargetVTs(tv), - TmpNo(0), OpcNo(0), VTNo(0) {} + DoReplace(dorep), TmpNo(0), OpcNo(0), VTNo(0) {} /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo /// if the match fails. At this point, we already know that the opcode for N @@ -2234,14 +2225,24 @@ bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE); bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE); bool EmittedUseCheck = false; + bool EmittedSlctedCheck = false; if (HasChain) { if (NodeHasChain) OpNo = 1; if (!isRoot) { const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator()); + // Not in flight? + emitCheck("InFlightSet.count(" + RootName + ".Val) == 0"); // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); EmittedUseCheck = true; + // hasOneUse() check is not strong enough. If the original node has + // already been selected, it may have been replaced with another. + for (unsigned j = 0; j != CInfo.getNumResults(); j++) + emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + + "))"); + + EmittedSlctedCheck = true; if (NodeHasChain) { // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node // has a chain use. @@ -2279,8 +2280,14 @@ PInfo.hasProperty(SDNodeInfo::SDNPHasChain) || PInfo.hasProperty(SDNodeInfo::SDNPInFlag) || PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag)) - emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName + - ".Val)"); + if (PInfo.getNumOperands() > 1) { + emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName + + ".Val)"); + } else { + emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" + + "isNonImmUse(" + ParentName + ".Val, " + RootName + + ".Val))"); + } } } @@ -2310,6 +2317,12 @@ // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); } + if (!EmittedSlctedCheck) + // hasOneUse() check is not strong enough. If the original node has + // already been selected, it may have been replaced with another. + for (unsigned j = 0; j < CInfo.getNumResults(); j++) + emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + + "))"); } for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) { @@ -2466,14 +2479,30 @@ for (unsigned i = 0; i < NumRes; ++i) emitDecl("CPTmp" + utostr(i+ResNo)); - std::string Code = Fn + "(" + Val; + std::string Code = "bool Match = " + Fn + "(" + Val; for (unsigned i = 0; i < NumRes; i++) Code += ", CPTmp" + utostr(i + ResNo); - emitCheck(Code + ")"); + emitCode(Code + ");"); + if (InflightNodes.size()) { + // Remove the in-flight nodes if the ComplexPattern does not match! + emitCode("if (!Match) {"); + for (std::vector::iterator AI = InflightNodes.begin(), + AE = InflightNodes.end(); AI != AE; ++AI) + emitCode(" SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " + + *AI + ".Val);"); + emitCode("}"); + } + emitCheck("Match"); + + for (unsigned i = 0; i < NumRes; ++i) { + emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, CPTmp" + + utostr(i+ResNo) + ".Val);"); + InflightNodes.push_back("CPTmp" + utostr(i+ResNo)); + } for (unsigned i = 0; i < NumRes; ++i) { emitDecl("Tmp" + utostr(i+ResNo)); - emitCode("AddToQueue(Tmp" + utostr(i+ResNo) + ", CPTmp" + + emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" + utostr(i+ResNo) + ");"); } @@ -2485,12 +2514,12 @@ if (LikeLeaf) emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";"); else { - emitCode("AddToQueue(Tmp" + utostr(ResNo) + ", " + Val + ");"); - if (isRoot && N->isLeaf()) { - emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); - emitCode("Result = Tmp" + utostr(ResNo) + ";"); - emitCode("return;"); - } + emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");"); + } + + if (isRoot && N->isLeaf()) { + emitCode("Result = Tmp" + utostr(ResNo) + ";"); + emitCode("return;"); } } // Add Tmp to VariableMap, so that we don't multiply select this @@ -2585,6 +2614,22 @@ } } + // Make sure these operands which would be selected won't be folded while + // the isel traverses the DAG upward. + for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) { + TreePatternNode *Child = EmitOrder[i].second; + if (!Child->getName().empty()) { + std::string &Val = VariableMap[Child->getName()]; + assert(!Val.empty() && + "Variable referenced but not defined and not caught earlier!"); + if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) { + emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, " + + Val + ".Val);"); + InflightNodes.push_back(Val); + } + } + } + // Emit all of the operands. std::vector > NumTemps(EmitOrder.size()); for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) { @@ -2604,12 +2649,20 @@ // Emit all the chain and CopyToReg stuff. bool ChainEmitted = NodeHasChain; if (NodeHasChain) - emitCode("AddToQueue(" + ChainName + ", " + ChainName + ");"); + emitCode("Select(" + ChainName + ", " + ChainName + ");"); if (NodeHasInFlag || HasImpInputs) EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true); if (NodeHasOptInFlag) { emitCode("if (HasInFlag)"); - emitCode(" AddToQueue(InFlag, N.getOperand(N.getNumOperands()-1));"); + emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));"); + } + + if (isRoot) { + // The operands have been selected. Remove them from InFlightSet. + for (std::vector::iterator AI = InflightNodes.begin(), + AE = InflightNodes.end(); AI != AE; ++AI) + emitCode("SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " + + *AI + ".Val);"); } unsigned NumResults = Inst.getNumResults(); @@ -2661,7 +2714,7 @@ emitCode("for (unsigned i = 2, e = N.getNumOperands(); " "i != e; ++i) {"); emitCode(" SDOperand VarOp(0, 0);"); - emitCode(" AddToQueue(VarOp, N.getOperand(i));"); + emitCode(" Select(VarOp, N.getOperand(i));"); emitCode(" Ops.push_back(VarOp);"); emitCode("}"); } @@ -2683,7 +2736,7 @@ } if (HasVarOps) - Code += ", &Ops[0], Ops.size()"; + Code += ", Ops"; else if (NodeHasOptInFlag) Code = "HasInFlag ? " + Code + ", InFlag) : " + Code; @@ -2704,35 +2757,50 @@ return std::make_pair(1, ResNo); for (unsigned i = 0; i < NumResults; i++) - emitCode("ReplaceUses(SDOperand(N.Val, " + - utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));"); + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + + utostr(i) + ", ResNode, " + utostr(i) + ");"); if (NodeHasOutFlag) emitCode("InFlag = SDOperand(ResNode, " + utostr(NumResults + (unsigned)NodeHasChain) + ");"); if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) { - emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));"); + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + "0, ResNode, 0);"); NumResults = 1; } - if (InputHasChain) - emitCode("ReplaceUses(SDOperand(N.Val, " + - utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, " + - ChainName + ".ResNo" + "));"); + if (InputHasChain) { + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + + utostr(PatResults) + ", " + ChainName + ".Val, " + + ChainName + ".ResNo" + ");"); + if (DoReplace) + emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " + + utostr(PatResults) + ", " + ChainName + ".Val, " + + ChainName + ".ResNo" + ");"); + } if (FoldedChains.size() > 0) { std::string Code; for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) - emitCode("ReplaceUses(SDOperand(" + + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " + FoldedChains[j].first + ".Val, " + - utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " + - utostr(NumResults) + "));"); + utostr(FoldedChains[j].second) + ", ResNode, " + + utostr(NumResults) + ");"); + + for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) { + std::string Code = + FoldedChains[j].first + ".Val, " + + utostr(FoldedChains[j].second) + ", "; + emitCode("AddHandleReplacement(" + Code + "ResNode, " + + utostr(NumResults) + ");"); + } } if (NodeHasOutFlag) - emitCode("ReplaceUses(SDOperand(N.Val, " + - utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);"); + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + + utostr(PatResults + (unsigned)InputHasChain) + + ", InFlag.Val, InFlag.ResNo);"); // User does not expect the instruction would produce a chain! bool AddedChain = NodeHasChain && !InputHasChain; @@ -2789,7 +2857,8 @@ if (NodeHasInFlag || HasImpInputs) Code += ", InFlag"; emitCode(Code + ");"); - emitCode(" ReplaceUses(N, SDOperand(ResNode, 0));"); + emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo" + ", ResNode, 0);"); emitCode(" Result = SDOperand(ResNode, 0);"); emitCode("}"); } @@ -2807,7 +2876,9 @@ emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName() + "(Tmp" + utostr(OpVal) + ".Val);"); if (isRoot) { - emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); + emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val," + "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" + + utostr(ResNo) + ".ResNo);"); emitCode("Result = Tmp" + utostr(ResNo) + ";"); emitCode("return;"); } @@ -2824,15 +2895,13 @@ /// 'Pat' may be missing types. If we find an unresolved type to add a check /// for, this returns true otherwise false if Pat has all types. bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other, - const std::string &Prefix, bool isRoot = false) { + const std::string &Prefix) { // Did we find one? if (Pat->getExtTypes() != Other->getExtTypes()) { // Move a type over from 'other' to 'pat'. Pat->setTypes(Other->getExtTypes()); - // The top level node type is checked outside of the select function. - if (!isRoot) - emitCheck(Prefix + ".Val->getValueType(0) == " + - getName(Pat->getTypeNum(0))); + emitCheck(Prefix + ".Val->getValueType(0) == " + + getName(Pat->getTypeNum(0))); return true; } @@ -2871,7 +2940,7 @@ if (RR->isSubClassOf("Register")) { MVT::ValueType RVT = getRegisterValueType(RR, T); if (RVT == MVT::Flag) { - emitCode("AddToQueue(InFlag, " + RootName + utostr(OpNo) + ");"); + emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");"); } else { if (!ChainEmitted) { emitDecl("Chain"); @@ -2879,7 +2948,7 @@ ChainName = "Chain"; ChainEmitted = true; } - emitCode("AddToQueue(" + RootName + utostr(OpNo) + ", " + + emitCode("Select(" + RootName + utostr(OpNo) + ", " + RootName + utostr(OpNo) + ");"); emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName + ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) + @@ -2894,7 +2963,7 @@ } if (HasInFlag) - emitCode("AddToQueue(InFlag, " + RootName + + emitCode("Select(InFlag, " + RootName + ".getOperand(" + utostr(OpNo) + "));"); } @@ -2940,11 +3009,13 @@ std::vector > &GeneratedCode, std::set > &GeneratedDecl, std::vector &TargetOpcodes, - std::vector &TargetVTs) { + std::vector &TargetVTs, + bool DoReplace) { PatternCodeEmitter Emitter(*this, Pattern.getPredicates(), Pattern.getSrcPattern(), Pattern.getDstPattern(), GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs); + TargetOpcodes, TargetVTs, + DoReplace); // Emit the matcher, capturing named arguments in VariableMap. bool FoundChain = false; @@ -2984,7 +3055,7 @@ // Insert a check for an unresolved type and add it to the tree. If we find // an unresolved type to add a check for, this returns true and we iterate, // otherwise we are done. - } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true)); + } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N")); Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/); delete Pat; @@ -3071,9 +3142,7 @@ OS << std::string(Indent, ' ') << "// Pattern complexity = " << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity << " cost = " - << getResultPatternCost(Pattern.getDstPattern(), *this) - << " size = " - << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n"; + << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n"; } EmitPatterns(Other, Indent, OS); return; @@ -3171,12 +3240,7 @@ } } } - - // For each opcode, there might be multiple select functions, one per - // ValueType of the node (or its first operand if it doesn't produce a - // non-chain result. - std::map > OpcodeVTMap; - + // Emit one Select_* method for each top-level opcode. We do this instead of // emitting one giant switch statement to support compilers where this will // result in the recursive functions taking less stack space. @@ -3185,245 +3249,223 @@ E = PatternsByOpcode.end(); PBOI != E; ++PBOI) { const std::string &OpName = PBOI->first->getName(); const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first); - std::vector &PatternsOfOp = PBOI->second; - assert(!PatternsOfOp.empty() && "No patterns but map has entry?"); - + bool OptSlctOrder = + (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) && + OpcodeInfo.getNumResults() > 0); + std::vector &Patterns = PBOI->second; + assert(!Patterns.empty() && "No patterns but map has entry?"); + // We want to emit all of the matching code now. However, we want to emit // the matches in order of minimal cost. Sort the patterns so the least // cost one is at the start. - std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(), + std::stable_sort(Patterns.begin(), Patterns.end(), PatternSortingPredicate(*this)); - // Split them into groups by type. - std::map > PatternsByType; - for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) { - PatternToMatch *Pat = PatternsOfOp[i]; - TreePatternNode *SrcPat = Pat->getSrcPattern(); - if (OpcodeInfo.getNumResults() == 0 && SrcPat->getNumChildren() > 0) - SrcPat = SrcPat->getChild(0); - MVT::ValueType VT = SrcPat->getTypeNum(0); - std::map >::iterator TI = - PatternsByType.find(VT); - if (TI != PatternsByType.end()) - TI->second.push_back(Pat); - else { - std::vector PVec; - PVec.push_back(Pat); - PatternsByType.insert(std::make_pair(VT, PVec)); - } - } - - for (std::map >::iterator - II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE; - ++II) { - MVT::ValueType OpVT = II->first; - std::vector &Patterns = II->second; - typedef std::vector > CodeList; - typedef std::vector >::iterator CodeListI; + typedef std::vector > CodeList; + typedef std::vector >::iterator CodeListI; - std::vector > CodeForPatterns; - std::vector > PatternOpcodes; - std::vector > PatternVTs; - std::vector > > PatternDecls; - std::set > AllGenDecls; - for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { - CodeList GeneratedCode; - std::set > GeneratedDecl; - std::vector TargetOpcodes; - std::vector TargetVTs; - GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs); - for (std::set >::iterator - si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) - AllGenDecls.insert(*si); - CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode)); - PatternDecls.push_back(GeneratedDecl); - PatternOpcodes.push_back(TargetOpcodes); - PatternVTs.push_back(TargetVTs); - } + std::vector > CodeForPatterns; + std::vector > PatternOpcodes; + std::vector > PatternVTs; + std::vector > > PatternDecls; + std::set > AllGenDecls; + for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { + CodeList GeneratedCode; + std::set > GeneratedDecl; + std::vector TargetOpcodes; + std::vector TargetVTs; + GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, + TargetOpcodes, TargetVTs, OptSlctOrder); + for (std::set >::iterator + si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) + AllGenDecls.insert(*si); + CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode)); + PatternDecls.push_back(GeneratedDecl); + PatternOpcodes.push_back(TargetOpcodes); + PatternVTs.push_back(TargetVTs); + } - // Scan the code to see if all of the patterns are reachable and if it is - // possible that the last one might not match. - bool mightNotMatch = true; - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - mightNotMatch = false; - - for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) { - if (GeneratedCode[j].first) { // predicate. - mightNotMatch = true; - break; - } + // Scan the code to see if all of the patterns are reachable and if it is + // possible that the last one might not match. + bool mightNotMatch = true; + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + mightNotMatch = false; + + for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) { + if (GeneratedCode[j].first) { // predicate. + mightNotMatch = true; + break; } + } - // If this pattern definitely matches, and if it isn't the last one, the - // patterns after it CANNOT ever match. Error out. - if (mightNotMatch == false && i != CodeForPatterns.size()-1) { - std::cerr << "Pattern '"; - CodeForPatterns[i+1].first->getSrcPattern()->print(std::cerr); - std::cerr << "' is impossible to select!\n"; - exit(1); - } + // If this pattern definitely matches, and if it isn't the last one, the + // patterns after it CANNOT ever match. Error out. + if (mightNotMatch == false && i != CodeForPatterns.size()-1) { + std::cerr << "Pattern '"; + CodeForPatterns[i+1].first->getSrcPattern()->print(OS); + std::cerr << "' is impossible to select!\n"; + exit(1); } + } - // Factor target node emission code (emitted by EmitResultCode) into - // separate functions. Uniquing and share them among all instruction - // selection routines. - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - std::vector &TargetOpcodes = PatternOpcodes[i]; - std::vector &TargetVTs = PatternVTs[i]; - std::set > Decls = PatternDecls[i]; - int CodeSize = (int)GeneratedCode.size(); - int LastPred = -1; - for (int j = CodeSize-1; j >= 0; --j) { - if (GeneratedCode[j].first) { - LastPred = j; - break; - } + // Factor target node emission code (emitted by EmitResultCode) into + // separate functions. Uniquing and share them among all instruction + // selection routines. + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + std::vector &TargetOpcodes = PatternOpcodes[i]; + std::vector &TargetVTs = PatternVTs[i]; + std::set > Decls = PatternDecls[i]; + int CodeSize = (int)GeneratedCode.size(); + int LastPred = -1; + for (int j = CodeSize-1; j >= 0; --j) { + if (GeneratedCode[j].first) { + LastPred = j; + break; } + } - std::string CalleeDecls; - std::string CalleeCode = "(SDOperand &Result, const SDOperand &N"; - std::string CallerCode = "(Result, N"; - for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) { - CalleeCode += ", unsigned Opc" + utostr(j); - CallerCode += ", " + TargetOpcodes[j]; - } - for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) { - CalleeCode += ", MVT::ValueType VT" + utostr(j); - CallerCode += ", " + TargetVTs[j]; - } - for (std::set >::iterator - I = Decls.begin(), E = Decls.end(); I != E; ++I) { - std::string Name = I->second; - if (I->first == 0) { - if (Name == "InFlag" || - (Name.size() > 3 && - Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) { - CalleeDecls += " SDOperand " + Name + "(0, 0);\n"; - continue; - } - CalleeCode += ", SDOperand &" + Name; - CallerCode += ", " + Name; - } else if (I->first == 1) { - if (Name == "ResNode") { - CalleeDecls += " SDNode *" + Name + " = NULL;\n"; - continue; - } - CalleeCode += ", SDNode *" + Name; - CallerCode += ", " + Name; - } else { - CalleeCode += ", bool " + Name; - CallerCode += ", " + Name; + std::string CalleeDecls; + std::string CalleeCode = "(SDOperand &Result, SDOperand &N"; + std::string CallerCode = "(Result, N"; + for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) { + CalleeCode += ", unsigned Opc" + utostr(j); + CallerCode += ", " + TargetOpcodes[j]; + } + for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) { + CalleeCode += ", MVT::ValueType VT" + utostr(j); + CallerCode += ", " + TargetVTs[j]; + } + for (std::set >::iterator + I = Decls.begin(), E = Decls.end(); I != E; ++I) { + std::string Name = I->second; + if (I->first == 0) { + if (Name == "InFlag" || + (Name.size() > 3 && + Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) { + CalleeDecls += " SDOperand " + Name + "(0, 0);\n"; + continue; } - } - CallerCode += ");"; - CalleeCode += ") "; - // Prevent emission routines from being inlined to reduce selection - // routines stack frame sizes. - CalleeCode += "NOINLINE "; - CalleeCode += "{\n" + CalleeDecls; - for (int j = LastPred+1; j < CodeSize; ++j) - CalleeCode += " " + GeneratedCode[j].second + '\n'; - for (int j = LastPred+1; j < CodeSize; ++j) - GeneratedCode.pop_back(); - CalleeCode += "}\n"; - - // Uniquing the emission routines. - unsigned EmitFuncNum; - std::map::iterator EFI = - EmitFunctions.find(CalleeCode); - if (EFI != EmitFunctions.end()) { - EmitFuncNum = EFI->second; + CalleeCode += ", SDOperand &" + Name; + CallerCode += ", " + Name; + } else if (I->first == 1) { + if (Name == "ResNode") { + CalleeDecls += " SDNode *" + Name + " = NULL;\n"; + continue; + } + CalleeCode += ", SDNode *" + Name; + CallerCode += ", " + Name; } else { - EmitFuncNum = EmitFunctions.size(); - EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum)); - OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode; - } - - // Replace the emission code within selection routines with calls to the - // emission functions. - CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode; - GeneratedCode.push_back(std::make_pair(false, CallerCode)); - GeneratedCode.push_back(std::make_pair(false, "return;")); - } - - // Print function. - std::string OpVTStr = (OpVT != MVT::isVoid && OpVT != MVT::iPTR) - ? getEnumName(OpVT).substr(5) : "" ; - std::map >::iterator OpVTI = - OpcodeVTMap.find(OpName); - if (OpVTI == OpcodeVTMap.end()) { - std::vector VTSet; - VTSet.push_back(OpVTStr); - OpcodeVTMap.insert(std::make_pair(OpName, VTSet)); - } else - OpVTI->second.push_back(OpVTStr); - - OS << "void Select_" << OpName << (OpVTStr != "" ? "_" : "") - << OpVTStr << "(SDOperand &Result, const SDOperand &N) {\n"; - - // Print all declarations. - for (std::set >::iterator - I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I) - if (I->first == 0) - OS << " SDOperand " << I->second << "(0, 0);\n"; - else if (I->first == 1) - OS << " SDNode *" << I->second << " = NULL;\n"; - else - OS << " bool " << I->second << " = false;\n"; - - // Loop through and reverse all of the CodeList vectors, as we will be - // accessing them from their logical front, but accessing the end of a - // vector is more efficient. - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - std::reverse(GeneratedCode.begin(), GeneratedCode.end()); + CalleeCode += ", bool " + Name; + CallerCode += ", " + Name; + } } + CallerCode += ");"; + CalleeCode += ") "; + // Prevent emission routines from being inlined to reduce selection + // routines stack frame sizes. + CalleeCode += "NOINLINE "; + CalleeCode += "{\n" + CalleeDecls; + for (int j = LastPred+1; j < CodeSize; ++j) + CalleeCode += " " + GeneratedCode[j].second + '\n'; + for (int j = LastPred+1; j < CodeSize; ++j) + GeneratedCode.pop_back(); + CalleeCode += "}\n"; + + // Uniquing the emission routines. + unsigned EmitFuncNum; + std::map::iterator EFI = + EmitFunctions.find(CalleeCode); + if (EFI != EmitFunctions.end()) { + EmitFuncNum = EFI->second; + } else { + EmitFuncNum = EmitFunctions.size(); + EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum)); + OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode; + } + + // Replace the emission code within selection routines with calls to the + // emission functions. + CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode; + GeneratedCode.push_back(std::make_pair(false, CallerCode)); + GeneratedCode.push_back(std::make_pair(false, "return;")); + } + + // Print function. + OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n"; + if (OptSlctOrder) { + OS << " if (N.ResNo == " << OpcodeInfo.getNumResults() + << " && N.getValue(0).hasOneUse()) {\n" + << " SDOperand Dummy = " + << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, " + << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" + << " Result = Dummy;\n" + << " return;\n" + << " }\n"; + } + + // Print all declarations. + for (std::set >::iterator + I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I) + if (I->first == 0) + OS << " SDOperand " << I->second << "(0, 0);\n"; + else if (I->first == 1) + OS << " SDNode *" << I->second << " = NULL;\n"; + else + OS << " bool " << I->second << " = false;\n"; + + // Loop through and reverse all of the CodeList vectors, as we will be + // accessing them from their logical front, but accessing the end of a + // vector is more efficient. + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + std::reverse(GeneratedCode.begin(), GeneratedCode.end()); + } - // Next, reverse the list of patterns itself for the same reason. - std::reverse(CodeForPatterns.begin(), CodeForPatterns.end()); + // Next, reverse the list of patterns itself for the same reason. + std::reverse(CodeForPatterns.begin(), CodeForPatterns.end()); - // Emit all of the patterns now, grouped together to share code. - EmitPatterns(CodeForPatterns, 2, OS); + // Emit all of the patterns now, grouped together to share code. + EmitPatterns(CodeForPatterns, 2, OS); - // If the last pattern has predicates (which could fail) emit code to catch - // the case where nothing handles a pattern. - if (mightNotMatch) { - OS << " std::cerr << \"Cannot yet select: \";\n"; - if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" && - OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" && - OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") { - OS << " N.Val->dump(CurDAG);\n"; - } else { - OS << " unsigned iid = cast(N.getOperand(" - "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n" - << " std::cerr << \"intrinsic %\"<< " - "Intrinsic::getName((Intrinsic::ID)iid);\n"; - } - OS << " std::cerr << '\\n';\n" - << " abort();\n"; + // If the last pattern has predicates (which could fail) emit code to catch + // the case where nothing handles a pattern. + if (mightNotMatch) { + OS << " std::cerr << \"Cannot yet select: \";\n"; + if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" && + OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" && + OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") { + OS << " N.Val->dump(CurDAG);\n"; + } else { + OS << " unsigned iid = cast(N.getOperand(" + "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n" + << " std::cerr << \"intrinsic %\"<< " + "Intrinsic::getName((Intrinsic::ID)iid);\n"; } - OS << "}\n\n"; + OS << " std::cerr << '\\n';\n" + << " abort();\n"; } + OS << "}\n\n"; } // Emit boilerplate. OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n" << " std::vector Ops(N.Val->op_begin(), N.Val->op_end());\n" - << " AddToQueue(Ops[0], N.getOperand(0)); // Select the chain.\n\n" + << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n" << " // Select the flag operand.\n" << " if (Ops.back().getValueType() == MVT::Flag)\n" - << " AddToQueue(Ops.back(), Ops.back());\n" + << " Select(Ops.back(), Ops.back());\n" << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n" << " std::vector VTs;\n" << " VTs.push_back(MVT::Other);\n" << " VTs.push_back(MVT::Flag);\n" - << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], " - "Ops.size());\n" - << " ReplaceUses(SDOperand(N.Val, 0), New);\n" - << " ReplaceUses(SDOperand(N.Val, 1), SDOperand(New.Val, 1));\n" + << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n" << " Result = New.getValue(N.ResNo);\n" << " return;\n" << "}\n\n"; @@ -3436,6 +3478,11 @@ << " Result = N;\n" << " return; // Already selected.\n" << " }\n\n" + << " std::map::iterator CGMI = CodeGenMap.find(N);\n" + << " if (CGMI != CodeGenMap.end()) {\n" + << " Result = CGMI->second;\n" + << " return;\n" + << " }\n\n" << " switch (N.getOpcode()) {\n" << " default: break;\n" << " case ISD::EntryToken: // These leaves remain the same.\n" @@ -3452,18 +3499,96 @@ << " }\n" << " case ISD::AssertSext:\n" << " case ISD::AssertZext: {\n" - << " AddToQueue(Result, N.getOperand(0));\n" - << " ReplaceUses(N, Result);\n" + << " SDOperand Tmp0;\n" + << " Select(Tmp0, N.getOperand(0));\n" + << " if (!N.Val->hasOneUse())\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " + << "Tmp0.Val, Tmp0.ResNo);\n" + << " Result = Tmp0;\n" << " return;\n" << " }\n" << " case ISD::TokenFactor:\n" - << " case ISD::CopyFromReg:\n" - << " case ISD::CopyToReg: {\n" - << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" - << " SDOperand Dummy;\n" - << " AddToQueue(Dummy, N.getOperand(i));\n" + << " if (N.getNumOperands() == 2) {\n" + << " SDOperand Op0, Op1;\n" + << " Select(Op0, N.getOperand(0));\n" + << " Select(Op1, N.getOperand(1));\n" + << " Result = \n" + << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " + << "Result.Val, Result.ResNo);\n" + << " } else {\n" + << " std::vector Ops;\n" + << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" + << " SDOperand Val;\n" + << " Select(Val, N.getOperand(i));\n" + << " Ops.push_back(Val);\n" + << " }\n" + << " Result = \n" + << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " + << "Result.Val, Result.ResNo);\n" << " }\n" + << " return;\n" + << " case ISD::CopyFromReg: {\n" + << " SDOperand Chain;\n" + << " Select(Chain, N.getOperand(0));\n" + << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" + << " MVT::ValueType VT = N.Val->getValueType(0);\n" + << " if (N.Val->getNumValues() == 2) {\n" + << " if (Chain == N.getOperand(0)) {\n" + << " Result = N; // No change\n" + << " return;\n" + << " }\n" + << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " + << "New.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " + << "New.Val, 1);\n" + << " Result = New.getValue(N.ResNo);\n" + << " return;\n" + << " } else {\n" + << " SDOperand Flag;\n" + << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n" + << " if (Chain == N.getOperand(0) &&\n" + << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n" + << " Result = N; // No change\n" + << " return;\n" + << " }\n" + << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " + << "New.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " + << "New.Val, 1);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, " + << "New.Val, 2);\n" + << " Result = New.getValue(N.ResNo);\n" + << " return;\n" + << " }\n" + << " }\n" + << " case ISD::CopyToReg: {\n" + << " SDOperand Chain;\n" + << " Select(Chain, N.getOperand(0));\n" + << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" + << " SDOperand Val;\n" + << " Select(Val, N.getOperand(2));\n" << " Result = N;\n" + << " if (N.Val->getNumValues() == 1) {\n" + << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n" + << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " + << "Result.Val, 0);\n" + << " } else {\n" + << " SDOperand Flag(0, 0);\n" + << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n" + << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n" + << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n" + << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " + << "Result.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " + << "Result.Val, 1);\n" + << " Result = Result.getValue(N.ResNo);\n" + << " }\n" << " return;\n" << " }\n" << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n"; @@ -3475,48 +3600,9 @@ CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end(); PBOI != E; ++PBOI) { const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first); - const std::string &OpName = PBOI->first->getName(); - // Potentially multiple versions of select for this opcode. One for each - // ValueType of the node (or its first true operand if it doesn't produce a - // result. - std::map >::iterator OpVTI = - OpcodeVTMap.find(OpName); - std::vector &OpVTs = OpVTI->second; - OS << " case " << OpcodeInfo.getEnumName() << ": {\n"; - if (OpVTs.size() == 1) { - std::string &VTStr = OpVTs[0]; - OS << " Select_" << OpName - << (VTStr != "" ? "_" : "") << VTStr << "(Result, N);\n"; - } else { - if (OpcodeInfo.getNumResults()) - OS << " MVT::ValueType NVT = N.Val->getValueType(0);\n"; - else if (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain)) - OS << " MVT::ValueType NVT = (N.getNumOperands() > 1) ?" - << " N.getOperand(1).Val->getValueType(0) : MVT::isVoid;\n"; - else - OS << " MVT::ValueType NVT = (N.getNumOperands() > 0) ?" - << " N.getOperand(0).Val->getValueType(0) : MVT::isVoid;\n"; - int ElseCase = -1; - bool First = true; - for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) { - std::string &VTStr = OpVTs[i]; - if (VTStr == "") { - ElseCase = i; - continue; - } - OS << (First ? " if" : " else if") - << " (NVT == MVT::" << VTStr << ")\n" - << " Select_" << OpName - << "_" << VTStr << "(Result, N);\n"; - First = false; - } - if (ElseCase != -1) - OS << " else\n" << " Select_" << OpName << "(Result, N);\n"; - else - OS << " else\n" << " break;\n"; - } - OS << " return;\n"; - OS << " }\n"; + OS << " case " << OpcodeInfo.getEnumName() << ": " + << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ') + << "Select_" << PBOI->first->getName() << "(Result, N); return;\n"; } OS << " } // end of big switch.\n\n" @@ -3547,93 +3633,112 @@ OS << "#if defined(__GNUC__) && \\\n"; OS << " ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))\n"; OS << "#define NOINLINE __attribute__((noinline))\n"; - OS << "#else\n"; - OS << "#define NOINLINE\n"; OS << "#endif\n\n"; - OS << "// Instruction selector priority queue:\n" - << "std::vector ISelQueue;\n"; - OS << "/// Keep track of nodes which have already been added to queue.\n" - << "unsigned char *ISelQueued;\n"; - OS << "/// Keep track of nodes which have already been selected.\n" - << "unsigned char *ISelSelected;\n"; - OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n" - << "std::vector ISelKilled;\n\n"; - - OS << "/// Sorting functions for the selection queue.\n" - << "struct isel_sort : public std::binary_function" - << " {\n" - << " bool operator()(const SDNode* left, const SDNode* right) " - << "const {\n" - << " return (left->getNodeId() > right->getNodeId());\n" - << " }\n" - << "};\n\n"; + OS << "// Instance var to keep track of multiply used nodes that have \n" + << "// already been selected.\n" + << "std::map CodeGenMap;\n"; + + OS << "// Instance var to keep track of mapping of chain generating nodes\n" + << "// and their place handle nodes.\n"; + OS << "std::map HandleMap;\n"; + OS << "// Instance var to keep track of mapping of place handle nodes\n" + << "// and their replacement nodes.\n"; + OS << "std::map ReplaceMap;\n"; + OS << "// Keep track of nodes that are currently being selecte and therefore\n" + << "// should not be folded.\n"; + OS << "std::set InFlightSet;\n"; - OS << "inline void setQueued(int Id) {\n"; - OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n"; - OS << "}\n"; - OS << "inline bool isQueued(int Id) {\n"; - OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n"; - OS << "}\n"; - OS << "inline void setSelected(int Id) {\n"; - OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n"; - OS << "}\n"; - OS << "inline bool isSelected(int Id) {\n"; - OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n"; - OS << "}\n\n"; - - OS << "inline void AddToQueue(SDOperand &Result, SDOperand N) {\n"; - OS << " Result = N;\n"; - OS << " int Id = N.Val->getNodeId();\n"; - OS << " if (Id != -1 && !isQueued(Id)) {\n"; - OS << " ISelQueue.push_back(N.Val);\n"; - OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; - OS << " setQueued(Id);\n"; + OS << "\n"; + OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, " + << "std::set &Visited) {\n"; + OS << " if (found || !Visited.insert(Use).second) return;\n"; + OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n"; + OS << " SDNode *N = Use->getOperand(i).Val;\n"; + OS << " if (N != Def) {\n"; + OS << " findNonImmUse(N, Def, found, Visited);\n"; + OS << " } else {\n"; + OS << " found = true;\n"; + OS << " break;\n"; + OS << " }\n"; OS << " }\n"; - OS << "}\n\n"; + OS << "}\n"; - OS << "inline void RemoveKilled() {\n"; -OS << " unsigned NumKilled = ISelKilled.size();\n"; - OS << " if (NumKilled) {\n"; - OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n"; - OS << " SDNode *Temp = ISelKilled[i];\n"; - OS << " std::remove(ISelQueue.begin(), ISelQueue.end(), Temp);\n"; - OS << " };\n"; - OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; - OS << " ISelKilled.clear();\n"; + OS << "\n"; + OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n"; + OS << " std::set Visited;\n"; + OS << " bool found = false;\n"; + OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n"; + OS << " SDNode *N = Use->getOperand(i).Val;\n"; + OS << " if (N != Def) {\n"; + OS << " findNonImmUse(N, Def, found, Visited);\n"; + OS << " if (found) break;\n"; + OS << " }\n"; OS << " }\n"; - OS << "}\n\n"; + OS << " return found;\n"; + OS << "}\n"; - OS << "inline void ReplaceUses(SDOperand F, SDOperand T) {\n"; - OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n"; - OS << " setSelected(F.Val->getNodeId());\n"; - OS << " RemoveKilled();\n"; - OS << "}\n\n"; + OS << "\n"; + OS << "// AddHandleReplacement - Note the pending replacement node for a\n" + << "// handle node in ReplaceMap.\n"; + OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, " + << "unsigned RNum) {\n"; + OS << " SDOperand N(H, HNum);\n"; + OS << " std::map::iterator HMI = HandleMap.find(N);\n"; + OS << " if (HMI != HandleMap.end()) {\n"; + OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n"; + OS << " HandleMap.erase(N);\n"; + OS << " }\n"; + OS << "}\n"; - OS << "// SelectRoot - Top level entry to DAG isel.\n"; - OS << "SDOperand SelectRoot(SDOperand Root) {\n"; - OS << " SelectRootInit();\n"; - OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n"; - OS << " ISelQueued = new unsigned char[NumBytes];\n"; - OS << " ISelSelected = new unsigned char[NumBytes];\n"; - OS << " memset(ISelQueued, 0, NumBytes);\n"; - OS << " memset(ISelSelected, 0, NumBytes);\n"; OS << "\n"; - OS << " SDOperand ResNode;\n"; - OS << " Select(ResNode, Root);\n"; - OS << " while (!ISelQueue.empty()) {\n"; - OS << " SDOperand Tmp;\n"; - OS << " SDNode *Node = ISelQueue.front();\n"; - OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; - OS << " ISelQueue.pop_back();\n"; - OS << " if (!isSelected(Node->getNodeId()))\n"; - OS << " Select(Tmp, SDOperand(Node, 0));\n"; + OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n"; + OS << "// handles.Some handles do not yet have replacements because the\n"; + OS << "// nodes they replacements have only dead readers.\n"; + OS << "void SelectDanglingHandles() {\n"; + OS << " for (std::map::iterator I = " + << "HandleMap.begin(),\n" + << " E = HandleMap.end(); I != E; ++I) {\n"; + OS << " SDOperand N = I->first;\n"; + OS << " SDOperand R;\n"; + OS << " Select(R, N.getValue(0));\n"; + OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n"; OS << " }\n"; + OS << "}\n"; OS << "\n"; - OS << " delete[] ISelQueued;\n"; - OS << " ISelQueued = NULL;\n"; - OS << " delete[] ISelSelected;\n"; - OS << " ISelSelected = NULL;\n"; + OS << "// ReplaceHandles - Replace all the handles with the real target\n"; + OS << "// specific nodes.\n"; + OS << "void ReplaceHandles() {\n"; + OS << " for (std::map::iterator I = " + << "ReplaceMap.begin(),\n" + << " E = ReplaceMap.end(); I != E; ++I) {\n"; + OS << " SDOperand From = I->first;\n"; + OS << " SDOperand To = I->second;\n"; + OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), " + << "E = From.Val->use_end(); UI != E; ++UI) {\n"; + OS << " SDNode *Use = *UI;\n"; + OS << " std::vector Ops;\n"; + OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n"; + OS << " SDOperand O = Use->getOperand(i);\n"; + OS << " if (O.Val == From.Val)\n"; + OS << " Ops.push_back(To);\n"; + OS << " else\n"; + OS << " Ops.push_back(O);\n"; + OS << " }\n"; + OS << " SDOperand U = SDOperand(Use, 0);\n"; + OS << " CurDAG->UpdateNodeOperands(U, Ops);\n"; + OS << " }\n"; + OS << " }\n"; + OS << "}\n"; + + OS << "\n"; + OS << "// SelectRoot - Top level entry to DAG isel.\n"; + OS << "SDOperand SelectRoot(SDOperand N) {\n"; + OS << " SDOperand ResNode;\n"; + OS << " Select(ResNode, N);\n"; + OS << " SelectDanglingHandles();\n"; + OS << " ReplaceHandles();\n"; + OS << " ReplaceMap.clear();\n"; OS << " return ResNode;\n"; OS << "}\n"; From lattner at cs.uiuc.edu Wed Aug 9 11:44:58 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Wed, 9 Aug 2006 11:44:58 -0500 Subject: [llvm-commits] CVS: llvm/utils/TableGen/DAGISelEmitter.cpp Message-ID: <200608091644.k79GiwM7024281@zion.cs.uiuc.edu> Changes in directory llvm/utils/TableGen: DAGISelEmitter.cpp updated: 1.239 -> 1.240 --- Log message: Revert previous patch --- Diffs of the changes: (+398 -503) DAGISelEmitter.cpp | 901 +++++++++++++++++++++++------------------------------ 1 files changed, 398 insertions(+), 503 deletions(-) Index: llvm/utils/TableGen/DAGISelEmitter.cpp diff -u llvm/utils/TableGen/DAGISelEmitter.cpp:1.239 llvm/utils/TableGen/DAGISelEmitter.cpp:1.240 --- llvm/utils/TableGen/DAGISelEmitter.cpp:1.239 Wed Aug 9 11:41:21 2006 +++ llvm/utils/TableGen/DAGISelEmitter.cpp Wed Aug 9 11:44:44 2006 @@ -1829,9 +1829,22 @@ // If this node is commutative, consider the commuted order. if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) { assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!"); + // Don't count children which are actually register references. + unsigned NC = 0; + for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) { + TreePatternNode *Child = N->getChild(i); + if (Child->isLeaf()) + if (DefInit *DI = dynamic_cast(Child->getLeafValue())) { + Record *RR = DI->getDef(); + if (RR->isSubClassOf("Register")) + continue; + } + NC++; + } // Consider the commuted order. - CombineChildVariants(N, ChildVariants[1], ChildVariants[0], - OutVariants, ISE); + if (NC == 2) + CombineChildVariants(N, ChildVariants[1], ChildVariants[0], + OutVariants, ISE); } } @@ -2106,8 +2119,6 @@ // Names of all the folded nodes which produce chains. std::vector > FoldedChains; std::set Duplicates; - /// These nodes are being marked "in-flight" so they cannot be folded. - std::vector InflightNodes; /// GeneratedCode - This is the buffer that we emit code to. The first bool /// indicates whether this is an exit predicate (something that should be @@ -2123,7 +2134,6 @@ std::vector &TargetVTs; std::string ChainName; - bool DoReplace; unsigned TmpNo; unsigned OpcNo; unsigned VTNo; @@ -2154,11 +2164,10 @@ std::vector > &gc, std::set > &gd, std::vector &to, - std::vector &tv, - bool dorep) + std::vector &tv) : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr), GeneratedCode(gc), GeneratedDecl(gd), TargetOpcodes(to), TargetVTs(tv), - DoReplace(dorep), TmpNo(0), OpcNo(0), VTNo(0) {} + TmpNo(0), OpcNo(0), VTNo(0) {} /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo /// if the match fails. At this point, we already know that the opcode for N @@ -2225,24 +2234,14 @@ bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE); bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE); bool EmittedUseCheck = false; - bool EmittedSlctedCheck = false; if (HasChain) { if (NodeHasChain) OpNo = 1; if (!isRoot) { const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator()); - // Not in flight? - emitCheck("InFlightSet.count(" + RootName + ".Val) == 0"); // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); EmittedUseCheck = true; - // hasOneUse() check is not strong enough. If the original node has - // already been selected, it may have been replaced with another. - for (unsigned j = 0; j != CInfo.getNumResults(); j++) - emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + - "))"); - - EmittedSlctedCheck = true; if (NodeHasChain) { // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node // has a chain use. @@ -2280,14 +2279,8 @@ PInfo.hasProperty(SDNodeInfo::SDNPHasChain) || PInfo.hasProperty(SDNodeInfo::SDNPInFlag) || PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag)) - if (PInfo.getNumOperands() > 1) { - emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName + - ".Val)"); - } else { - emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" + - "isNonImmUse(" + ParentName + ".Val, " + RootName + - ".Val))"); - } + emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName + + ".Val)"); } } @@ -2317,12 +2310,6 @@ // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); } - if (!EmittedSlctedCheck) - // hasOneUse() check is not strong enough. If the original node has - // already been selected, it may have been replaced with another. - for (unsigned j = 0; j < CInfo.getNumResults(); j++) - emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) + - "))"); } for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) { @@ -2479,30 +2466,14 @@ for (unsigned i = 0; i < NumRes; ++i) emitDecl("CPTmp" + utostr(i+ResNo)); - std::string Code = "bool Match = " + Fn + "(" + Val; + std::string Code = Fn + "(" + Val; for (unsigned i = 0; i < NumRes; i++) Code += ", CPTmp" + utostr(i + ResNo); - emitCode(Code + ");"); - if (InflightNodes.size()) { - // Remove the in-flight nodes if the ComplexPattern does not match! - emitCode("if (!Match) {"); - for (std::vector::iterator AI = InflightNodes.begin(), - AE = InflightNodes.end(); AI != AE; ++AI) - emitCode(" SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " + - *AI + ".Val);"); - emitCode("}"); - } + emitCheck(Code + ")"); - emitCheck("Match"); - - for (unsigned i = 0; i < NumRes; ++i) { - emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, CPTmp" + - utostr(i+ResNo) + ".Val);"); - InflightNodes.push_back("CPTmp" + utostr(i+ResNo)); - } for (unsigned i = 0; i < NumRes; ++i) { emitDecl("Tmp" + utostr(i+ResNo)); - emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" + + emitCode("AddToQueue(Tmp" + utostr(i+ResNo) + ", CPTmp" + utostr(i+ResNo) + ");"); } @@ -2514,12 +2485,12 @@ if (LikeLeaf) emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";"); else { - emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");"); - } - - if (isRoot && N->isLeaf()) { - emitCode("Result = Tmp" + utostr(ResNo) + ";"); - emitCode("return;"); + emitCode("AddToQueue(Tmp" + utostr(ResNo) + ", " + Val + ");"); + if (isRoot && N->isLeaf()) { + emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); + emitCode("Result = Tmp" + utostr(ResNo) + ";"); + emitCode("return;"); + } } } // Add Tmp to VariableMap, so that we don't multiply select this @@ -2614,22 +2585,6 @@ } } - // Make sure these operands which would be selected won't be folded while - // the isel traverses the DAG upward. - for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) { - TreePatternNode *Child = EmitOrder[i].second; - if (!Child->getName().empty()) { - std::string &Val = VariableMap[Child->getName()]; - assert(!Val.empty() && - "Variable referenced but not defined and not caught earlier!"); - if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) { - emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, " + - Val + ".Val);"); - InflightNodes.push_back(Val); - } - } - } - // Emit all of the operands. std::vector > NumTemps(EmitOrder.size()); for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) { @@ -2649,20 +2604,12 @@ // Emit all the chain and CopyToReg stuff. bool ChainEmitted = NodeHasChain; if (NodeHasChain) - emitCode("Select(" + ChainName + ", " + ChainName + ");"); + emitCode("AddToQueue(" + ChainName + ", " + ChainName + ");"); if (NodeHasInFlag || HasImpInputs) EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true); if (NodeHasOptInFlag) { emitCode("if (HasInFlag)"); - emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));"); - } - - if (isRoot) { - // The operands have been selected. Remove them from InFlightSet. - for (std::vector::iterator AI = InflightNodes.begin(), - AE = InflightNodes.end(); AI != AE; ++AI) - emitCode("SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " + - *AI + ".Val);"); + emitCode(" AddToQueue(InFlag, N.getOperand(N.getNumOperands()-1));"); } unsigned NumResults = Inst.getNumResults(); @@ -2714,7 +2661,7 @@ emitCode("for (unsigned i = 2, e = N.getNumOperands(); " "i != e; ++i) {"); emitCode(" SDOperand VarOp(0, 0);"); - emitCode(" Select(VarOp, N.getOperand(i));"); + emitCode(" AddToQueue(VarOp, N.getOperand(i));"); emitCode(" Ops.push_back(VarOp);"); emitCode("}"); } @@ -2736,7 +2683,7 @@ } if (HasVarOps) - Code += ", Ops"; + Code += ", &Ops[0], Ops.size()"; else if (NodeHasOptInFlag) Code = "HasInFlag ? " + Code + ", InFlag) : " + Code; @@ -2757,50 +2704,35 @@ return std::make_pair(1, ResNo); for (unsigned i = 0; i < NumResults; i++) - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + - utostr(i) + ", ResNode, " + utostr(i) + ");"); + emitCode("ReplaceUses(SDOperand(N.Val, " + + utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));"); if (NodeHasOutFlag) emitCode("InFlag = SDOperand(ResNode, " + utostr(NumResults + (unsigned)NodeHasChain) + ");"); if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) { - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " - "0, ResNode, 0);"); + emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));"); NumResults = 1; } - if (InputHasChain) { - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + - utostr(PatResults) + ", " + ChainName + ".Val, " + - ChainName + ".ResNo" + ");"); - if (DoReplace) - emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " + - utostr(PatResults) + ", " + ChainName + ".Val, " + - ChainName + ".ResNo" + ");"); - } + if (InputHasChain) + emitCode("ReplaceUses(SDOperand(N.Val, " + + utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, " + + ChainName + ".ResNo" + "));"); if (FoldedChains.size() > 0) { std::string Code; for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " + + emitCode("ReplaceUses(SDOperand(" + FoldedChains[j].first + ".Val, " + - utostr(FoldedChains[j].second) + ", ResNode, " + - utostr(NumResults) + ");"); - - for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) { - std::string Code = - FoldedChains[j].first + ".Val, " + - utostr(FoldedChains[j].second) + ", "; - emitCode("AddHandleReplacement(" + Code + "ResNode, " + - utostr(NumResults) + ");"); - } + utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " + + utostr(NumResults) + "));"); } if (NodeHasOutFlag) - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + - utostr(PatResults + (unsigned)InputHasChain) + - ", InFlag.Val, InFlag.ResNo);"); + emitCode("ReplaceUses(SDOperand(N.Val, " + + utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);"); // User does not expect the instruction would produce a chain! bool AddedChain = NodeHasChain && !InputHasChain; @@ -2857,8 +2789,7 @@ if (NodeHasInFlag || HasImpInputs) Code += ", InFlag"; emitCode(Code + ");"); - emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo" - ", ResNode, 0);"); + emitCode(" ReplaceUses(N, SDOperand(ResNode, 0));"); emitCode(" Result = SDOperand(ResNode, 0);"); emitCode("}"); } @@ -2876,9 +2807,7 @@ emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName() + "(Tmp" + utostr(OpVal) + ".Val);"); if (isRoot) { - emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val," - "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" + - utostr(ResNo) + ".ResNo);"); + emitCode("ReplaceUses(N, Tmp" + utostr(ResNo) + ");"); emitCode("Result = Tmp" + utostr(ResNo) + ";"); emitCode("return;"); } @@ -2895,13 +2824,15 @@ /// 'Pat' may be missing types. If we find an unresolved type to add a check /// for, this returns true otherwise false if Pat has all types. bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other, - const std::string &Prefix) { + const std::string &Prefix, bool isRoot = false) { // Did we find one? if (Pat->getExtTypes() != Other->getExtTypes()) { // Move a type over from 'other' to 'pat'. Pat->setTypes(Other->getExtTypes()); - emitCheck(Prefix + ".Val->getValueType(0) == " + - getName(Pat->getTypeNum(0))); + // The top level node type is checked outside of the select function. + if (!isRoot) + emitCheck(Prefix + ".Val->getValueType(0) == " + + getName(Pat->getTypeNum(0))); return true; } @@ -2940,7 +2871,7 @@ if (RR->isSubClassOf("Register")) { MVT::ValueType RVT = getRegisterValueType(RR, T); if (RVT == MVT::Flag) { - emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");"); + emitCode("AddToQueue(InFlag, " + RootName + utostr(OpNo) + ");"); } else { if (!ChainEmitted) { emitDecl("Chain"); @@ -2948,7 +2879,7 @@ ChainName = "Chain"; ChainEmitted = true; } - emitCode("Select(" + RootName + utostr(OpNo) + ", " + + emitCode("AddToQueue(" + RootName + utostr(OpNo) + ", " + RootName + utostr(OpNo) + ");"); emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName + ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) + @@ -2963,7 +2894,7 @@ } if (HasInFlag) - emitCode("Select(InFlag, " + RootName + + emitCode("AddToQueue(InFlag, " + RootName + ".getOperand(" + utostr(OpNo) + "));"); } @@ -3009,13 +2940,11 @@ std::vector > &GeneratedCode, std::set > &GeneratedDecl, std::vector &TargetOpcodes, - std::vector &TargetVTs, - bool DoReplace) { + std::vector &TargetVTs) { PatternCodeEmitter Emitter(*this, Pattern.getPredicates(), Pattern.getSrcPattern(), Pattern.getDstPattern(), GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs, - DoReplace); + TargetOpcodes, TargetVTs); // Emit the matcher, capturing named arguments in VariableMap. bool FoundChain = false; @@ -3055,7 +2984,7 @@ // Insert a check for an unresolved type and add it to the tree. If we find // an unresolved type to add a check for, this returns true and we iterate, // otherwise we are done. - } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N")); + } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true)); Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/); delete Pat; @@ -3142,7 +3071,9 @@ OS << std::string(Indent, ' ') << "// Pattern complexity = " << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity << " cost = " - << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n"; + << getResultPatternCost(Pattern.getDstPattern(), *this) + << " size = " + << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n"; } EmitPatterns(Other, Indent, OS); return; @@ -3240,7 +3171,12 @@ } } } - + + // For each opcode, there might be multiple select functions, one per + // ValueType of the node (or its first operand if it doesn't produce a + // non-chain result. + std::map > OpcodeVTMap; + // Emit one Select_* method for each top-level opcode. We do this instead of // emitting one giant switch statement to support compilers where this will // result in the recursive functions taking less stack space. @@ -3249,223 +3185,245 @@ E = PatternsByOpcode.end(); PBOI != E; ++PBOI) { const std::string &OpName = PBOI->first->getName(); const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first); - bool OptSlctOrder = - (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) && - OpcodeInfo.getNumResults() > 0); - std::vector &Patterns = PBOI->second; - assert(!Patterns.empty() && "No patterns but map has entry?"); - + std::vector &PatternsOfOp = PBOI->second; + assert(!PatternsOfOp.empty() && "No patterns but map has entry?"); + // We want to emit all of the matching code now. However, we want to emit // the matches in order of minimal cost. Sort the patterns so the least // cost one is at the start. - std::stable_sort(Patterns.begin(), Patterns.end(), + std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(), PatternSortingPredicate(*this)); - typedef std::vector > CodeList; - typedef std::vector >::iterator CodeListI; - - std::vector > CodeForPatterns; - std::vector > PatternOpcodes; - std::vector > PatternVTs; - std::vector > > PatternDecls; - std::set > AllGenDecls; - for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { - CodeList GeneratedCode; - std::set > GeneratedDecl; - std::vector TargetOpcodes; - std::vector TargetVTs; - GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs, OptSlctOrder); - for (std::set >::iterator - si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) - AllGenDecls.insert(*si); - CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode)); - PatternDecls.push_back(GeneratedDecl); - PatternOpcodes.push_back(TargetOpcodes); - PatternVTs.push_back(TargetVTs); + // Split them into groups by type. + std::map > PatternsByType; + for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) { + PatternToMatch *Pat = PatternsOfOp[i]; + TreePatternNode *SrcPat = Pat->getSrcPattern(); + if (OpcodeInfo.getNumResults() == 0 && SrcPat->getNumChildren() > 0) + SrcPat = SrcPat->getChild(0); + MVT::ValueType VT = SrcPat->getTypeNum(0); + std::map >::iterator TI = + PatternsByType.find(VT); + if (TI != PatternsByType.end()) + TI->second.push_back(Pat); + else { + std::vector PVec; + PVec.push_back(Pat); + PatternsByType.insert(std::make_pair(VT, PVec)); + } } + + for (std::map >::iterator + II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE; + ++II) { + MVT::ValueType OpVT = II->first; + std::vector &Patterns = II->second; + typedef std::vector > CodeList; + typedef std::vector >::iterator CodeListI; - // Scan the code to see if all of the patterns are reachable and if it is - // possible that the last one might not match. - bool mightNotMatch = true; - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - mightNotMatch = false; - - for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) { - if (GeneratedCode[j].first) { // predicate. - mightNotMatch = true; - break; - } + std::vector > CodeForPatterns; + std::vector > PatternOpcodes; + std::vector > PatternVTs; + std::vector > > PatternDecls; + std::set > AllGenDecls; + for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { + CodeList GeneratedCode; + std::set > GeneratedDecl; + std::vector TargetOpcodes; + std::vector TargetVTs; + GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, + TargetOpcodes, TargetVTs); + for (std::set >::iterator + si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) + AllGenDecls.insert(*si); + CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode)); + PatternDecls.push_back(GeneratedDecl); + PatternOpcodes.push_back(TargetOpcodes); + PatternVTs.push_back(TargetVTs); } + + // Scan the code to see if all of the patterns are reachable and if it is + // possible that the last one might not match. + bool mightNotMatch = true; + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + mightNotMatch = false; + + for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) { + if (GeneratedCode[j].first) { // predicate. + mightNotMatch = true; + break; + } + } - // If this pattern definitely matches, and if it isn't the last one, the - // patterns after it CANNOT ever match. Error out. - if (mightNotMatch == false && i != CodeForPatterns.size()-1) { - std::cerr << "Pattern '"; - CodeForPatterns[i+1].first->getSrcPattern()->print(OS); - std::cerr << "' is impossible to select!\n"; - exit(1); - } - } - - // Factor target node emission code (emitted by EmitResultCode) into - // separate functions. Uniquing and share them among all instruction - // selection routines. - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - std::vector &TargetOpcodes = PatternOpcodes[i]; - std::vector &TargetVTs = PatternVTs[i]; - std::set > Decls = PatternDecls[i]; - int CodeSize = (int)GeneratedCode.size(); - int LastPred = -1; - for (int j = CodeSize-1; j >= 0; --j) { - if (GeneratedCode[j].first) { - LastPred = j; - break; + // If this pattern definitely matches, and if it isn't the last one, the + // patterns after it CANNOT ever match. Error out. + if (mightNotMatch == false && i != CodeForPatterns.size()-1) { + std::cerr << "Pattern '"; + CodeForPatterns[i+1].first->getSrcPattern()->print(std::cerr); + std::cerr << "' is impossible to select!\n"; + exit(1); } } - std::string CalleeDecls; - std::string CalleeCode = "(SDOperand &Result, SDOperand &N"; - std::string CallerCode = "(Result, N"; - for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) { - CalleeCode += ", unsigned Opc" + utostr(j); - CallerCode += ", " + TargetOpcodes[j]; - } - for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) { - CalleeCode += ", MVT::ValueType VT" + utostr(j); - CallerCode += ", " + TargetVTs[j]; - } - for (std::set >::iterator - I = Decls.begin(), E = Decls.end(); I != E; ++I) { - std::string Name = I->second; - if (I->first == 0) { - if (Name == "InFlag" || - (Name.size() > 3 && - Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) { - CalleeDecls += " SDOperand " + Name + "(0, 0);\n"; - continue; + // Factor target node emission code (emitted by EmitResultCode) into + // separate functions. Uniquing and share them among all instruction + // selection routines. + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + std::vector &TargetOpcodes = PatternOpcodes[i]; + std::vector &TargetVTs = PatternVTs[i]; + std::set > Decls = PatternDecls[i]; + int CodeSize = (int)GeneratedCode.size(); + int LastPred = -1; + for (int j = CodeSize-1; j >= 0; --j) { + if (GeneratedCode[j].first) { + LastPred = j; + break; } - CalleeCode += ", SDOperand &" + Name; - CallerCode += ", " + Name; - } else if (I->first == 1) { - if (Name == "ResNode") { - CalleeDecls += " SDNode *" + Name + " = NULL;\n"; - continue; + } + + std::string CalleeDecls; + std::string CalleeCode = "(SDOperand &Result, const SDOperand &N"; + std::string CallerCode = "(Result, N"; + for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) { + CalleeCode += ", unsigned Opc" + utostr(j); + CallerCode += ", " + TargetOpcodes[j]; + } + for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) { + CalleeCode += ", MVT::ValueType VT" + utostr(j); + CallerCode += ", " + TargetVTs[j]; + } + for (std::set >::iterator + I = Decls.begin(), E = Decls.end(); I != E; ++I) { + std::string Name = I->second; + if (I->first == 0) { + if (Name == "InFlag" || + (Name.size() > 3 && + Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) { + CalleeDecls += " SDOperand " + Name + "(0, 0);\n"; + continue; + } + CalleeCode += ", SDOperand &" + Name; + CallerCode += ", " + Name; + } else if (I->first == 1) { + if (Name == "ResNode") { + CalleeDecls += " SDNode *" + Name + " = NULL;\n"; + continue; + } + CalleeCode += ", SDNode *" + Name; + CallerCode += ", " + Name; + } else { + CalleeCode += ", bool " + Name; + CallerCode += ", " + Name; } - CalleeCode += ", SDNode *" + Name; - CallerCode += ", " + Name; - } else { - CalleeCode += ", bool " + Name; - CallerCode += ", " + Name; } - } - CallerCode += ");"; - CalleeCode += ") "; - // Prevent emission routines from being inlined to reduce selection - // routines stack frame sizes. - CalleeCode += "NOINLINE "; - CalleeCode += "{\n" + CalleeDecls; - for (int j = LastPred+1; j < CodeSize; ++j) - CalleeCode += " " + GeneratedCode[j].second + '\n'; - for (int j = LastPred+1; j < CodeSize; ++j) - GeneratedCode.pop_back(); - CalleeCode += "}\n"; - - // Uniquing the emission routines. - unsigned EmitFuncNum; - std::map::iterator EFI = - EmitFunctions.find(CalleeCode); - if (EFI != EmitFunctions.end()) { - EmitFuncNum = EFI->second; - } else { - EmitFuncNum = EmitFunctions.size(); - EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum)); - OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode; - } - - // Replace the emission code within selection routines with calls to the - // emission functions. - CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode; - GeneratedCode.push_back(std::make_pair(false, CallerCode)); - GeneratedCode.push_back(std::make_pair(false, "return;")); - } - - // Print function. - OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n"; - if (OptSlctOrder) { - OS << " if (N.ResNo == " << OpcodeInfo.getNumResults() - << " && N.getValue(0).hasOneUse()) {\n" - << " SDOperand Dummy = " - << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " - << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, " - << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" - << " Result = Dummy;\n" - << " return;\n" - << " }\n"; - } - - // Print all declarations. - for (std::set >::iterator - I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I) - if (I->first == 0) - OS << " SDOperand " << I->second << "(0, 0);\n"; - else if (I->first == 1) - OS << " SDNode *" << I->second << " = NULL;\n"; - else - OS << " bool " << I->second << " = false;\n"; + CallerCode += ");"; + CalleeCode += ") "; + // Prevent emission routines from being inlined to reduce selection + // routines stack frame sizes. + CalleeCode += "NOINLINE "; + CalleeCode += "{\n" + CalleeDecls; + for (int j = LastPred+1; j < CodeSize; ++j) + CalleeCode += " " + GeneratedCode[j].second + '\n'; + for (int j = LastPred+1; j < CodeSize; ++j) + GeneratedCode.pop_back(); + CalleeCode += "}\n"; + + // Uniquing the emission routines. + unsigned EmitFuncNum; + std::map::iterator EFI = + EmitFunctions.find(CalleeCode); + if (EFI != EmitFunctions.end()) { + EmitFuncNum = EFI->second; + } else { + EmitFuncNum = EmitFunctions.size(); + EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum)); + OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode; + } + + // Replace the emission code within selection routines with calls to the + // emission functions. + CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode; + GeneratedCode.push_back(std::make_pair(false, CallerCode)); + GeneratedCode.push_back(std::make_pair(false, "return;")); + } + + // Print function. + std::string OpVTStr = (OpVT != MVT::isVoid && OpVT != MVT::iPTR) + ? getEnumName(OpVT).substr(5) : "" ; + std::map >::iterator OpVTI = + OpcodeVTMap.find(OpName); + if (OpVTI == OpcodeVTMap.end()) { + std::vector VTSet; + VTSet.push_back(OpVTStr); + OpcodeVTMap.insert(std::make_pair(OpName, VTSet)); + } else + OpVTI->second.push_back(OpVTStr); - // Loop through and reverse all of the CodeList vectors, as we will be - // accessing them from their logical front, but accessing the end of a - // vector is more efficient. - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - std::reverse(GeneratedCode.begin(), GeneratedCode.end()); - } + OS << "void Select_" << OpName << (OpVTStr != "" ? "_" : "") + << OpVTStr << "(SDOperand &Result, const SDOperand &N) {\n"; + + // Print all declarations. + for (std::set >::iterator + I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I) + if (I->first == 0) + OS << " SDOperand " << I->second << "(0, 0);\n"; + else if (I->first == 1) + OS << " SDNode *" << I->second << " = NULL;\n"; + else + OS << " bool " << I->second << " = false;\n"; + + // Loop through and reverse all of the CodeList vectors, as we will be + // accessing them from their logical front, but accessing the end of a + // vector is more efficient. + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + std::reverse(GeneratedCode.begin(), GeneratedCode.end()); + } - // Next, reverse the list of patterns itself for the same reason. - std::reverse(CodeForPatterns.begin(), CodeForPatterns.end()); + // Next, reverse the list of patterns itself for the same reason. + std::reverse(CodeForPatterns.begin(), CodeForPatterns.end()); - // Emit all of the patterns now, grouped together to share code. - EmitPatterns(CodeForPatterns, 2, OS); + // Emit all of the patterns now, grouped together to share code. + EmitPatterns(CodeForPatterns, 2, OS); - // If the last pattern has predicates (which could fail) emit code to catch - // the case where nothing handles a pattern. - if (mightNotMatch) { - OS << " std::cerr << \"Cannot yet select: \";\n"; - if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" && - OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" && - OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") { - OS << " N.Val->dump(CurDAG);\n"; - } else { - OS << " unsigned iid = cast(N.getOperand(" - "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n" - << " std::cerr << \"intrinsic %\"<< " - "Intrinsic::getName((Intrinsic::ID)iid);\n"; + // If the last pattern has predicates (which could fail) emit code to catch + // the case where nothing handles a pattern. + if (mightNotMatch) { + OS << " std::cerr << \"Cannot yet select: \";\n"; + if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" && + OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" && + OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") { + OS << " N.Val->dump(CurDAG);\n"; + } else { + OS << " unsigned iid = cast(N.getOperand(" + "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n" + << " std::cerr << \"intrinsic %\"<< " + "Intrinsic::getName((Intrinsic::ID)iid);\n"; + } + OS << " std::cerr << '\\n';\n" + << " abort();\n"; } - OS << " std::cerr << '\\n';\n" - << " abort();\n"; + OS << "}\n\n"; } - OS << "}\n\n"; } // Emit boilerplate. OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n" << " std::vector Ops(N.Val->op_begin(), N.Val->op_end());\n" - << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n" + << " AddToQueue(Ops[0], N.getOperand(0)); // Select the chain.\n\n" << " // Select the flag operand.\n" << " if (Ops.back().getValueType() == MVT::Flag)\n" - << " Select(Ops.back(), Ops.back());\n" + << " AddToQueue(Ops.back(), Ops.back());\n" << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n" << " std::vector VTs;\n" << " VTs.push_back(MVT::Other);\n" << " VTs.push_back(MVT::Flag);\n" - << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n" + << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], " + "Ops.size());\n" + << " ReplaceUses(SDOperand(N.Val, 0), New);\n" + << " ReplaceUses(SDOperand(N.Val, 1), SDOperand(New.Val, 1));\n" << " Result = New.getValue(N.ResNo);\n" << " return;\n" << "}\n\n"; @@ -3478,11 +3436,6 @@ << " Result = N;\n" << " return; // Already selected.\n" << " }\n\n" - << " std::map::iterator CGMI = CodeGenMap.find(N);\n" - << " if (CGMI != CodeGenMap.end()) {\n" - << " Result = CGMI->second;\n" - << " return;\n" - << " }\n\n" << " switch (N.getOpcode()) {\n" << " default: break;\n" << " case ISD::EntryToken: // These leaves remain the same.\n" @@ -3499,96 +3452,18 @@ << " }\n" << " case ISD::AssertSext:\n" << " case ISD::AssertZext: {\n" - << " SDOperand Tmp0;\n" - << " Select(Tmp0, N.getOperand(0));\n" - << " if (!N.Val->hasOneUse())\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " - << "Tmp0.Val, Tmp0.ResNo);\n" - << " Result = Tmp0;\n" + << " AddToQueue(Result, N.getOperand(0));\n" + << " ReplaceUses(N, Result);\n" << " return;\n" << " }\n" << " case ISD::TokenFactor:\n" - << " if (N.getNumOperands() == 2) {\n" - << " SDOperand Op0, Op1;\n" - << " Select(Op0, N.getOperand(0));\n" - << " Select(Op1, N.getOperand(1));\n" - << " Result = \n" - << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " - << "Result.Val, Result.ResNo);\n" - << " } else {\n" - << " std::vector Ops;\n" - << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" - << " SDOperand Val;\n" - << " Select(Val, N.getOperand(i));\n" - << " Ops.push_back(Val);\n" - << " }\n" - << " Result = \n" - << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, " - << "Result.Val, Result.ResNo);\n" - << " }\n" - << " return;\n" - << " case ISD::CopyFromReg: {\n" - << " SDOperand Chain;\n" - << " Select(Chain, N.getOperand(0));\n" - << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" - << " MVT::ValueType VT = N.Val->getValueType(0);\n" - << " if (N.Val->getNumValues() == 2) {\n" - << " if (Chain == N.getOperand(0)) {\n" - << " Result = N; // No change\n" - << " return;\n" - << " }\n" - << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "New.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " - << "New.Val, 1);\n" - << " Result = New.getValue(N.ResNo);\n" - << " return;\n" - << " } else {\n" - << " SDOperand Flag;\n" - << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n" - << " if (Chain == N.getOperand(0) &&\n" - << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n" - << " Result = N; // No change\n" - << " return;\n" - << " }\n" - << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "New.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " - << "New.Val, 1);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, " - << "New.Val, 2);\n" - << " Result = New.getValue(N.ResNo);\n" - << " return;\n" - << " }\n" - << " }\n" + << " case ISD::CopyFromReg:\n" << " case ISD::CopyToReg: {\n" - << " SDOperand Chain;\n" - << " Select(Chain, N.getOperand(0));\n" - << " unsigned Reg = cast(N.getOperand(1))->getReg();\n" - << " SDOperand Val;\n" - << " Select(Val, N.getOperand(2));\n" - << " Result = N;\n" - << " if (N.Val->getNumValues() == 1) {\n" - << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n" - << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "Result.Val, 0);\n" - << " } else {\n" - << " SDOperand Flag(0, 0);\n" - << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n" - << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n" - << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n" - << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, " - << "Result.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, " - << "Result.Val, 1);\n" - << " Result = Result.getValue(N.ResNo);\n" + << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n" + << " SDOperand Dummy;\n" + << " AddToQueue(Dummy, N.getOperand(i));\n" << " }\n" + << " Result = N;\n" << " return;\n" << " }\n" << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n"; @@ -3600,9 +3475,48 @@ CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end(); PBOI != E; ++PBOI) { const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first); - OS << " case " << OpcodeInfo.getEnumName() << ": " - << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ') - << "Select_" << PBOI->first->getName() << "(Result, N); return;\n"; + const std::string &OpName = PBOI->first->getName(); + // Potentially multiple versions of select for this opcode. One for each + // ValueType of the node (or its first true operand if it doesn't produce a + // result. + std::map >::iterator OpVTI = + OpcodeVTMap.find(OpName); + std::vector &OpVTs = OpVTI->second; + OS << " case " << OpcodeInfo.getEnumName() << ": {\n"; + if (OpVTs.size() == 1) { + std::string &VTStr = OpVTs[0]; + OS << " Select_" << OpName + << (VTStr != "" ? "_" : "") << VTStr << "(Result, N);\n"; + } else { + if (OpcodeInfo.getNumResults()) + OS << " MVT::ValueType NVT = N.Val->getValueType(0);\n"; + else if (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain)) + OS << " MVT::ValueType NVT = (N.getNumOperands() > 1) ?" + << " N.getOperand(1).Val->getValueType(0) : MVT::isVoid;\n"; + else + OS << " MVT::ValueType NVT = (N.getNumOperands() > 0) ?" + << " N.getOperand(0).Val->getValueType(0) : MVT::isVoid;\n"; + int ElseCase = -1; + bool First = true; + for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) { + std::string &VTStr = OpVTs[i]; + if (VTStr == "") { + ElseCase = i; + continue; + } + OS << (First ? " if" : " else if") + << " (NVT == MVT::" << VTStr << ")\n" + << " Select_" << OpName + << "_" << VTStr << "(Result, N);\n"; + First = false; + } + if (ElseCase != -1) + OS << " else\n" << " Select_" << OpName << "(Result, N);\n"; + else + OS << " else\n" << " break;\n"; + } + OS << " return;\n"; + OS << " }\n"; } OS << " } // end of big switch.\n\n" @@ -3633,112 +3547,93 @@ OS << "#if defined(__GNUC__) && \\\n"; OS << " ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))\n"; OS << "#define NOINLINE __attribute__((noinline))\n"; + OS << "#else\n"; + OS << "#define NOINLINE\n"; OS << "#endif\n\n"; - OS << "// Instance var to keep track of multiply used nodes that have \n" - << "// already been selected.\n" - << "std::map CodeGenMap;\n"; - - OS << "// Instance var to keep track of mapping of chain generating nodes\n" - << "// and their place handle nodes.\n"; - OS << "std::map HandleMap;\n"; - OS << "// Instance var to keep track of mapping of place handle nodes\n" - << "// and their replacement nodes.\n"; - OS << "std::map ReplaceMap;\n"; - OS << "// Keep track of nodes that are currently being selecte and therefore\n" - << "// should not be folded.\n"; - OS << "std::set InFlightSet;\n"; + OS << "// Instruction selector priority queue:\n" + << "std::vector ISelQueue;\n"; + OS << "/// Keep track of nodes which have already been added to queue.\n" + << "unsigned char *ISelQueued;\n"; + OS << "/// Keep track of nodes which have already been selected.\n" + << "unsigned char *ISelSelected;\n"; + OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n" + << "std::vector ISelKilled;\n\n"; + + OS << "/// Sorting functions for the selection queue.\n" + << "struct isel_sort : public std::binary_function" + << " {\n" + << " bool operator()(const SDNode* left, const SDNode* right) " + << "const {\n" + << " return (left->getNodeId() > right->getNodeId());\n" + << " }\n" + << "};\n\n"; - OS << "\n"; - OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, " - << "std::set &Visited) {\n"; - OS << " if (found || !Visited.insert(Use).second) return;\n"; - OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n"; - OS << " SDNode *N = Use->getOperand(i).Val;\n"; - OS << " if (N != Def) {\n"; - OS << " findNonImmUse(N, Def, found, Visited);\n"; - OS << " } else {\n"; - OS << " found = true;\n"; - OS << " break;\n"; - OS << " }\n"; - OS << " }\n"; + OS << "inline void setQueued(int Id) {\n"; + OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n"; OS << "}\n"; - - OS << "\n"; - OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n"; - OS << " std::set Visited;\n"; - OS << " bool found = false;\n"; - OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n"; - OS << " SDNode *N = Use->getOperand(i).Val;\n"; - OS << " if (N != Def) {\n"; - OS << " findNonImmUse(N, Def, found, Visited);\n"; - OS << " if (found) break;\n"; - OS << " }\n"; - OS << " }\n"; - OS << " return found;\n"; + OS << "inline bool isQueued(int Id) {\n"; + OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n"; OS << "}\n"; - - OS << "\n"; - OS << "// AddHandleReplacement - Note the pending replacement node for a\n" - << "// handle node in ReplaceMap.\n"; - OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, " - << "unsigned RNum) {\n"; - OS << " SDOperand N(H, HNum);\n"; - OS << " std::map::iterator HMI = HandleMap.find(N);\n"; - OS << " if (HMI != HandleMap.end()) {\n"; - OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n"; - OS << " HandleMap.erase(N);\n"; - OS << " }\n"; + OS << "inline void setSelected(int Id) {\n"; + OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n"; OS << "}\n"; - - OS << "\n"; - OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n"; - OS << "// handles.Some handles do not yet have replacements because the\n"; - OS << "// nodes they replacements have only dead readers.\n"; - OS << "void SelectDanglingHandles() {\n"; - OS << " for (std::map::iterator I = " - << "HandleMap.begin(),\n" - << " E = HandleMap.end(); I != E; ++I) {\n"; - OS << " SDOperand N = I->first;\n"; - OS << " SDOperand R;\n"; - OS << " Select(R, N.getValue(0));\n"; - OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n"; + OS << "inline bool isSelected(int Id) {\n"; + OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n"; + OS << "}\n\n"; + + OS << "inline void AddToQueue(SDOperand &Result, SDOperand N) {\n"; + OS << " Result = N;\n"; + OS << " int Id = N.Val->getNodeId();\n"; + OS << " if (Id != -1 && !isQueued(Id)) {\n"; + OS << " ISelQueue.push_back(N.Val);\n"; + OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; + OS << " setQueued(Id);\n"; OS << " }\n"; - OS << "}\n"; - OS << "\n"; - OS << "// ReplaceHandles - Replace all the handles with the real target\n"; - OS << "// specific nodes.\n"; - OS << "void ReplaceHandles() {\n"; - OS << " for (std::map::iterator I = " - << "ReplaceMap.begin(),\n" - << " E = ReplaceMap.end(); I != E; ++I) {\n"; - OS << " SDOperand From = I->first;\n"; - OS << " SDOperand To = I->second;\n"; - OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), " - << "E = From.Val->use_end(); UI != E; ++UI) {\n"; - OS << " SDNode *Use = *UI;\n"; - OS << " std::vector Ops;\n"; - OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n"; - OS << " SDOperand O = Use->getOperand(i);\n"; - OS << " if (O.Val == From.Val)\n"; - OS << " Ops.push_back(To);\n"; - OS << " else\n"; - OS << " Ops.push_back(O);\n"; - OS << " }\n"; - OS << " SDOperand U = SDOperand(Use, 0);\n"; - OS << " CurDAG->UpdateNodeOperands(U, Ops);\n"; - OS << " }\n"; + OS << "}\n\n"; + + OS << "inline void RemoveKilled() {\n"; +OS << " unsigned NumKilled = ISelKilled.size();\n"; + OS << " if (NumKilled) {\n"; + OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n"; + OS << " SDNode *Temp = ISelKilled[i];\n"; + OS << " std::remove(ISelQueue.begin(), ISelQueue.end(), Temp);\n"; + OS << " };\n"; + OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; + OS << " ISelKilled.clear();\n"; OS << " }\n"; - OS << "}\n"; + OS << "}\n\n"; + + OS << "inline void ReplaceUses(SDOperand F, SDOperand T) {\n"; + OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n"; + OS << " setSelected(F.Val->getNodeId());\n"; + OS << " RemoveKilled();\n"; + OS << "}\n\n"; - OS << "\n"; OS << "// SelectRoot - Top level entry to DAG isel.\n"; - OS << "SDOperand SelectRoot(SDOperand N) {\n"; + OS << "SDOperand SelectRoot(SDOperand Root) {\n"; + OS << " SelectRootInit();\n"; + OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n"; + OS << " ISelQueued = new unsigned char[NumBytes];\n"; + OS << " ISelSelected = new unsigned char[NumBytes];\n"; + OS << " memset(ISelQueued, 0, NumBytes);\n"; + OS << " memset(ISelSelected, 0, NumBytes);\n"; + OS << "\n"; OS << " SDOperand ResNode;\n"; - OS << " Select(ResNode, N);\n"; - OS << " SelectDanglingHandles();\n"; - OS << " ReplaceHandles();\n"; - OS << " ReplaceMap.clear();\n"; + OS << " Select(ResNode, Root);\n"; + OS << " while (!ISelQueue.empty()) {\n"; + OS << " SDOperand Tmp;\n"; + OS << " SDNode *Node = ISelQueue.front();\n"; + OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n"; + OS << " ISelQueue.pop_back();\n"; + OS << " if (!isSelected(Node->getNodeId()))\n"; + OS << " Select(Tmp, SDOperand(Node, 0));\n"; + OS << " }\n"; + OS << "\n"; + OS << " delete[] ISelQueued;\n"; + OS << " ISelQueued = NULL;\n"; + OS << " delete[] ISelSelected;\n"; + OS << " ISelSelected = NULL;\n"; OS << " return ResNode;\n"; OS << "}\n"; From tbrethou at cs.uiuc.edu Wed Aug 9 11:46:31 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 11:46:31 -0500 Subject: [llvm-commits] [release_18] CVS: llvm/utils/TableGen/DAGISelEmitter.cpp Message-ID: <200608091646.k79GkVxZ024336@zion.cs.uiuc.edu> Changes in directory llvm/utils/TableGen: DAGISelEmitter.cpp updated: 1.226.2.2 -> 1.226.2.3 --- Log message: Revert. --- Diffs of the changes: (+272 -286) DAGISelEmitter.cpp | 558 +++++++++++++++++++++++++---------------------------- 1 files changed, 272 insertions(+), 286 deletions(-) Index: llvm/utils/TableGen/DAGISelEmitter.cpp diff -u llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.2 llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.3 --- llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.2 Wed Aug 9 11:33:15 2006 +++ llvm/utils/TableGen/DAGISelEmitter.cpp Wed Aug 9 11:46:19 2006 @@ -1829,22 +1829,9 @@ // If this node is commutative, consider the commuted order. if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) { assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!"); - // Don't count children which are actually register references. - unsigned NC = 0; - for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) { - TreePatternNode *Child = N->getChild(i); - if (Child->isLeaf()) - if (DefInit *DI = dynamic_cast(Child->getLeafValue())) { - Record *RR = DI->getDef(); - if (RR->isSubClassOf("Register")) - continue; - } - NC++; - } // Consider the commuted order. - if (NC == 2) - CombineChildVariants(N, ChildVariants[1], ChildVariants[0], - OutVariants, ISE); + CombineChildVariants(N, ChildVariants[1], ChildVariants[0], + OutVariants, ISE); } } @@ -2119,6 +2106,8 @@ // Names of all the folded nodes which produce chains. std::vector > FoldedChains; std::set Duplicates; + /// These nodes are being marked "in-flight" so they cannot be folded. + std::vector InflightNodes; /// GeneratedCode - This is the buffer that we emit code to. The first bool /// indicates whether this is an exit predicate (something that should be @@ -2242,6 +2231,8 @@ OpNo = 1; if (!isRoot) { const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator()); + // Not in flight? + emitCheck("InFlightSet.count(" + RootName + ".Val) == 0"); // Multiple uses of actual result? emitCheck(RootName + ".hasOneUse()"); EmittedUseCheck = true; @@ -2289,8 +2280,14 @@ PInfo.hasProperty(SDNodeInfo::SDNPHasChain) || PInfo.hasProperty(SDNodeInfo::SDNPInFlag) || PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag)) - emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName + - ".Val)"); + if (PInfo.getNumOperands() > 1) { + emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName + + ".Val)"); + } else { + emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" + + "isNonImmUse(" + ParentName + ".Val, " + RootName + + ".Val))"); + } } } @@ -2482,11 +2479,27 @@ for (unsigned i = 0; i < NumRes; ++i) emitDecl("CPTmp" + utostr(i+ResNo)); - std::string Code = Fn + "(" + Val; + std::string Code = "bool Match = " + Fn + "(" + Val; for (unsigned i = 0; i < NumRes; i++) Code += ", CPTmp" + utostr(i + ResNo); - emitCheck(Code + ")"); + emitCode(Code + ");"); + if (InflightNodes.size()) { + // Remove the in-flight nodes if the ComplexPattern does not match! + emitCode("if (!Match) {"); + for (std::vector::iterator AI = InflightNodes.begin(), + AE = InflightNodes.end(); AI != AE; ++AI) + emitCode(" SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " + + *AI + ".Val);"); + emitCode("}"); + } + emitCheck("Match"); + + for (unsigned i = 0; i < NumRes; ++i) { + emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, CPTmp" + + utostr(i+ResNo) + ".Val);"); + InflightNodes.push_back("CPTmp" + utostr(i+ResNo)); + } for (unsigned i = 0; i < NumRes; ++i) { emitDecl("Tmp" + utostr(i+ResNo)); emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" + @@ -2601,6 +2614,22 @@ } } + // Make sure these operands which would be selected won't be folded while + // the isel traverses the DAG upward. + for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) { + TreePatternNode *Child = EmitOrder[i].second; + if (!Child->getName().empty()) { + std::string &Val = VariableMap[Child->getName()]; + assert(!Val.empty() && + "Variable referenced but not defined and not caught earlier!"); + if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) { + emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, " + + Val + ".Val);"); + InflightNodes.push_back(Val); + } + } + } + // Emit all of the operands. std::vector > NumTemps(EmitOrder.size()); for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) { @@ -2628,6 +2657,14 @@ emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));"); } + if (isRoot) { + // The operands have been selected. Remove them from InFlightSet. + for (std::vector::iterator AI = InflightNodes.begin(), + AE = InflightNodes.end(); AI != AE; ++AI) + emitCode("SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " + + *AI + ".Val);"); + } + unsigned NumResults = Inst.getNumResults(); unsigned ResNo = TmpNo++; if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag || @@ -2858,15 +2895,13 @@ /// 'Pat' may be missing types. If we find an unresolved type to add a check /// for, this returns true otherwise false if Pat has all types. bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other, - const std::string &Prefix, bool isRoot = false) { + const std::string &Prefix) { // Did we find one? if (Pat->getExtTypes() != Other->getExtTypes()) { // Move a type over from 'other' to 'pat'. Pat->setTypes(Other->getExtTypes()); - // The top level node type is checked outside of the select function. - if (!isRoot) - emitCheck(Prefix + ".Val->getValueType(0) == " + - getName(Pat->getTypeNum(0))); + emitCheck(Prefix + ".Val->getValueType(0) == " + + getName(Pat->getTypeNum(0))); return true; } @@ -3020,7 +3055,7 @@ // Insert a check for an unresolved type and add it to the tree. If we find // an unresolved type to add a check for, this returns true and we iterate, // otherwise we are done. - } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true)); + } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N")); Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/); delete Pat; @@ -3205,12 +3240,7 @@ } } } - - // For each opcode, there might be multiple select functions, one per - // ValueType of the node (or its first operand if it doesn't produce a - // non-chain result. - std::map > OpcodeVTMap; - + // Emit one Select_* method for each top-level opcode. We do this instead of // emitting one giant switch statement to support compilers where this will // result in the recursive functions taking less stack space. @@ -3222,241 +3252,204 @@ bool OptSlctOrder = (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) && OpcodeInfo.getNumResults() > 0); - std::vector &PatternsOfOp = PBOI->second; - assert(!PatternsOfOp.empty() && "No patterns but map has entry?"); - + std::vector &Patterns = PBOI->second; + assert(!Patterns.empty() && "No patterns but map has entry?"); + // We want to emit all of the matching code now. However, we want to emit // the matches in order of minimal cost. Sort the patterns so the least // cost one is at the start. - std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(), + std::stable_sort(Patterns.begin(), Patterns.end(), PatternSortingPredicate(*this)); - // Split them into groups by type. - std::map > PatternsByType; - for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) { - PatternToMatch *Pat = PatternsOfOp[i]; - TreePatternNode *SrcPat = Pat->getSrcPattern(); - if (OpcodeInfo.getNumResults() == 0 && SrcPat->getNumChildren() > 0) - SrcPat = SrcPat->getChild(0); - MVT::ValueType VT = SrcPat->getTypeNum(0); - std::map >::iterator TI = - PatternsByType.find(VT); - if (TI != PatternsByType.end()) - TI->second.push_back(Pat); - else { - std::vector PVec; - PVec.push_back(Pat); - PatternsByType.insert(std::make_pair(VT, PVec)); - } - } - - for (std::map >::iterator - II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE; - ++II) { - MVT::ValueType OpVT = II->first; - std::vector &Patterns = II->second; - typedef std::vector > CodeList; - typedef std::vector >::iterator CodeListI; + typedef std::vector > CodeList; + typedef std::vector >::iterator CodeListI; - std::vector > CodeForPatterns; - std::vector > PatternOpcodes; - std::vector > PatternVTs; - std::vector > > PatternDecls; - std::set > AllGenDecls; - for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { - CodeList GeneratedCode; - std::set > GeneratedDecl; - std::vector TargetOpcodes; - std::vector TargetVTs; - GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, - TargetOpcodes, TargetVTs, OptSlctOrder); - for (std::set >::iterator - si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) - AllGenDecls.insert(*si); - CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode)); - PatternDecls.push_back(GeneratedDecl); - PatternOpcodes.push_back(TargetOpcodes); - PatternVTs.push_back(TargetVTs); - } + std::vector > CodeForPatterns; + std::vector > PatternOpcodes; + std::vector > PatternVTs; + std::vector > > PatternDecls; + std::set > AllGenDecls; + for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { + CodeList GeneratedCode; + std::set > GeneratedDecl; + std::vector TargetOpcodes; + std::vector TargetVTs; + GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl, + TargetOpcodes, TargetVTs, OptSlctOrder); + for (std::set >::iterator + si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si) + AllGenDecls.insert(*si); + CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode)); + PatternDecls.push_back(GeneratedDecl); + PatternOpcodes.push_back(TargetOpcodes); + PatternVTs.push_back(TargetVTs); + } - // Scan the code to see if all of the patterns are reachable and if it is - // possible that the last one might not match. - bool mightNotMatch = true; - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - mightNotMatch = false; - - for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) { - if (GeneratedCode[j].first) { // predicate. - mightNotMatch = true; - break; - } + // Scan the code to see if all of the patterns are reachable and if it is + // possible that the last one might not match. + bool mightNotMatch = true; + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + mightNotMatch = false; + + for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) { + if (GeneratedCode[j].first) { // predicate. + mightNotMatch = true; + break; } + } - // If this pattern definitely matches, and if it isn't the last one, the - // patterns after it CANNOT ever match. Error out. - if (mightNotMatch == false && i != CodeForPatterns.size()-1) { - std::cerr << "Pattern '"; - CodeForPatterns[i+1].first->getSrcPattern()->print(std::cerr); - std::cerr << "' is impossible to select!\n"; - exit(1); - } + // If this pattern definitely matches, and if it isn't the last one, the + // patterns after it CANNOT ever match. Error out. + if (mightNotMatch == false && i != CodeForPatterns.size()-1) { + std::cerr << "Pattern '"; + CodeForPatterns[i+1].first->getSrcPattern()->print(OS); + std::cerr << "' is impossible to select!\n"; + exit(1); } + } - // Factor target node emission code (emitted by EmitResultCode) into - // separate functions. Uniquing and share them among all instruction - // selection routines. - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - std::vector &TargetOpcodes = PatternOpcodes[i]; - std::vector &TargetVTs = PatternVTs[i]; - std::set > Decls = PatternDecls[i]; - int CodeSize = (int)GeneratedCode.size(); - int LastPred = -1; - for (int j = CodeSize-1; j >= 0; --j) { - if (GeneratedCode[j].first) { - LastPred = j; - break; - } + // Factor target node emission code (emitted by EmitResultCode) into + // separate functions. Uniquing and share them among all instruction + // selection routines. + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + std::vector &TargetOpcodes = PatternOpcodes[i]; + std::vector &TargetVTs = PatternVTs[i]; + std::set > Decls = PatternDecls[i]; + int CodeSize = (int)GeneratedCode.size(); + int LastPred = -1; + for (int j = CodeSize-1; j >= 0; --j) { + if (GeneratedCode[j].first) { + LastPred = j; + break; } + } - std::string CalleeDecls; - std::string CalleeCode = "(SDOperand &Result, const SDOperand &N"; - std::string CallerCode = "(Result, N"; - for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) { - CalleeCode += ", unsigned Opc" + utostr(j); - CallerCode += ", " + TargetOpcodes[j]; - } - for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) { - CalleeCode += ", MVT::ValueType VT" + utostr(j); - CallerCode += ", " + TargetVTs[j]; - } - for (std::set >::iterator - I = Decls.begin(), E = Decls.end(); I != E; ++I) { - std::string Name = I->second; - if (I->first == 0) { - if (Name == "InFlag" || - (Name.size() > 3 && - Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) { - CalleeDecls += " SDOperand " + Name + "(0, 0);\n"; - continue; - } - CalleeCode += ", SDOperand &" + Name; - CallerCode += ", " + Name; - } else if (I->first == 1) { - if (Name == "ResNode") { - CalleeDecls += " SDNode *" + Name + " = NULL;\n"; - continue; - } - CalleeCode += ", SDNode *" + Name; - CallerCode += ", " + Name; - } else { - CalleeCode += ", bool " + Name; - CallerCode += ", " + Name; + std::string CalleeDecls; + std::string CalleeCode = "(SDOperand &Result, SDOperand &N"; + std::string CallerCode = "(Result, N"; + for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) { + CalleeCode += ", unsigned Opc" + utostr(j); + CallerCode += ", " + TargetOpcodes[j]; + } + for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) { + CalleeCode += ", MVT::ValueType VT" + utostr(j); + CallerCode += ", " + TargetVTs[j]; + } + for (std::set >::iterator + I = Decls.begin(), E = Decls.end(); I != E; ++I) { + std::string Name = I->second; + if (I->first == 0) { + if (Name == "InFlag" || + (Name.size() > 3 && + Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) { + CalleeDecls += " SDOperand " + Name + "(0, 0);\n"; + continue; } - } - CallerCode += ");"; - CalleeCode += ") "; - // Prevent emission routines from being inlined to reduce selection - // routines stack frame sizes. - CalleeCode += "NOINLINE "; - CalleeCode += "{\n" + CalleeDecls; - for (int j = LastPred+1; j < CodeSize; ++j) - CalleeCode += " " + GeneratedCode[j].second + '\n'; - for (int j = LastPred+1; j < CodeSize; ++j) - GeneratedCode.pop_back(); - CalleeCode += "}\n"; - - // Uniquing the emission routines. - unsigned EmitFuncNum; - std::map::iterator EFI = - EmitFunctions.find(CalleeCode); - if (EFI != EmitFunctions.end()) { - EmitFuncNum = EFI->second; + CalleeCode += ", SDOperand &" + Name; + CallerCode += ", " + Name; + } else if (I->first == 1) { + if (Name == "ResNode") { + CalleeDecls += " SDNode *" + Name + " = NULL;\n"; + continue; + } + CalleeCode += ", SDNode *" + Name; + CallerCode += ", " + Name; } else { - EmitFuncNum = EmitFunctions.size(); - EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum)); - OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode; - } - - // Replace the emission code within selection routines with calls to the - // emission functions. - CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode; - GeneratedCode.push_back(std::make_pair(false, CallerCode)); - GeneratedCode.push_back(std::make_pair(false, "return;")); - } - - // Print function. - std::string OpVTStr = (OpVT != MVT::isVoid && OpVT != MVT::iPTR) - ? getEnumName(OpVT).substr(5) : "" ; - std::map >::iterator OpVTI = - OpcodeVTMap.find(OpName); - if (OpVTI == OpcodeVTMap.end()) { - std::vector VTSet; - VTSet.push_back(OpVTStr); - OpcodeVTMap.insert(std::make_pair(OpName, VTSet)); - } else - OpVTI->second.push_back(OpVTStr); - - OS << "void Select_" << OpName << (OpVTStr != "" ? "_" : "") - << OpVTStr << "(SDOperand &Result, const SDOperand &N) {\n"; - if (OptSlctOrder) { - OS << " if (N.ResNo == " << OpcodeInfo.getNumResults() - << " && N.getValue(0).hasOneUse()) {\n" - << " SDOperand Dummy = " - << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n" - << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " - << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" - << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, " - << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" - << " Result = Dummy;\n" - << " return;\n" - << " }\n"; + CalleeCode += ", bool " + Name; + CallerCode += ", " + Name; + } } + CallerCode += ");"; + CalleeCode += ") "; + // Prevent emission routines from being inlined to reduce selection + // routines stack frame sizes. + CalleeCode += "NOINLINE "; + CalleeCode += "{\n" + CalleeDecls; + for (int j = LastPred+1; j < CodeSize; ++j) + CalleeCode += " " + GeneratedCode[j].second + '\n'; + for (int j = LastPred+1; j < CodeSize; ++j) + GeneratedCode.pop_back(); + CalleeCode += "}\n"; + + // Uniquing the emission routines. + unsigned EmitFuncNum; + std::map::iterator EFI = + EmitFunctions.find(CalleeCode); + if (EFI != EmitFunctions.end()) { + EmitFuncNum = EFI->second; + } else { + EmitFuncNum = EmitFunctions.size(); + EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum)); + OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode; + } + + // Replace the emission code within selection routines with calls to the + // emission functions. + CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode; + GeneratedCode.push_back(std::make_pair(false, CallerCode)); + GeneratedCode.push_back(std::make_pair(false, "return;")); + } + + // Print function. + OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n"; + if (OptSlctOrder) { + OS << " if (N.ResNo == " << OpcodeInfo.getNumResults() + << " && N.getValue(0).hasOneUse()) {\n" + << " SDOperand Dummy = " + << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n" + << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " + << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" + << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, " + << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n" + << " Result = Dummy;\n" + << " return;\n" + << " }\n"; + } + + // Print all declarations. + for (std::set >::iterator + I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I) + if (I->first == 0) + OS << " SDOperand " << I->second << "(0, 0);\n"; + else if (I->first == 1) + OS << " SDNode *" << I->second << " = NULL;\n"; + else + OS << " bool " << I->second << " = false;\n"; - // Print all declarations. - for (std::set >::iterator - I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I) - if (I->first == 0) - OS << " SDOperand " << I->second << "(0, 0);\n"; - else if (I->first == 1) - OS << " SDNode *" << I->second << " = NULL;\n"; - else - OS << " bool " << I->second << " = false;\n"; - - // Loop through and reverse all of the CodeList vectors, as we will be - // accessing them from their logical front, but accessing the end of a - // vector is more efficient. - for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { - CodeList &GeneratedCode = CodeForPatterns[i].second; - std::reverse(GeneratedCode.begin(), GeneratedCode.end()); - } + // Loop through and reverse all of the CodeList vectors, as we will be + // accessing them from their logical front, but accessing the end of a + // vector is more efficient. + for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) { + CodeList &GeneratedCode = CodeForPatterns[i].second; + std::reverse(GeneratedCode.begin(), GeneratedCode.end()); + } - // Next, reverse the list of patterns itself for the same reason. - std::reverse(CodeForPatterns.begin(), CodeForPatterns.end()); + // Next, reverse the list of patterns itself for the same reason. + std::reverse(CodeForPatterns.begin(), CodeForPatterns.end()); - // Emit all of the patterns now, grouped together to share code. - EmitPatterns(CodeForPatterns, 2, OS); + // Emit all of the patterns now, grouped together to share code. + EmitPatterns(CodeForPatterns, 2, OS); - // If the last pattern has predicates (which could fail) emit code to catch - // the case where nothing handles a pattern. - if (mightNotMatch) { - OS << " std::cerr << \"Cannot yet select: \";\n"; - if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" && - OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" && - OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") { - OS << " N.Val->dump(CurDAG);\n"; - } else { - OS << " unsigned iid = cast(N.getOperand(" - "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n" - << " std::cerr << \"intrinsic %\"<< " - "Intrinsic::getName((Intrinsic::ID)iid);\n"; - } - OS << " std::cerr << '\\n';\n" - << " abort();\n"; + // If the last pattern has predicates (which could fail) emit code to catch + // the case where nothing handles a pattern. + if (mightNotMatch) { + OS << " std::cerr << \"Cannot yet select: \";\n"; + if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" && + OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" && + OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") { + OS << " N.Val->dump(CurDAG);\n"; + } else { + OS << " unsigned iid = cast(N.getOperand(" + "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n" + << " std::cerr << \"intrinsic %\"<< " + "Intrinsic::getName((Intrinsic::ID)iid);\n"; } - OS << "}\n\n"; + OS << " std::cerr << '\\n';\n" + << " abort();\n"; } + OS << "}\n\n"; } // Emit boilerplate. @@ -3607,48 +3600,9 @@ CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end(); PBOI != E; ++PBOI) { const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first); - const std::string &OpName = PBOI->first->getName(); - // Potentially multiple versions of select for this opcode. One for each - // ValueType of the node (or its first true operand if it doesn't produce a - // result. - std::map >::iterator OpVTI = - OpcodeVTMap.find(OpName); - std::vector &OpVTs = OpVTI->second; - OS << " case " << OpcodeInfo.getEnumName() << ": {\n"; - if (OpVTs.size() == 1) { - std::string &VTStr = OpVTs[0]; - OS << " Select_" << OpName - << (VTStr != "" ? "_" : "") << VTStr << "(Result, N);\n"; - } else { - if (OpcodeInfo.getNumResults()) - OS << " MVT::ValueType NVT = N.Val->getValueType(0);\n"; - else if (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain)) - OS << " MVT::ValueType NVT = (N.getNumOperands() > 1) ?" - << " N.getOperand(1).Val->getValueType(0) : MVT::isVoid;\n"; - else - OS << " MVT::ValueType NVT = (N.getNumOperands() > 0) ?" - << " N.getOperand(0).Val->getValueType(0) : MVT::isVoid;\n"; - int ElseCase = -1; - bool First = true; - for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) { - std::string &VTStr = OpVTs[i]; - if (VTStr == "") { - ElseCase = i; - continue; - } - OS << (First ? " if" : " else if") - << " (NVT == MVT::" << VTStr << ")\n" - << " Select_" << OpName - << "_" << VTStr << "(Result, N);\n"; - First = false; - } - if (ElseCase != -1) - OS << " else\n" << " Select_" << OpName << "(Result, N);\n"; - else - OS << " else\n" << " break;\n"; - } - OS << " return;\n"; - OS << " }\n"; + OS << " case " << OpcodeInfo.getEnumName() << ": " + << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ') + << "Select_" << PBOI->first->getName() << "(Result, N); return;\n"; } OS << " } // end of big switch.\n\n" @@ -3691,6 +3645,38 @@ OS << "// Instance var to keep track of mapping of place handle nodes\n" << "// and their replacement nodes.\n"; OS << "std::map ReplaceMap;\n"; + OS << "// Keep track of nodes that are currently being selecte and therefore\n" + << "// should not be folded.\n"; + OS << "std::set InFlightSet;\n"; + + OS << "\n"; + OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, " + << "std::set &Visited) {\n"; + OS << " if (found || !Visited.insert(Use).second) return;\n"; + OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n"; + OS << " SDNode *N = Use->getOperand(i).Val;\n"; + OS << " if (N != Def) {\n"; + OS << " findNonImmUse(N, Def, found, Visited);\n"; + OS << " } else {\n"; + OS << " found = true;\n"; + OS << " break;\n"; + OS << " }\n"; + OS << " }\n"; + OS << "}\n"; + + OS << "\n"; + OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n"; + OS << " std::set Visited;\n"; + OS << " bool found = false;\n"; + OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n"; + OS << " SDNode *N = Use->getOperand(i).Val;\n"; + OS << " if (N != Def) {\n"; + OS << " findNonImmUse(N, Def, found, Visited);\n"; + OS << " if (found) break;\n"; + OS << " }\n"; + OS << " }\n"; + OS << " return found;\n"; + OS << "}\n"; OS << "\n"; OS << "// AddHandleReplacement - Note the pending replacement node for a\n" From lattner at cs.uiuc.edu Wed Aug 9 11:55:39 2006 From: lattner at cs.uiuc.edu (Chris Lattner) Date: Wed, 9 Aug 2006 11:55:39 -0500 Subject: [llvm-commits] [release_18] CVS: llvm/utils/TableGen/DAGISelEmitter.cpp Message-ID: <200608091655.k79Gtd3K024572@zion.cs.uiuc.edu> Changes in directory llvm/utils/TableGen: DAGISelEmitter.cpp updated: 1.226.2.3 -> 1.226.2.4 --- Log message: Apply patch from mainline for GCC 3.3 compatibility. --- Diffs of the changes: (+2 -0) DAGISelEmitter.cpp | 2 ++ 1 files changed, 2 insertions(+) Index: llvm/utils/TableGen/DAGISelEmitter.cpp diff -u llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.3 llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.4 --- llvm/utils/TableGen/DAGISelEmitter.cpp:1.226.2.3 Wed Aug 9 11:46:19 2006 +++ llvm/utils/TableGen/DAGISelEmitter.cpp Wed Aug 9 11:55:25 2006 @@ -3633,6 +3633,8 @@ OS << "#if defined(__GNUC__) && \\\n"; OS << " ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)))\n"; OS << "#define NOINLINE __attribute__((noinline))\n"; + OS << "#else\n\n"; + OS << "#define NOINLINE\n\n"; OS << "#endif\n\n"; OS << "// Instance var to keep track of multiply used nodes that have \n" From tbrethou at cs.uiuc.edu Wed Aug 9 11:59:53 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 11:59:53 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/1.8/llvm-1.8a.tar.gz Message-ID: <200608091659.k79GxrRm024728@zion.cs.uiuc.edu> Changes in directory llvm-www/releases/1.8: llvm-1.8a.tar.gz added (r1.1) --- Log message: New tar ball with ISelEmitter.cpp patch for GCC 3.3 compatibility. --- Diffs of the changes: (+0 -0) llvm-1.8a.tar.gz | 0 1 files changed Index: llvm-www/releases/1.8/llvm-1.8a.tar.gz From tbrethou at cs.uiuc.edu Wed Aug 9 12:00:37 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 12:00:37 -0500 Subject: [llvm-commits] CVS: llvm-www/releases/download.html Message-ID: <200608091700.k79H0b16024772@zion.cs.uiuc.edu> Changes in directory llvm-www/releases: download.html updated: 1.35 -> 1.36 --- Log message: Adjust link to new tar for 1.8a --- Diffs of the changes: (+1 -1) download.html | 2 +- 1 files changed, 1 insertion(+), 1 deletion(-) Index: llvm-www/releases/download.html diff -u llvm-www/releases/download.html:1.35 llvm-www/releases/download.html:1.36 --- llvm-www/releases/download.html:1.35 Wed Aug 9 01:02:21 2006 +++ llvm-www/releases/download.html Wed Aug 9 12:00:24 2006 @@ -39,7 +39,7 @@ downloading:

          -
        • LLVM source code (4.5M)
        • +
        • LLVM source code (4.5M)
        • LLVM Test Suite (11.6M)
        • LLVM-GCC 3.4 Front End Binaries for Linux/x86 (6.4M)
        • LLVM-GCC 3.4 Front End Binaries for MacOS X/PowerPC (6.5M)
        • From tbrethou at cs.uiuc.edu Wed Aug 9 12:08:39 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 12:08:39 -0500 Subject: [llvm-commits] CVS: llvm/docs/ReleaseNotes.html Message-ID: <200608091708.k79H8dKI024947@zion.cs.uiuc.edu> Changes in directory llvm/docs: ReleaseNotes.html updated: 1.361 -> 1.362 --- Log message: Fixed misspelling --- Diffs of the changes: (+2 -2) ReleaseNotes.html | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-) Index: llvm/docs/ReleaseNotes.html diff -u llvm/docs/ReleaseNotes.html:1.361 llvm/docs/ReleaseNotes.html:1.362 --- llvm/docs/ReleaseNotes.html:1.361 Tue Aug 8 23:10:32 2006 +++ llvm/docs/ReleaseNotes.html Wed Aug 9 12:08:27 2006 @@ -61,7 +61,7 @@
          -

          This is the nineth public release of the LLVM Compiler Infrastructure. This +

          This is the ninth public release of the LLVM Compiler Infrastructure. This release incorporates a large number of enhancements and new features, including DWARF debugging support (C and C++ on Darwin/PPC), improved inline assembly support, a new nightly @@ -684,7 +684,7 @@ src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" /> The LLVM Compiler Infrastructure
          - Last modified: $Date: 2006/08/09 04:10:32 $ + Last modified: $Date: 2006/08/09 17:08:27 $ From rafael.espindola at gmail.com Wed Aug 9 12:37:59 2006 From: rafael.espindola at gmail.com (Rafael Espindola) Date: Wed, 9 Aug 2006 12:37:59 -0500 Subject: [llvm-commits] CVS: llvm/lib/Target/ARM/ARMRegisterInfo.cpp ARMTargetMachine.cpp Message-ID: <200608091737.k79Hbx80025626@zion.cs.uiuc.edu> Changes in directory llvm/lib/Target/ARM: ARMRegisterInfo.cpp updated: 1.13 -> 1.14 ARMTargetMachine.cpp updated: 1.3 -> 1.4 --- Log message: correctly set LocalAreaOffset of TargetFrameInfo --- Diffs of the changes: (+1 -6) ARMRegisterInfo.cpp | 5 ----- ARMTargetMachine.cpp | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) Index: llvm/lib/Target/ARM/ARMRegisterInfo.cpp diff -u llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.13 llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.14 --- llvm/lib/Target/ARM/ARMRegisterInfo.cpp:1.13 Wed Aug 9 11:41:12 2006 +++ llvm/lib/Target/ARM/ARMRegisterInfo.cpp Wed Aug 9 12:37:45 2006 @@ -93,11 +93,6 @@ unsigned StackSize = MF.getFrameInfo()->getStackSize(); - // - if (Offset < 0) - Offset -= 4; - // - Offset += StackSize; assert (Offset >= 0); Index: llvm/lib/Target/ARM/ARMTargetMachine.cpp diff -u llvm/lib/Target/ARM/ARMTargetMachine.cpp:1.3 llvm/lib/Target/ARM/ARMTargetMachine.cpp:1.4 --- llvm/lib/Target/ARM/ARMTargetMachine.cpp:1.3 Fri Jun 16 13:22:52 2006 +++ llvm/lib/Target/ARM/ARMTargetMachine.cpp Wed Aug 9 12:37:45 2006 @@ -33,7 +33,7 @@ /// ARMTargetMachine::ARMTargetMachine(const Module &M, const std::string &FS) : TargetMachine("ARM"), DataLayout("E-p:32:32"), - FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) { + FrameInfo(TargetFrameInfo::StackGrowsDown, 8, -4) { } unsigned ARMTargetMachine::getModuleMatchQuality(const Module &M) { From reid at x10sys.com Wed Aug 9 14:40:28 2006 From: reid at x10sys.com (Reid Spencer) Date: Wed, 9 Aug 2006 14:40:28 -0500 Subject: [llvm-commits] CVS: llvm/utils/findsym.pl Message-ID: <200608091940.k79JeSQP004950@zion.cs.uiuc.edu> Changes in directory llvm/utils: findsym.pl updated: 1.1 -> 1.2 --- Log message: Fix a comment. --- Diffs of the changes: (+1 -2) findsym.pl | 3 +-- 1 files changed, 1 insertion(+), 2 deletions(-) Index: llvm/utils/findsym.pl diff -u llvm/utils/findsym.pl:1.1 llvm/utils/findsym.pl:1.2 --- llvm/utils/findsym.pl:1.1 Thu Mar 23 17:04:50 2006 +++ llvm/utils/findsym.pl Wed Aug 9 14:40:13 2006 @@ -5,14 +5,13 @@ # Synopsis: Generate a list of the libraries in which a symbol is defined or # referenced. # -# Syntax: GenLibDeps.pl +# Syntax: findsym.pl # # Give first option a name. my $Directory = $ARGV[0]; my $Symbol = $ARGV[1]; - # Open the directory and read its contents, sorting by name and differentiating # by whether its a library (.a) or an object file (.o) opendir DIR,$Directory; From reid at x10sys.com Wed Aug 9 17:29:11 2006 From: reid at x10sys.com (Reid Spencer) Date: Wed, 9 Aug 2006 17:29:11 -0500 Subject: [llvm-commits] CVS: llvm-www/demo/index.cgi Message-ID: <200608092229.k79MTBq5009015@zion.cs.uiuc.edu> Changes in directory llvm-www/demo: index.cgi updated: 1.59 -> 1.60 --- Log message: Add the invocation of llvm2cpp to the demo page. Also, rearrange the "what to do" options to make it more legible. --- Diffs of the changes: (+41 -33) index.cgi | 74 ++++++++++++++++++++++++++++++++++---------------------------- 1 files changed, 41 insertions(+), 33 deletions(-) Index: llvm-www/demo/index.cgi diff -u llvm-www/demo/index.cgi:1.59 llvm-www/demo/index.cgi:1.60 --- llvm-www/demo/index.cgi:1.59 Sat Jul 16 00:46:08 2005 +++ llvm-www/demo/index.cgi Wed Aug 9 17:28:57 2006 @@ -5,13 +5,13 @@ # doing remote web JO99C compilations. (It could still be used for that # purpose, though the two scripts have diverged somewhat.) # -# Last modified $Date: 2005/07/16 05:46:08 $ +# Last modified $Date: 2006/08/09 22:28:57 $ # use strict; use CGI; use POSIX; -use Mail::Send; +# use Mail::Send; $| = 1; @@ -105,8 +105,8 @@ sub mailto { my ( $recipient, $body ) = @_; - my $msg = - new Mail::Send( Subject => "LLVM Demo Page Run", To => $recipient ); + my $msg = "Nada"; +# new Mail::Send( Subject => "LLVM Demo Page Run", To => $recipient ); my $fh = $msg->open(); print $fh $body; $fh->close(); @@ -187,44 +187,45 @@ information about Stacker and examples.

          \n"; -print "
          "; -print -"

          Click here if you want Bitter Melon to run the resulting code through c++filt. Warning, the LLVM code produced will probably not be lexically valid, but it will be easier to understand.

            ", - $c->checkbox( +print '
            '; + +print $c->checkbox( -name => 'cxxdemangle', -label => 'Demangle C++ names with c++filt' - ), - ""; -print ""; - + ),''; print -"

            Bitter Melon can also run the link-time optimizer for you, if you like (but she won't link your code with any libraries). Note that you have to define 'main' in your program for this to make much of a difference.

              ", - $c->checkbox( +"

              Click here if you want Bitter Melon to run the resulting code through c++filt. Warning, the LLVM code produced will probably not be lexically valid, but it will be easier to understand.

            "; + +print $c->checkbox( -name => 'linkopt', -label => 'Run link-time optimizer', -checked => 'checked' - ), - ""; - -print ""; - + ),""; print -"

            Would you believe that BitterMelon even has a stopwatch? Click here to get detailed compilation statistic and timings from each pass.

              ", - $c->checkbox( +"

              Bitter Melon can also run the link-time optimizer for you, if you like (but she won't link your code with any libraries). Note that you have to define 'main' in your program for this to make much of a difference.

              "; +print "
            "; + +print $c->checkbox( -name => 'showstats', - -label => 'Show detailed statistics' - ), - ""; - -print ""; - -print "

            And further, the cat can even produce detailed information about the bytecode file generated!", - " Click here to get a detailed description of the various artifacts in the bytecode file your program generates.

              ", - $c->checkbox( + -label => 'Show detailed pass statistics' + ), "
            "; +print +"

            Would you believe that BitterMelon even has a stopwatch? Click here to get detailed compilation statistic and timings from each pass.

            "; +print "
            "; + +print $c->checkbox( -name => 'showbcanalysis', - -label => 'Show detailed bytecode information' - ), - ""; + -label => 'Show detailed bytecode analysis' + ),""; +print "

            And further, the cat can even produce detailed information about the bytecode file generated! Click here to get a detailed description of the various artifacts in the bytecode file your program generates.

            "; + +print "
            "; + +print $c->checkbox( + -name => 'showllvm2cpp', + -label => 'Show corresponding LLVM C++ code' + ),""; +print "

            And, BitterMelon, that fabulously talented cat can even turn your bytecode back into LLVM C++ that would produce the same bytecode! Click here to get a C++ program that generates the equivalent bytecode for your program by direct LLVM IR calls.

            "; print "
            "; @@ -263,6 +264,9 @@ $sanitycheckfail .= ' llvm-bcanalyzer' if `llvm-bcanalyzer --help 2>&1` !~ /bcanalyzer/; + $sanitycheckfail .= ' llvm2cpp' + if `llvm2cpp --help 2>&1` !~ /llvm2cpp/; + barf( "
            The demo page is currently unavailable. [tools: ($sanitycheckfail ) failed sanity check]" ) @@ -434,6 +438,10 @@ try_run( "llvm-bcanalyzer", "llvm-bcanalyzer $bytecodeFile > $analFile 2>&1", $analFile); } + if ($c->param('showllvm2cpp') ) { + my $l2cppFile = getname(".l2cpp"); + try_run("llvm2cpp","llvm2cpp $bytecodeFile -o l2cppFile 2>&1",$l2cppFile); + } addlog( $source, $pid, $UnhilightedResult ); my ( $ip, $host, $lg, $lines ); From reid at x10sys.com Wed Aug 9 17:31:58 2006 From: reid at x10sys.com (Reid Spencer) Date: Wed, 9 Aug 2006 17:31:58 -0500 Subject: [llvm-commits] CVS: llvm-www/demo/index.cgi Message-ID: <200608092231.k79MVwCA009162@zion.cs.uiuc.edu> Changes in directory llvm-www/demo: index.cgi updated: 1.60 -> 1.61 --- Log message: Take llvm2cpp out of the sanity check to restore the demo page. --- Diffs of the changes: (+1 -4) index.cgi | 5 +---- 1 files changed, 1 insertion(+), 4 deletions(-) Index: llvm-www/demo/index.cgi diff -u llvm-www/demo/index.cgi:1.60 llvm-www/demo/index.cgi:1.61 --- llvm-www/demo/index.cgi:1.60 Wed Aug 9 17:28:57 2006 +++ llvm-www/demo/index.cgi Wed Aug 9 17:31:44 2006 @@ -5,7 +5,7 @@ # doing remote web JO99C compilations. (It could still be used for that # purpose, though the two scripts have diverged somewhat.) # -# Last modified $Date: 2006/08/09 22:28:57 $ +# Last modified $Date: 2006/08/09 22:31:44 $ # use strict; @@ -264,9 +264,6 @@ $sanitycheckfail .= ' llvm-bcanalyzer' if `llvm-bcanalyzer --help 2>&1` !~ /bcanalyzer/; - $sanitycheckfail .= ' llvm2cpp' - if `llvm2cpp --help 2>&1` !~ /llvm2cpp/; - barf( "
            The demo page is currently unavailable. [tools: ($sanitycheckfail ) failed sanity check]" ) From reid at x10sys.com Wed Aug 9 17:33:33 2006 From: reid at x10sys.com (Reid Spencer) Date: Wed, 9 Aug 2006 17:33:33 -0500 Subject: [llvm-commits] CVS: llvm-www/demo/index.cgi Message-ID: <200608092233.k79MXXNY009285@zion.cs.uiuc.edu> Changes in directory llvm-www/demo: index.cgi updated: 1.61 -> 1.62 --- Log message: Remove temporary hack! --- Diffs of the changes: (+4 -4) index.cgi | 8 ++++---- 1 files changed, 4 insertions(+), 4 deletions(-) Index: llvm-www/demo/index.cgi diff -u llvm-www/demo/index.cgi:1.61 llvm-www/demo/index.cgi:1.62 --- llvm-www/demo/index.cgi:1.61 Wed Aug 9 17:31:44 2006 +++ llvm-www/demo/index.cgi Wed Aug 9 17:33:19 2006 @@ -5,13 +5,13 @@ # doing remote web JO99C compilations. (It could still be used for that # purpose, though the two scripts have diverged somewhat.) # -# Last modified $Date: 2006/08/09 22:31:44 $ +# Last modified $Date: 2006/08/09 22:33:19 $ # use strict; use CGI; use POSIX; -# use Mail::Send; +use Mail::Send; $| = 1; @@ -105,8 +105,8 @@ sub mailto { my ( $recipient, $body ) = @_; - my $msg = "Nada"; -# new Mail::Send( Subject => "LLVM Demo Page Run", To => $recipient ); + my $msg = + new Mail::Send( Subject => "LLVM Demo Page Run", To => $recipient ); my $fh = $msg->open(); print $fh $body; $fh->close(); From reid at x10sys.com Wed Aug 9 17:47:42 2006 From: reid at x10sys.com (Reid Spencer) Date: Wed, 9 Aug 2006 17:47:42 -0500 Subject: [llvm-commits] CVS: llvm-www/demo/index.cgi Message-ID: <200608092247.k79MlgTF009581@zion.cs.uiuc.edu> Changes in directory llvm-www/demo: index.cgi updated: 1.62 -> 1.63 --- Log message: Make a timeout on the usage lock. --- Diffs of the changes: (+10 -7) index.cgi | 17 ++++++++++------- 1 files changed, 10 insertions(+), 7 deletions(-) Index: llvm-www/demo/index.cgi diff -u llvm-www/demo/index.cgi:1.62 llvm-www/demo/index.cgi:1.63 --- llvm-www/demo/index.cgi:1.62 Wed Aug 9 17:33:19 2006 +++ llvm-www/demo/index.cgi Wed Aug 9 17:47:28 2006 @@ -5,7 +5,7 @@ # doing remote web JO99C compilations. (It could still be used for that # purpose, though the two scripts have diverged somewhat.) # -# Last modified $Date: 2006/08/09 22:33:19 $ +# Last modified $Date: 2006/08/09 22:47:28 $ # use strict; @@ -140,12 +140,15 @@ print ""; } -if ( -f "/tmp/webcompile/locked" ) { - -print "

            Bitter Melon the cat says, 'this page is already in use by someone else at this "; -print "time, try reloading in a second or two. Meow!'

            \n"; -exit 0; - +if ( -f "/tmp/webcompile/locked" ) { + my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$locktime) = + stat("/tmp/webcompile/locked"); + my $currtime = time(); + if ($locktime + 60 > $currtime) { + print "

            Bitter Melon the cat says, 'this page is already in use by someone else at this "; + print "time, try reloading in a second or two. Meow!'

            \n"; + exit 0; + } } system("touch /tmp/webcompile/locked"); From tbrethou at cs.uiuc.edu Wed Aug 9 19:23:18 2006 From: tbrethou at cs.uiuc.edu (Tanya Lattner) Date: Wed, 9 Aug 2006 19:23:18 -0500 Subject: [llvm-commits] CVS: llvm/docs/HowToReleaseLLVM.html Message-ID: <200608100023.k7A0NI4M011639@zion.cs.uiuc.edu> Changes in directory llvm/docs: HowToReleaseLLVM.html updated: 1.8 -> 1.9 --- Log message: Adding notes from release experience. --- Diffs of the changes: (+37 -1) HowToReleaseLLVM.html | 38 +++++++++++++++++++++++++++++++++++++- 1 files changed, 37 insertions(+), 1 deletion(-) Index: llvm/docs/HowToReleaseLLVM.html diff -u llvm/docs/HowToReleaseLLVM.html:1.8 llvm/docs/HowToReleaseLLVM.html:1.9 --- llvm/docs/HowToReleaseLLVM.html:1.8 Tue Apr 11 17:02:18 2006 +++ llvm/docs/HowToReleaseLLVM.html Wed Aug 9 19:23:05 2006 @@ -56,11 +56,13 @@
          • Make LibDeps.txt
          • Settle LLVM HEAD
          • Tag LLVM and Create the Release Branch
          • +
          • Update LLVM Version
          • Build LLVM
          • Run 'make check'
          • Run LLVM Test Suite
          • Build the LLVM Source Distributions
          • Build the LLVM GCC Binary Distribution
          • +
          • Update the LLVM Website
          • @@ -138,12 +140,20 @@ "ROOT_RELEASE_XX" where XX is the major and minor release numbers (you can't have . in a cvs tag name). So, for Release 1.2, XX=12 and for Release 1.10, XX=110. + +

            + cvs tag ROOT_RELEASE_XX
            +

          • Immediately create cvs branches based on the ROOT_RELEASE_XX tag. The tag should be "release_XX" (where XX matches that used for the ROOT_RELEASE_XX tag). This is where the release distribution will be created. + +

            + cvs tag -b -r ROOT_RELEASE_XX release_XX +

          • @@ -165,6 +175,17 @@ + +
            +

            + After creating the llvm release branch, update the release branch's autoconf/configure.ac + version from X.Xcvs to just X.X. Update it on mainline as well to be the next version + (X.X+1cvs). +

            + +
            + +

            @@ -274,6 +295,21 @@

            + + + +
            +

            + Check out the llvm-www module from cvs. Create a new subdirectory X.X in the + releases directory. Place the llvm, llvm-test, llvm-gcc source, and llvm-gcc + binaries in this new directory. Copy the llvm/docs and LICENSE.txt files + into this new directory. Update the releases/download.html file with the new release. + Update the releases/index.html with the new release. Finally, update the main page ( + index.html and sidebar) to point to the new release and release announcement. Make + sure this all gets commited back into cvs. +

            +
            +

    operation never modifies the archive. + + =item q[Rfz] + + Quickly append files to the end of the archive. The F, F, and F + modifiers apply to this operation. This operation quickly adds the + F to the archive without checking for duplicates that should be + removed first. If no F are specified, the archive is not modified. + Because of the way that B constructs the archive file, its dubious + whether the F operation is any faster than the F operation. + + =item r[Rabfuz] + + Replace or insert file members. The F, F, F, F, F, and F + modifiers apply to this operation. This operation will replace existing + F or insert them at the end of the archive if they do not exist. If no + F are specified, the archive is not modified. + + =item t[v] + + Print the table of contents. Without any modifiers, this operation just prints + the names of the members to the standard output. With the F modifier, + B also prints out the file type (B=bytecode, Z=compressed, S=symbol + table, blank=regular file), the permission mode, the owner and group, the + size, and the date. If any F are specified, the listing is only for + those files. If no F are specified, the table of contents for the + whole archive is printed. + + =item x[oP] + + Extract archive members back to files. The F modifier applies to this + operation. This operation retrieves the indicated F from the archive + and writes them back to the operating system's file system. If no + F are specified, the entire archive is extract. + + =back + + =head2 Modifiers (operation specific) + + The modifiers below are specific to certain operations. See the Operations + section (above) to determine which modifiers are applicable to which operations. + + =over + + =item [a] + + When inserting or moving member files, this option specifies the destination of + the new files as being Cfter the F member. If F is not found, + the files are placed at the end of the archive. + + =item [b] + + When inserting or moving member files, this option specifies the destination of + the new files as being Cefore the F member. If F is not + found, the files are placed at the end of the archive. This modifier is + identical to the the F modifier. + + =item [f] + + Normally, B stores the full path name to a file as presented to it on + the command line. With this option, truncated (15 characters max) names are + used. This ensures name compatibility with older versions of C but may also + thwart correct extraction of the files (duplicates may overwrite). If used with + the F option, the directory recursion will be performed but the file names + will all be Clattened to simple file names. + + =item [i] + + A synonym for the F option. + + =item [k] + + Normally, B will not print the contents of bytecode files when the + F