From sabre at nondot.org Mon Dec 28 01:41:18 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 07:41:18 -0000 Subject: [llvm-commits] [llvm] r92206 - in /llvm/trunk/lib/CodeGen/AsmPrinter: DwarfDebug.cpp DwarfException.cpp Message-ID: <200912280741.nBS7fImn000337@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 01:41:18 2009 New Revision: 92206 URL: http://llvm.org/viewvc/llvm-project?rev=92206&view=rev Log: move these out of their own timer groups into the 'uncategorized' groups. Modified: llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp llvm/trunk/lib/CodeGen/AsmPrinter/DwarfException.cpp Modified: llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp?rev=92206&r1=92205&r2=92206&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp (original) +++ llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp Mon Dec 28 01:41:18 2009 @@ -30,11 +30,6 @@ #include "llvm/System/Path.h" using namespace llvm; -static TimerGroup &getDwarfTimerGroup() { - static TimerGroup DwarfTimerGroup("Dwarf Debugging"); - return DwarfTimerGroup; -} - //===----------------------------------------------------------------------===// /// Configuration values for initial hash set sizes (log2). @@ -274,8 +269,7 @@ SectionSourceLines(), didInitial(false), shouldEmit(false), CurrentFnDbgScope(0), DebugTimer(0) { if (TimePassesIsEnabled) - DebugTimer = new Timer("Dwarf Debug Writer", - getDwarfTimerGroup()); + DebugTimer = new Timer("Dwarf Debug Writer"); } DwarfDebug::~DwarfDebug() { for (unsigned j = 0, M = DIEValues.size(); j < M; ++j) Modified: llvm/trunk/lib/CodeGen/AsmPrinter/DwarfException.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/AsmPrinter/DwarfException.cpp?rev=92206&r1=92205&r2=92206&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/AsmPrinter/DwarfException.cpp (original) +++ llvm/trunk/lib/CodeGen/AsmPrinter/DwarfException.cpp Mon Dec 28 01:41:18 2009 @@ -35,19 +35,13 @@ #include "llvm/ADT/StringExtras.h" using namespace llvm; -static TimerGroup &getDwarfTimerGroup() { - static TimerGroup DwarfTimerGroup("DWARF Exception"); - return DwarfTimerGroup; -} - DwarfException::DwarfException(raw_ostream &OS, AsmPrinter *A, const MCAsmInfo *T) : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false), shouldEmitTableModule(false), shouldEmitMovesModule(false), ExceptionTimer(0) { if (TimePassesIsEnabled) - ExceptionTimer = new Timer("DWARF Exception Writer", - getDwarfTimerGroup()); + ExceptionTimer = new Timer("DWARF Exception Writer"); } DwarfException::~DwarfException() { From sabre at nondot.org Mon Dec 28 01:41:54 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 07:41:54 -0000 Subject: [llvm-commits] [llvm] r92207 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp Message-ID: <200912280741.nBS7fsFa000367@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 01:41:54 2009 New Revision: 92207 URL: http://llvm.org/viewvc/llvm-project?rev=92207&view=rev Log: move ElementVH out of the MDNode class into the MDNode.cpp file. Among other things, this avoids vtable and rtti data for it being splatted in every translation unit that uses it. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92207&r1=92206&r2=92207&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 01:41:54 2009 @@ -84,6 +84,9 @@ } }; + +class MDNodeElement; + //===----------------------------------------------------------------------===// /// MDNode - a tuple of other values. /// These contain a list of the values that represent the metadata. @@ -91,29 +94,14 @@ class MDNode : public MetadataBase, public FoldingSetNode { MDNode(const MDNode &); // DO NOT IMPLEMENT - friend class ElementVH; - // Use CallbackVH to hold MDNode elements. - struct ElementVH : public CallbackVH { - MDNode *Parent; - ElementVH() {} - ElementVH(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {} - ~ElementVH() {} - - virtual void deleted() { - Parent->replaceElement(this->operator Value*(), 0); - } - - virtual void allUsesReplacedWith(Value *NV) { - Parent->replaceElement(this->operator Value*(), NV); - } - }; + friend class MDNodeElement; static const unsigned short FunctionLocalBit = 1; // Replace each instance of F from the element list of this node with T. void replaceElement(Value *F, Value *T); - ElementVH *Node; + MDNodeElement *Node; unsigned NodeSize; protected: @@ -128,11 +116,8 @@ ~MDNode(); /// getElement - Return specified element. - Value *getElement(unsigned i) const { - assert(i < getNumElements() && "Invalid element number!"); - return Node[i]; - } - + Value *getElement(unsigned i) const; + /// getNumElements - Return number of MDNode elements. unsigned getNumElements() const { return NodeSize; } Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92207&r1=92206&r2=92207&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 01:41:54 2009 @@ -47,16 +47,46 @@ } //===----------------------------------------------------------------------===// +// MDNodeElement implementation. +// + +// Use CallbackVH to hold MDNode elements. +namespace llvm { +class MDNodeElement : public CallbackVH { + MDNode *Parent; +public: + MDNodeElement() {} + MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {} + ~MDNodeElement() {} + + virtual void deleted(); + virtual void allUsesReplacedWith(Value *NV); +}; +} // end namespace llvm. + + +void MDNodeElement::deleted() { + Parent->replaceElement(this->operator Value*(), 0); +} + +void MDNodeElement::allUsesReplacedWith(Value *NV) { + Parent->replaceElement(this->operator Value*(), NV); +} + + + +//===----------------------------------------------------------------------===// // MDNode implementation. // + MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, bool isFunctionLocal) : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) { NodeSize = NumVals; - Node = new ElementVH[NodeSize]; - ElementVH *Ptr = Node; + Node = new MDNodeElement[NodeSize]; + MDNodeElement *Ptr = Node; for (unsigned i = 0; i != NumVals; ++i) - *Ptr++ = ElementVH(Vals[i], this); + *Ptr++ = MDNodeElement(Vals[i], this); if (isFunctionLocal) SubclassData |= FunctionLocalBit; } @@ -91,6 +121,14 @@ Node = NULL; } +/// getElement - Return specified element. +Value *MDNode::getElement(unsigned i) const { + assert(i < getNumElements() && "Invalid element number!"); + return Node[i]; +} + + + // Replace value from this node's element list. void MDNode::replaceElement(Value *From, Value *To) { if (From == To || !getType()) @@ -119,7 +157,7 @@ for (SmallVector::iterator I = Indexes.begin(), E = Indexes.end(); I != E; ++I) { unsigned Index = *I; - Node[Index] = ElementVH(To, this); + Node[Index] = MDNodeElement(To, this); } // Insert updated "this" into the context's folding node set. From sabre at nondot.org Mon Dec 28 01:57:01 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 07:57:01 -0000 Subject: [llvm-commits] [llvm] r92208 - in /llvm/trunk: include/llvm/Metadata.h lib/Bitcode/Writer/ValueEnumerator.cpp Message-ID: <200912280757.nBS7v168000817@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 01:57:01 2009 New Revision: 92208 URL: http://llvm.org/viewvc/llvm-project?rev=92208&view=rev Log: eliminate the elem_* iterator stuff from NamedMDNode. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92208&r1=92207&r2=92208&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 01:57:01 2009 @@ -203,15 +203,6 @@ Node.push_back(TrackingVH(M)); } - typedef SmallVectorImpl >::iterator elem_iterator; - typedef SmallVectorImpl >::const_iterator - const_elem_iterator; - bool elem_empty() const { return Node.empty(); } - const_elem_iterator elem_begin() const { return Node.begin(); } - const_elem_iterator elem_end() const { return Node.end(); } - elem_iterator elem_begin() { return Node.begin(); } - elem_iterator elem_end() { return Node.end(); } - /// Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const NamedMDNode *) { return true; } static bool classof(const Value *V) { Modified: llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp?rev=92208&r1=92207&r2=92208&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp Mon Dec 28 01:57:01 2009 @@ -226,11 +226,8 @@ } if (const NamedMDNode *N = dyn_cast(MD)) { - for(NamedMDNode::const_elem_iterator I = N->elem_begin(), - E = N->elem_end(); I != E; ++I) { - MetadataBase *M = *I; - EnumerateValue(M); - } + for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) + EnumerateValue(N->getElement(i)); MDValues.push_back(std::make_pair(MD, 1U)); MDValueMap[MD] = Values.size(); return; From sabre at nondot.org Mon Dec 28 02:07:15 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 08:07:15 -0000 Subject: [llvm-commits] [llvm] r92209 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp Message-ID: <200912280807.nBS87FTw001106@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 02:07:14 2009 New Revision: 92209 URL: http://llvm.org/viewvc/llvm-project?rev=92209&view=rev Log: change NamedMDNode to use a pimpl for its operand list instead of making it a declared part of the value. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92209&r1=92208&r2=92209&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 02:07:14 2009 @@ -158,7 +158,7 @@ NamedMDNode(const NamedMDNode &); // DO NOT IMPLEMENT Module *Parent; - SmallVector, 4> Node; + void *Operands; // SmallVector, 4> void setParent(Module *M) { Parent = M; } protected: @@ -188,21 +188,14 @@ inline const Module *getParent() const { return Parent; } /// getElement - Return specified element. - MetadataBase *getElement(unsigned i) const { - assert(i < getNumElements() && "Invalid element number!"); - return Node[i]; - } - + MetadataBase *getElement(unsigned i) const; + /// getNumElements - Return number of NamedMDNode elements. - unsigned getNumElements() const { - return (unsigned)Node.size(); - } + unsigned getNumElements() const; /// addElement - Add metadata element. - void addElement(MetadataBase *M) { - Node.push_back(TrackingVH(M)); - } - + void addElement(MetadataBase *M); + /// Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const NamedMDNode *) { return true; } static bool classof(const Value *V) { Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92209&r1=92208&r2=92209&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 02:07:14 2009 @@ -226,12 +226,19 @@ //===----------------------------------------------------------------------===// // NamedMDNode implementation. // +static SmallVector, 4> &getNMDOps(void *Operands) { + return *(SmallVector, 4>*)Operands; +} + NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N, MetadataBase *const *MDs, unsigned NumMDs, Module *ParentModule) : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) { setName(N); - + + Operands = new SmallVector, 4>(); + + SmallVector, 4> &Node = getNMDOps(Operands); for (unsigned i = 0; i != NumMDs; ++i) Node.push_back(TrackingVH(MDs[i])); @@ -242,12 +249,35 @@ NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) { assert(NMD && "Invalid source NamedMDNode!"); SmallVector Elems; + Elems.reserve(NMD->getNumElements()); + for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) Elems.push_back(NMD->getElement(i)); return new NamedMDNode(NMD->getContext(), NMD->getName().data(), Elems.data(), Elems.size(), M); } +NamedMDNode::~NamedMDNode() { + dropAllReferences(); + delete &getNMDOps(Operands); +} + +/// getNumElements - Return number of NamedMDNode elements. +unsigned NamedMDNode::getNumElements() const { + return (unsigned)getNMDOps(Operands).size(); +} + +/// getElement - Return specified element. +MetadataBase *NamedMDNode::getElement(unsigned i) const { + assert(i < getNumElements() && "Invalid element number!"); + return getNMDOps(Operands)[i]; +} + +/// addElement - Add metadata element. +void NamedMDNode::addElement(MetadataBase *M) { + getNMDOps(Operands).push_back(TrackingVH(M)); +} + /// eraseFromParent - Drop all references and remove the node from parent /// module. void NamedMDNode::eraseFromParent() { @@ -256,12 +286,9 @@ /// dropAllReferences - Remove all uses and clear node vector. void NamedMDNode::dropAllReferences() { - Node.clear(); + getNMDOps(Operands).clear(); } -NamedMDNode::~NamedMDNode() { - dropAllReferences(); -} //===----------------------------------------------------------------------===// // MetadataContextImpl implementation. From sabre at nondot.org Mon Dec 28 02:14:55 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 08:14:55 -0000 Subject: [llvm-commits] [llvm] r92210 - in /llvm/trunk: include/llvm/Metadata.h lib/Bitcode/Writer/BitcodeWriter.cpp lib/Bitcode/Writer/ValueEnumerator.cpp lib/VMCore/AsmWriter.cpp lib/VMCore/Metadata.cpp Message-ID: <200912280814.nBS8Et36001371@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 02:14:54 2009 New Revision: 92210 URL: http://llvm.org/viewvc/llvm-project?rev=92210&view=rev Log: change the strange MetadataContext::getMDs function to expose less irrelevant internal implementation details to clients. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp llvm/trunk/lib/VMCore/AsmWriter.cpp llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92210&r1=92209&r2=92210&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 02:14:54 2009 @@ -236,7 +236,7 @@ /// getMDs - Get the metadata attached to an Instruction. void getMDs(const Instruction *Inst, - SmallVectorImpl > > &MDs) const; + SmallVectorImpl > &MDs) const; /// addMD - Attach the metadata of given kind to an Instruction. void addMD(unsigned Kind, MDNode *Node, Instruction *Inst); Modified: llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp?rev=92210&r1=92209&r2=92210&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp Mon Dec 28 02:14:54 2009 @@ -562,7 +562,7 @@ // Write metadata attachments // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] MetadataContext &TheMetadata = F.getContext().getMetadata(); - typedef SmallVector >, 2> MDMapTy; + typedef SmallVector, 2> MDMapTy; MDMapTy MDs; for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); Modified: llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp?rev=92210&r1=92209&r2=92210&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp Mon Dec 28 02:14:54 2009 @@ -88,7 +88,7 @@ EnumerateType(I->getType()); MetadataContext &TheMetadata = F->getContext().getMetadata(); - typedef SmallVector >, 2> MDMapTy; + typedef SmallVector, 2> MDMapTy; MDMapTy MDs; for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){ Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92210&r1=92209&r2=92210&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Mon Dec 28 02:14:54 2009 @@ -681,7 +681,7 @@ ST_DEBUG("Inserting Instructions:\n"); MetadataContext &TheMetadata = TheFunction->getContext().getMetadata(); - typedef SmallVector >, 2> MDMapTy; + typedef SmallVector, 2> MDMapTy; MDMapTy MDs; // Add all of the basic blocks and instructions with no names. @@ -2085,7 +2085,7 @@ // Print Metadata info if (!MDNames.empty()) { MetadataContext &TheMetadata = I.getContext().getMetadata(); - typedef SmallVector >, 2> MDMapTy; + typedef SmallVector, 2> MDMapTy; MDMapTy MDs; TheMetadata.getMDs(&I, MDs); for (MDMapTy::const_iterator MI = MDs.begin(), ME = MDs.end(); MI != ME; Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92210&r1=92209&r2=92210&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 02:14:54 2009 @@ -322,7 +322,8 @@ MDNode *getMD(unsigned Kind, const Instruction *Inst); /// getMDs - Get the metadata attached to an Instruction. - void getMDs(const Instruction *Inst, SmallVectorImpl &MDs) const; + void getMDs(const Instruction *Inst, + SmallVectorImpl > &MDs) const; /// addMD - Attach the metadata of given kind to an Instruction. void addMD(unsigned Kind, MDNode *Node, Instruction *Inst); @@ -447,7 +448,8 @@ /// getMDs - Get the metadata attached to an Instruction. void MetadataContextImpl:: -getMDs(const Instruction *Inst, SmallVectorImpl &MDs) const { +getMDs(const Instruction *Inst, + SmallVectorImpl > &MDs) const { MDStoreTy::const_iterator I = MetadataStore.find(Inst); if (I == MetadataStore.end()) return; @@ -542,7 +544,7 @@ /// getMDs - Get the metadata attached to an Instruction. void MetadataContext:: getMDs(const Instruction *Inst, - SmallVectorImpl > > &MDs) const { + SmallVectorImpl > &MDs) const { return pImpl->getMDs(Inst, MDs); } From sabre at nondot.org Mon Dec 28 02:20:47 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 08:20:47 -0000 Subject: [llvm-commits] [llvm] r92211 - in /llvm/trunk: include/llvm/CodeGen/MachineModuleInfo.h include/llvm/Metadata.h lib/AsmParser/LLParser.h lib/Transforms/Scalar/JumpThreading.cpp Message-ID: <200912280820.nBS8Klb8001574@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 02:20:46 2009 New Revision: 92211 URL: http://llvm.org/viewvc/llvm-project?rev=92211&view=rev Log: Metadata.h doesn't need to include ValueHandle.h anymore. Modified: llvm/trunk/include/llvm/CodeGen/MachineModuleInfo.h llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/AsmParser/LLParser.h llvm/trunk/lib/Transforms/Scalar/JumpThreading.cpp Modified: llvm/trunk/include/llvm/CodeGen/MachineModuleInfo.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/CodeGen/MachineModuleInfo.h?rev=92211&r1=92210&r2=92211&view=diff ============================================================================== --- llvm/trunk/include/llvm/CodeGen/MachineModuleInfo.h (original) +++ llvm/trunk/include/llvm/CodeGen/MachineModuleInfo.h Mon Dec 28 02:20:46 2009 @@ -43,6 +43,7 @@ #include "llvm/GlobalValue.h" #include "llvm/Pass.h" #include "llvm/Metadata.h" +#include "llvm/Support/ValueHandle.h" namespace llvm { Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92211&r1=92210&r2=92211&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 02:20:46 2009 @@ -22,7 +22,6 @@ #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/ilist_node.h" -#include "llvm/Support/ValueHandle.h" namespace llvm { class Constant; Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92211&r1=92210&r2=92211&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Mon Dec 28 02:20:46 2009 @@ -18,6 +18,7 @@ #include "llvm/Module.h" #include "llvm/Type.h" #include +#include "llvm/Support/ValueHandle.h" namespace llvm { class Module; Modified: llvm/trunk/lib/Transforms/Scalar/JumpThreading.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/JumpThreading.cpp?rev=92211&r1=92210&r2=92211&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/JumpThreading.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/JumpThreading.cpp Mon Dec 28 02:20:46 2009 @@ -29,6 +29,7 @@ #include "llvm/ADT/SmallSet.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/ValueHandle.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; From sabre at nondot.org Mon Dec 28 02:24:17 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 08:24:17 -0000 Subject: [llvm-commits] [llvm] r92212 - in /llvm/trunk/lib/VMCore: LLVMContext.cpp Metadata.cpp Message-ID: <200912280824.nBS8OHoB001690@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 02:24:16 2009 New Revision: 92212 URL: http://llvm.org/viewvc/llvm-project?rev=92212&view=rev Log: prune some #includes Modified: llvm/trunk/lib/VMCore/LLVMContext.cpp llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/lib/VMCore/LLVMContext.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/LLVMContext.cpp?rev=92212&r1=92211&r2=92212&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/LLVMContext.cpp (original) +++ llvm/trunk/lib/VMCore/LLVMContext.cpp Mon Dec 28 02:24:16 2009 @@ -19,7 +19,6 @@ #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/ValueHandle.h" #include "LLVMContextImpl.h" -#include using namespace llvm; Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92212&r1=92211&r2=92212&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 02:24:16 2009 @@ -11,14 +11,15 @@ // //===----------------------------------------------------------------------===// -#include "LLVMContextImpl.h" #include "llvm/Metadata.h" +#include "LLVMContextImpl.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Instruction.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/StringMap.h" #include "SymbolTableListTraitsImpl.h" +#include "llvm/Support/ValueHandle.h" using namespace llvm; //===----------------------------------------------------------------------===// From sabre at nondot.org Mon Dec 28 02:26:43 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 08:26:43 -0000 Subject: [llvm-commits] [llvm] r92213 - /llvm/trunk/include/llvm/Metadata.h Message-ID: <200912280826.nBS8Qhi4001768@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 02:26:43 2009 New Revision: 92213 URL: http://llvm.org/viewvc/llvm-project?rev=92213&view=rev Log: prune #includes more. Modified: llvm/trunk/include/llvm/Metadata.h Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92213&r1=92212&r2=92213&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 02:26:43 2009 @@ -19,8 +19,6 @@ #include "llvm/Value.h" #include "llvm/Type.h" #include "llvm/ADT/FoldingSet.h" -#include "llvm/ADT/SmallPtrSet.h" -#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/ilist_node.h" namespace llvm { @@ -28,6 +26,8 @@ class Instruction; class LLVMContext; class MetadataContextImpl; +template class SmallVectorImpl; +template class SmallPtrSet; //===----------------------------------------------------------------------===// // MetadataBase - A base class for MDNode, MDString and NamedMDNode. From sabre at nondot.org Mon Dec 28 02:30:44 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 08:30:44 -0000 Subject: [llvm-commits] [llvm] r92214 - in /llvm/trunk: include/llvm/Metadata.h lib/CodeGen/MachineInstr.cpp lib/VMCore/Metadata.cpp Message-ID: <200912280830.nBS8Uic9001911@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 02:30:43 2009 New Revision: 92214 URL: http://llvm.org/viewvc/llvm-project?rev=92214&view=rev Log: snip one more #include from Metadata.h Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/CodeGen/MachineInstr.cpp llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92214&r1=92213&r2=92214&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 02:30:43 2009 @@ -17,7 +17,6 @@ #define LLVM_METADATA_H #include "llvm/Value.h" -#include "llvm/Type.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ilist_node.h" @@ -25,6 +24,7 @@ class Constant; class Instruction; class LLVMContext; +class Module; class MetadataContextImpl; template class SmallVectorImpl; template class SmallPtrSet; @@ -55,8 +55,7 @@ StringRef Str; protected: - explicit MDString(LLVMContext &C, StringRef S) - : MetadataBase(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {} + explicit MDString(LLVMContext &C, StringRef S); public: static MDString *get(LLVMContext &Context, StringRef Str); Modified: llvm/trunk/lib/CodeGen/MachineInstr.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/MachineInstr.cpp?rev=92214&r1=92213&r2=92214&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/MachineInstr.cpp (original) +++ llvm/trunk/lib/CodeGen/MachineInstr.cpp Mon Dec 28 02:30:43 2009 @@ -15,6 +15,7 @@ #include "llvm/Constants.h" #include "llvm/Function.h" #include "llvm/InlineAsm.h" +#include "llvm/Type.h" #include "llvm/Value.h" #include "llvm/Assembly/Writer.h" #include "llvm/CodeGen/MachineFunction.h" Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92214&r1=92213&r2=92214&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 02:30:43 2009 @@ -29,6 +29,10 @@ //===----------------------------------------------------------------------===// // MDString implementation. // + +MDString::MDString(LLVMContext &C, StringRef S) + : MetadataBase(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {} + MDString *MDString::get(LLVMContext &Context, StringRef Str) { LLVMContextImpl *pImpl = Context.pImpl; StringMapEntry &Entry = From sabre at nondot.org Mon Dec 28 02:45:45 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 08:45:45 -0000 Subject: [llvm-commits] [llvm-gcc-4.2] r92215 - /llvm-gcc-4.2/trunk/gcc/llvm-linker-hack.cpp Message-ID: <200912280845.nBS8jjSM007850@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 02:45:45 2009 New Revision: 92215 URL: http://llvm.org/viewvc/llvm-project?rev=92215&view=rev Log: add #include that this was getting implicitly before. Modified: llvm-gcc-4.2/trunk/gcc/llvm-linker-hack.cpp Modified: llvm-gcc-4.2/trunk/gcc/llvm-linker-hack.cpp URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/gcc/llvm-linker-hack.cpp?rev=92215&r1=92214&r2=92215&view=diff ============================================================================== --- llvm-gcc-4.2/trunk/gcc/llvm-linker-hack.cpp (original) +++ llvm-gcc-4.2/trunk/gcc/llvm-linker-hack.cpp Mon Dec 28 02:45:45 2009 @@ -22,6 +22,7 @@ #include "llvm/LLVMContext.h" #include "llvm/Module.h" +#include "llvm/Type.h" #include "llvm/ModuleProvider.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Analysis/DebugInfo.h" From sabre at nondot.org Mon Dec 28 02:48:12 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 08:48:12 -0000 Subject: [llvm-commits] [llvm] r92216 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp Message-ID: <200912280848.nBS8mCal008808@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 02:48:12 2009 New Revision: 92216 URL: http://llvm.org/viewvc/llvm-project?rev=92216&view=rev Log: rename MDNode instance variables to something meaningful. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92216&r1=92215&r2=92216&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 02:48:12 2009 @@ -99,8 +99,8 @@ // Replace each instance of F from the element list of this node with T. void replaceElement(Value *F, Value *T); - MDNodeElement *Node; - unsigned NodeSize; + MDNodeElement *Operands; + unsigned NumOperands; protected: explicit MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, @@ -117,7 +117,7 @@ Value *getElement(unsigned i) const; /// getNumElements - Return number of MDNode elements. - unsigned getNumElements() const { return NodeSize; } + unsigned getNumElements() const { return NumOperands; } /// isFunctionLocal - Return whether MDNode is local to a function. /// Note: MDNodes are designated as function-local when created, and keep Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92216&r1=92215&r2=92216&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 02:48:12 2009 @@ -87,11 +87,12 @@ MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, bool isFunctionLocal) : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) { - NodeSize = NumVals; - Node = new MDNodeElement[NodeSize]; - MDNodeElement *Ptr = Node; + NumOperands = NumVals; + Operands = new MDNodeElement[NumOperands]; + MDNodeElement *Ptr = Operands; for (unsigned i = 0; i != NumVals; ++i) - *Ptr++ = MDNodeElement(Vals[i], this); + Ptr[i] = MDNodeElement(Vals[i], this); + if (isFunctionLocal) SubclassData |= FunctionLocalBit; } @@ -122,14 +123,14 @@ MDNode::~MDNode() { LLVMContextImpl *pImpl = getType()->getContext().pImpl; pImpl->MDNodeSet.RemoveNode(this); - delete [] Node; - Node = NULL; + delete [] Operands; + Operands = NULL; } /// getElement - Return specified element. Value *MDNode::getElement(unsigned i) const { assert(i < getNumElements() && "Invalid element number!"); - return Node[i]; + return Operands[i]; } @@ -161,8 +162,7 @@ // Replace From element(s) in place. for (SmallVector::iterator I = Indexes.begin(), E = Indexes.end(); I != E; ++I) { - unsigned Index = *I; - Node[Index] = MDNodeElement(To, this); + Operands[*I] = MDNodeElement(To, this); } // Insert updated "this" into the context's folding node set. From sabre at nondot.org Mon Dec 28 03:07:22 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 09:07:22 -0000 Subject: [llvm-commits] [llvm] r92217 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp lib/VMCore/Verifier.cpp Message-ID: <200912280907.nBS97Mae017422@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 03:07:21 2009 New Revision: 92217 URL: http://llvm.org/viewvc/llvm-project?rev=92217&view=rev Log: Rewrite the function-local validation logic for MDNodes (most of r91708). Among other benefits, this doesn't leak the SmallPtrSet, has the verifier code in the verifier pass, actually does the verification at the end, and is considerably simpler. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Metadata.cpp llvm/trunk/lib/VMCore/Verifier.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92217&r1=92216&r2=92217&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 03:07:21 2009 @@ -27,7 +27,6 @@ class Module; class MetadataContextImpl; template class SmallVectorImpl; -template class SmallPtrSet; //===----------------------------------------------------------------------===// // MetadataBase - A base class for MDNode, MDString and NamedMDNode. @@ -91,17 +90,20 @@ /// MDNode is always unnamed. class MDNode : public MetadataBase, public FoldingSetNode { MDNode(const MDNode &); // DO NOT IMPLEMENT - + void operator=(const MDNode &); // DO NOT IMPLEMENT friend class MDNodeElement; + + MDNodeElement *Operands; + unsigned NumOperands; - static const unsigned short FunctionLocalBit = 1; + // Subclass data enums. + enum { + FunctionLocalBit = 1 + }; // Replace each instance of F from the element list of this node with T. void replaceElement(Value *F, Value *T); - MDNodeElement *Operands; - unsigned NumOperands; - protected: explicit MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, bool isFunctionLocal); @@ -125,13 +127,6 @@ /// refer to function-local IR. bool isFunctionLocal() const { return SubclassData & FunctionLocalBit; } - /// getLocalFunction - Return false if MDNode's recursive function-localness - /// is invalid (local to more than one function). Return true otherwise. - /// If MDNode has one function to which it is local, set LocalFunction to that - /// function. - bool getLocalFunction(Function *LocalFunction, - SmallPtrSet *VisitedMDNodes = NULL); - /// Profile - calculate a unique identifier for this MDNode to collapse /// duplicates void Profile(FoldingSetNodeID &ID) const; Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92217&r1=92216&r2=92217&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 03:07:21 2009 @@ -188,46 +188,6 @@ } } -// getLocalFunction - Return false if MDNode's recursive function-localness is -// invalid (local to more than one function). Return true otherwise. If MDNode -// has one function to which it is local, set LocalFunction to that function. -bool MDNode::getLocalFunction(Function *LocalFunction, - SmallPtrSet *VisitedMDNodes) { - if (!isFunctionLocal()) - return true; - - if (!VisitedMDNodes) - VisitedMDNodes = new SmallPtrSet(); - - if (!VisitedMDNodes->insert(this)) - // MDNode has already been visited, nothing to do. - return true; - - for (unsigned i = 0, e = getNumElements(); i != e; ++i) { - Value *V = getElement(i); - if (!V) continue; - - Function *LocalFunctionTemp = NULL; - if (Instruction *I = dyn_cast(V)) - LocalFunctionTemp = I->getParent()->getParent(); - else if (MDNode *MD = dyn_cast(V)) - if (!MD->getLocalFunction(LocalFunctionTemp, VisitedMDNodes)) - // This MDNode's operand is function-locally invalid or local to a - // different function. - return false; - - if (LocalFunctionTemp) { - if (!LocalFunction) - LocalFunction = LocalFunctionTemp; - else if (LocalFunction != LocalFunctionTemp) - // This MDNode contains operands that are local to different functions. - return false; - } - } - - return true; -} - //===----------------------------------------------------------------------===// // NamedMDNode implementation. // Modified: llvm/trunk/lib/VMCore/Verifier.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Verifier.cpp?rev=92217&r1=92216&r2=92217&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Verifier.cpp (original) +++ llvm/trunk/lib/VMCore/Verifier.cpp Mon Dec 28 03:07:21 2009 @@ -329,6 +329,8 @@ int VT, unsigned ArgNo, std::string &Suffix); void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F, unsigned RetNum, unsigned ParamNum, ...); + void VerifyFunctionLocalMetadata(MDNode *N, Function *F, + SmallPtrSet &Visited); void VerifyParameterAttrs(Attributes Attrs, const Type *Ty, bool isReturnValue, const Value *V); void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs, @@ -1526,6 +1528,38 @@ } } +/// VerifyFunctionLocalMetadata - Verify that the specified MDNode is local to +/// specified Function. +void Verifier::VerifyFunctionLocalMetadata(MDNode *N, Function *F, + SmallPtrSet &Visited) { + assert(N->isFunctionLocal() && "Should only be called on function-local MD"); + + // Only visit each node once. + if (!Visited.insert(N)) + return; + + for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) { + Value *V = N->getElement(i); + if (!V) continue; + + Function *ActualF = 0; + if (Instruction *I = dyn_cast(V)) + ActualF = I->getParent()->getParent(); + else if (BasicBlock *BB = dyn_cast(V)) + ActualF = BB->getParent(); + else if (Argument *A = dyn_cast(V)) + ActualF = A->getParent(); + else if (MDNode *MD = dyn_cast(V)) + if (MD->isFunctionLocal()) + VerifyFunctionLocalMetadata(MD, F, Visited); + + // If this was an instruction, bb, or argument, verify that it is in the + // function that we expect. + Assert1(ActualF == 0 || ActualF == F, + "function-local metadata used in wrong function", N); + } +} + // Flags used by TableGen to mark intrinsic parameters with the // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes. static const unsigned ExtendedElementVectorType = 0x40000000; @@ -1542,14 +1576,13 @@ #include "llvm/Intrinsics.gen" #undef GET_INTRINSIC_VERIFIER + // If the intrinsic takes MDNode arguments, verify that they are either global + // or are local to *this* function. for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i) if (MDNode *MD = dyn_cast(CI.getOperand(i))) { - Function* LocalFunction = NULL; - Assert1(MD && MD->getLocalFunction(LocalFunction), - "invalid function-local metadata", &CI); - if (LocalFunction) - Assert1(LocalFunction == CI.getParent()->getParent(), - "function-local metadata used in wrong function", &CI); + if (!MD->isFunctionLocal()) continue; + SmallPtrSet Visited; + VerifyFunctionLocalMetadata(MD, CI.getParent()->getParent(), Visited); } switch (ID) { From sabre at nondot.org Mon Dec 28 03:10:16 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 09:10:16 -0000 Subject: [llvm-commits] [llvm] r92218 - /llvm/trunk/lib/VMCore/Metadata.cpp Message-ID: <200912280910.nBS9AGD0017721@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 03:10:16 2009 New Revision: 92218 URL: http://llvm.org/viewvc/llvm-project?rev=92218&view=rev Log: avoid temporary CallbackVH's. Modified: llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92218&r1=92217&r2=92218&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 03:10:16 2009 @@ -64,6 +64,11 @@ MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {} ~MDNodeElement() {} + void set(Value *V, MDNode *P) { + setValPtr(V); + Parent = P; + } + virtual void deleted(); virtual void allUsesReplacedWith(Value *NV); }; @@ -91,7 +96,7 @@ Operands = new MDNodeElement[NumOperands]; MDNodeElement *Ptr = Operands; for (unsigned i = 0; i != NumVals; ++i) - Ptr[i] = MDNodeElement(Vals[i], this); + Ptr[i].set(Vals[i], this); if (isFunctionLocal) SubclassData |= FunctionLocalBit; @@ -161,9 +166,8 @@ // Replace From element(s) in place. for (SmallVector::iterator I = Indexes.begin(), E = Indexes.end(); - I != E; ++I) { - Operands[*I] = MDNodeElement(To, this); - } + I != E; ++I) + Operands[*I].set(To, this); // Insert updated "this" into the context's folding node set. // If a node with same element list already exist then before inserting From sabre at nondot.org Mon Dec 28 03:12:36 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 09:12:36 -0000 Subject: [llvm-commits] [llvm] r92219 - /llvm/trunk/lib/VMCore/Metadata.cpp Message-ID: <200912280912.nBS9CaGL017802@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 03:12:35 2009 New Revision: 92219 URL: http://llvm.org/viewvc/llvm-project?rev=92219&view=rev Log: rearrange some methods, no functionality change. Modified: llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92219&r1=92218&r2=92219&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 03:12:35 2009 @@ -89,24 +89,27 @@ // MDNode implementation. // +/// ~MDNode - Destroy MDNode. +MDNode::~MDNode() { + LLVMContextImpl *pImpl = getType()->getContext().pImpl; + pImpl->MDNodeSet.RemoveNode(this); + delete [] Operands; + Operands = NULL; +} + MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, bool isFunctionLocal) : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) { NumOperands = NumVals; Operands = new MDNodeElement[NumOperands]; - MDNodeElement *Ptr = Operands; + for (unsigned i = 0; i != NumVals; ++i) - Ptr[i].set(Vals[i], this); + Operands[i].set(Vals[i], this); if (isFunctionLocal) SubclassData |= FunctionLocalBit; } -void MDNode::Profile(FoldingSetNodeID &ID) const { - for (unsigned i = 0, e = getNumElements(); i != e; ++i) - ID.AddPointer(getElement(i)); -} - MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals, bool isFunctionLocal) { LLVMContextImpl *pImpl = Context.pImpl; @@ -124,14 +127,12 @@ return N; } -/// ~MDNode - Destroy MDNode. -MDNode::~MDNode() { - LLVMContextImpl *pImpl = getType()->getContext().pImpl; - pImpl->MDNodeSet.RemoveNode(this); - delete [] Operands; - Operands = NULL; +void MDNode::Profile(FoldingSetNodeID &ID) const { + for (unsigned i = 0, e = getNumElements(); i != e; ++i) + ID.AddPointer(getElement(i)); } + /// getElement - Return specified element. Value *MDNode::getElement(unsigned i) const { assert(i < getNumElements() && "Invalid element number!"); From sabre at nondot.org Mon Dec 28 03:24:53 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 09:24:53 -0000 Subject: [llvm-commits] [llvm] r92220 - /llvm/trunk/lib/VMCore/Metadata.cpp Message-ID: <200912280924.nBS9OrX0018195@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 03:24:53 2009 New Revision: 92220 URL: http://llvm.org/viewvc/llvm-project?rev=92220&view=rev Log: Eliminate two bits of ugliness in MDNode::replaceElement: eliminate the temporary smallvector, and only do FindNodeOrInsertPos twice if the first one succeeds and we delete a node. Modified: llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92220&r1=92219&r2=92220&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 03:24:53 2009 @@ -145,31 +145,21 @@ void MDNode::replaceElement(Value *From, Value *To) { if (From == To || !getType()) return; - LLVMContext &Context = getType()->getContext(); - LLVMContextImpl *pImpl = Context.pImpl; + LLVMContextImpl *pImpl = getType()->getContext().pImpl; + + // Remove "this" from the context map. FoldingSet doesn't have to reprofile + // this node to remove it, so we don't care what state the operands are in. + pImpl->MDNodeSet.RemoveNode(this); + // Find value. This is a linear search, do something if it consumes // lot of time. It is possible that to have multiple instances of // From in this MDNode's element list. - SmallVector Indexes; - unsigned Index = 0; - for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) { - Value *V = getElement(i); - if (V && V == From) - Indexes.push_back(Index); + for (unsigned i = 0, e = getNumElements(); i != e; ++i) { + if (Operands[i] == From) + Operands[i].set(To, this); } - if (Indexes.empty()) - return; - - // Remove "this" from the context map. - pImpl->MDNodeSet.RemoveNode(this); - - // Replace From element(s) in place. - for (SmallVector::iterator I = Indexes.begin(), E = Indexes.end(); - I != E; ++I) - Operands[*I].set(To, this); - // Insert updated "this" into the context's folding node set. // If a node with same element list already exist then before inserting // updated "this" into the folding node set, replace all uses of existing @@ -182,15 +172,12 @@ if (N) { N->replaceAllUsesWith(this); delete N; - N = 0; + N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); + assert(N == 0 && "shouldn't be in the map now!"); (void)N; } - N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); - if (!N) { - // InsertPoint will have been set by the FindNodeOrInsertPos call. - N = this; - pImpl->MDNodeSet.InsertNode(N, InsertPoint); - } + // InsertPoint will have been set by the FindNodeOrInsertPos call. + pImpl->MDNodeSet.InsertNode(this, InsertPoint); } //===----------------------------------------------------------------------===// From nicholas at mxc.ca Mon Dec 28 03:26:35 2009 From: nicholas at mxc.ca (Nick Lewycky) Date: Mon, 28 Dec 2009 04:26:35 -0500 Subject: [llvm-commits] [llvm] r92216 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp In-Reply-To: <200912280848.nBS8mCal008808@zion.cs.uiuc.edu> References: <200912280848.nBS8mCal008808@zion.cs.uiuc.edu> Message-ID: <4B3879CB.6030105@mxc.ca> Chris Lattner wrote: > Author: lattner > Date: Mon Dec 28 02:48:12 2009 > New Revision: 92216 > > URL: http://llvm.org/viewvc/llvm-project?rev=92216&view=rev > Log: > rename MDNode instance variables to something meaningful. > Please name them Elements instead of Operands. There's a lot of great invariants that apply to operands which don't exist on MDNode elements. Nick > Modified: > llvm/trunk/include/llvm/Metadata.h > llvm/trunk/lib/VMCore/Metadata.cpp > > Modified: llvm/trunk/include/llvm/Metadata.h > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92216&r1=92215&r2=92216&view=diff > > ============================================================================== > --- llvm/trunk/include/llvm/Metadata.h (original) > +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 02:48:12 2009 > @@ -99,8 +99,8 @@ > // Replace each instance of F from the element list of this node with T. > void replaceElement(Value *F, Value *T); > > - MDNodeElement *Node; > - unsigned NodeSize; > + MDNodeElement *Operands; > + unsigned NumOperands; > > protected: > explicit MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, > @@ -117,7 +117,7 @@ > Value *getElement(unsigned i) const; > > /// getNumElements - Return number of MDNode elements. > - unsigned getNumElements() const { return NodeSize; } > + unsigned getNumElements() const { return NumOperands; } > > /// isFunctionLocal - Return whether MDNode is local to a function. > /// Note: MDNodes are designated as function-local when created, and keep > > Modified: llvm/trunk/lib/VMCore/Metadata.cpp > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92216&r1=92215&r2=92216&view=diff > > ============================================================================== > --- llvm/trunk/lib/VMCore/Metadata.cpp (original) > +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 02:48:12 2009 > @@ -87,11 +87,12 @@ > MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, > bool isFunctionLocal) > : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) { > - NodeSize = NumVals; > - Node = new MDNodeElement[NodeSize]; > - MDNodeElement *Ptr = Node; > + NumOperands = NumVals; > + Operands = new MDNodeElement[NumOperands]; > + MDNodeElement *Ptr = Operands; > for (unsigned i = 0; i != NumVals; ++i) > - *Ptr++ = MDNodeElement(Vals[i], this); > + Ptr[i] = MDNodeElement(Vals[i], this); > + > if (isFunctionLocal) > SubclassData |= FunctionLocalBit; > } > @@ -122,14 +123,14 @@ > MDNode::~MDNode() { > LLVMContextImpl *pImpl = getType()->getContext().pImpl; > pImpl->MDNodeSet.RemoveNode(this); > - delete [] Node; > - Node = NULL; > + delete [] Operands; > + Operands = NULL; > } > > /// getElement - Return specified element. > Value *MDNode::getElement(unsigned i) const { > assert(i < getNumElements() && "Invalid element number!"); > - return Node[i]; > + return Operands[i]; > } > > > @@ -161,8 +162,7 @@ > // Replace From element(s) in place. > for (SmallVector::iterator I = Indexes.begin(), E = Indexes.end(); > I != E; ++I) { > - unsigned Index = *I; > - Node[Index] = MDNodeElement(To, this); > + Operands[*I] = MDNodeElement(To, this); > } > > // Insert updated "this" into the context's folding node set. > > > _______________________________________________ > llvm-commits mailing list > llvm-commits at cs.uiuc.edu > http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits > From sabre at nondot.org Mon Dec 28 03:30:22 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 01:30:22 -0800 Subject: [llvm-commits] [llvm] r92216 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp In-Reply-To: <4B3879CB.6030105@mxc.ca> References: <200912280848.nBS8mCal008808@zion.cs.uiuc.edu> <4B3879CB.6030105@mxc.ca> Message-ID: <060AA104-DCDC-4C12-B4BC-9E0B524CD156@nondot.org> On Dec 28, 2009, at 1:26 AM, Nick Lewycky wrote: > Chris Lattner wrote: >> Author: lattner >> Date: Mon Dec 28 02:48:12 2009 >> New Revision: 92216 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=92216&view=rev >> Log: >> rename MDNode instance variables to something meaningful. >> > Please name them Elements instead of Operands. There's a lot of great invariants that apply to operands which don't exist on MDNode elements. I don't really care either way, anything is better than 'node'. We do have null operands though, e.g. global variable initializers, so I don't see how elements (which sounds like struct element to me) is better than operands here. We generally use 'element' for types, not values. -Chris From sabre at nondot.org Mon Dec 28 03:32:11 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 09:32:11 -0000 Subject: [llvm-commits] [llvm] r92221 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp Message-ID: <200912280932.nBS9WB6c018503@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 03:32:10 2009 New Revision: 92221 URL: http://llvm.org/viewvc/llvm-project?rev=92221&view=rev Log: avoid a completely unneeded linear walk. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92221&r1=92220&r2=92221&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 03:32:10 2009 @@ -102,7 +102,7 @@ }; // Replace each instance of F from the element list of this node with T. - void replaceElement(Value *F, Value *T); + void replaceElement(MDNodeElement *Op, Value *NewVal); protected: explicit MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92221&r1=92220&r2=92221&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 03:32:10 2009 @@ -76,11 +76,11 @@ void MDNodeElement::deleted() { - Parent->replaceElement(this->operator Value*(), 0); + Parent->replaceElement(this, 0); } void MDNodeElement::allUsesReplacedWith(Value *NV) { - Parent->replaceElement(this->operator Value*(), NV); + Parent->replaceElement(this, NV); } @@ -142,8 +142,10 @@ // Replace value from this node's element list. -void MDNode::replaceElement(Value *From, Value *To) { - if (From == To || !getType()) +void MDNode::replaceElement(MDNodeElement *Op, Value *To) { + Value *From = *Op; + + if (From == To) return; LLVMContextImpl *pImpl = getType()->getContext().pImpl; @@ -151,14 +153,9 @@ // Remove "this" from the context map. FoldingSet doesn't have to reprofile // this node to remove it, so we don't care what state the operands are in. pImpl->MDNodeSet.RemoveNode(this); - - // Find value. This is a linear search, do something if it consumes - // lot of time. It is possible that to have multiple instances of - // From in this MDNode's element list. - for (unsigned i = 0, e = getNumElements(); i != e; ++i) { - if (Operands[i] == From) - Operands[i].set(To, this); - } + + // Update the operand. + Op->set(To, this); // Insert updated "this" into the context's folding node set. // If a node with same element list already exist then before inserting From benny.kra at googlemail.com Mon Dec 28 06:27:56 2009 From: benny.kra at googlemail.com (Benjamin Kramer) Date: Mon, 28 Dec 2009 12:27:56 -0000 Subject: [llvm-commits] [llvm] r92222 - /llvm/trunk/lib/Target/ARM/AsmPrinter/ARMAsmPrinter.cpp Message-ID: <200912281227.nBSCRupx025231@zion.cs.uiuc.edu> Author: d0k Date: Mon Dec 28 06:27:56 2009 New Revision: 92222 URL: http://llvm.org/viewvc/llvm-project?rev=92222&view=rev Log: Add missing include (for inline PATypeHolder::get). Modified: llvm/trunk/lib/Target/ARM/AsmPrinter/ARMAsmPrinter.cpp Modified: llvm/trunk/lib/Target/ARM/AsmPrinter/ARMAsmPrinter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/ARM/AsmPrinter/ARMAsmPrinter.cpp?rev=92222&r1=92221&r2=92222&view=diff ============================================================================== --- llvm/trunk/lib/Target/ARM/AsmPrinter/ARMAsmPrinter.cpp (original) +++ llvm/trunk/lib/Target/ARM/AsmPrinter/ARMAsmPrinter.cpp Mon Dec 28 06:27:56 2009 @@ -23,6 +23,7 @@ #include "ARMTargetMachine.h" #include "llvm/Constants.h" #include "llvm/Module.h" +#include "llvm/Type.h" #include "llvm/Assembly/Writer.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/DwarfWriter.h" From sabre at nondot.org Mon Dec 28 13:49:01 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 19:49:01 -0000 Subject: [llvm-commits] [llvm] r92223 - /llvm/trunk/lib/VMCore/Metadata.cpp Message-ID: <200912281949.nBSJn1ec008481@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 13:49:00 2009 New Revision: 92223 URL: http://llvm.org/viewvc/llvm-project?rev=92223&view=rev Log: tidy up and delete a dead smallvector. Modified: llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92223&r1=92222&r2=92223&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 13:49:00 2009 @@ -23,10 +23,6 @@ using namespace llvm; //===----------------------------------------------------------------------===// -// MetadataBase implementation. -// - -//===----------------------------------------------------------------------===// // MDString implementation. // @@ -130,6 +126,8 @@ void MDNode::Profile(FoldingSetNodeID &ID) const { for (unsigned i = 0, e = getNumElements(); i != e; ++i) ID.AddPointer(getElement(i)); + // HASH TABLE COLLISIONS? + // DO NOT REINSERT AFTER AN OPERAND DROPS TO NULL! } @@ -433,10 +431,8 @@ MDStoreTy::iterator I = MetadataStore.find(In1); assert(I != MetadataStore.end() && "Invalid custom metadata info!"); - // FIXME : Give all metadata handlers a chance to adjust. - + // FIXME: Give all metadata handlers a chance to adjust. MDMapTy &In1Info = I->second; - MDMapTy In2Info; for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I) addMD(I->first, I->second, In2); } @@ -449,15 +445,14 @@ if (!I1 || !I2) return; - // FIXME : Give custom handlers a chance to override this. + // FIXME: Give custom handlers a chance to override this. ValueIsCloned(I1, I2); } //===----------------------------------------------------------------------===// // MetadataContext implementation. // -MetadataContext::MetadataContext() - : pImpl(new MetadataContextImpl()) { } +MetadataContext::MetadataContext() : pImpl(new MetadataContextImpl()) { } MetadataContext::~MetadataContext() { delete pImpl; } /// isValidName - Return true if Name is a valid custom metadata handler name. From sabre at nondot.org Mon Dec 28 14:10:43 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 20:10:43 -0000 Subject: [llvm-commits] [llvm] r92224 - in /llvm/trunk: include/llvm/Metadata.h lib/Bitcode/Writer/BitcodeWriter.cpp lib/VMCore/AsmWriter.cpp lib/VMCore/Metadata.cpp Message-ID: <200912282010.nBSKAh2x009180@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 14:10:43 2009 New Revision: 92224 URL: http://llvm.org/viewvc/llvm-project?rev=92224&view=rev Log: rename getHandlerNames to getMDKindNames, simplify its interface and simplify all the clients that use it. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp llvm/trunk/lib/VMCore/AsmWriter.cpp llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92224&r1=92223&r2=92224&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 14:10:43 2009 @@ -244,9 +244,9 @@ /// the same metadata to In2. void copyMD(Instruction *In1, Instruction *In2); - /// getHandlerNames - Populate client supplied smallvector using custom - /// metadata name and ID. - void getHandlerNames(SmallVectorImpl >&) const; + /// getMDKindNames - Populate client supplied SmallVector with the name for + /// each custom metadata ID. ID #0 is not used, so it is filled in as empty. + void getMDKindNames(SmallVectorImpl &) const; /// ValueIsDeleted - This handler is used to update metadata store /// when a value is deleted. Modified: llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp?rev=92224&r1=92223&r2=92224&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp Mon Dec 28 14:10:43 2009 @@ -593,35 +593,30 @@ Stream.ExitBlock(); } -static void WriteModuleMetadataStore(const Module *M, - const ValueEnumerator &VE, - BitstreamWriter &Stream) { - - bool StartedMetadataBlock = false; +static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) { SmallVector Record; // Write metadata kinds // METADATA_KIND - [n x [id, name]] MetadataContext &TheMetadata = M->getContext().getMetadata(); - SmallVector, 4> Names; - TheMetadata.getHandlerNames(Names); - for (SmallVector, 4>::iterator - I = Names.begin(), - E = Names.end(); I != E; ++I) { - Record.push_back(I->first); - StringRef KName = I->second; - for (unsigned i = 0, e = KName.size(); i != e; ++i) - Record.push_back(KName[i]); - if (!StartedMetadataBlock) { - Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); - StartedMetadataBlock = true; - } + SmallVector Names; + TheMetadata.getMDKindNames(Names); + + assert(Names[0] == "" && "MDKind #0 is invalid"); + if (Names.size() == 1) return; + + Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); + + for (unsigned MDKindID = 1, e = Names.size(); MDKindID != e; ++MDKindID) { + Record.push_back(MDKindID); + StringRef KName = Names[MDKindID]; + Record.append(KName.begin(), KName.end()); + Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); Record.clear(); } - if (StartedMetadataBlock) - Stream.ExitBlock(); + Stream.ExitBlock(); } static void WriteConstants(unsigned FirstVal, unsigned LastVal, @@ -1466,7 +1461,7 @@ WriteFunction(*I, VE, Stream); // Emit metadata. - WriteModuleMetadataStore(M, VE, Stream); + WriteModuleMetadataStore(M, Stream); // Emit the type symbol table information. WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream); Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92224&r1=92223&r2=92224&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Mon Dec 28 14:10:43 2009 @@ -1330,8 +1330,8 @@ TypePrinting TypePrinter; AssemblyAnnotationWriter *AnnotationWriter; std::vector NumberedTypes; - DenseMap MDNames; - + SmallVector MDNames; + public: inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M, @@ -1339,16 +1339,8 @@ : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) { AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M); // FIXME: Provide MDPrinter - if (M) { - MetadataContext &TheMetadata = M->getContext().getMetadata(); - SmallVector, 4> Names; - TheMetadata.getHandlerNames(Names); - for (SmallVector, 4>::iterator - I = Names.begin(), - E = Names.end(); I != E; ++I) { - MDNames[I->first] = I->second; - } - } + if (M) + M->getContext().getMetadata().getMDKindNames(MDNames); } void write(const Module *M) { printModule(M); } @@ -2075,14 +2067,14 @@ } } - // Print post operand alignment for load/store + // Print post operand alignment for load/store. if (isa(I) && cast(I).getAlignment()) { Out << ", align " << cast(I).getAlignment(); } else if (isa(I) && cast(I).getAlignment()) { Out << ", align " << cast(I).getAlignment(); } - // Print Metadata info + // Print Metadata info. if (!MDNames.empty()) { MetadataContext &TheMetadata = I.getContext().getMetadata(); typedef SmallVector, 2> MDMapTy; Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92224&r1=92223&r2=92224&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 14:10:43 2009 @@ -290,9 +290,9 @@ /// the same metadata to In2. void copyMD(Instruction *In1, Instruction *In2); - /// getHandlerNames - Populate client-supplied smallvector using custom + /// getMDKindNames - Populate client-supplied smallvector using custom /// metadata name and ID. - void getHandlerNames(SmallVectorImpl >&) const; + void getMDKindNames(SmallVectorImpl &) const; /// ValueIsDeleted - This handler is used to update metadata store /// when a value is deleted. @@ -415,12 +415,13 @@ /// getHandlerNames - Populate client supplied smallvector using custome /// metadata name and ID. void MetadataContextImpl:: -getHandlerNames(SmallVectorImpl >&Names) const { - Names.resize(MDHandlerNames.size()); +getMDKindNames(SmallVectorImpl &Names) const { + Names.resize(MDHandlerNames.size()+1); + Names[0] = ""; for (StringMap::const_iterator I = MDHandlerNames.begin(), E = MDHandlerNames.end(); I != E; ++I) // MD Handlers are numbered from 1. - Names[I->second - 1] = std::make_pair(I->second, I->first()); + Names[I->second] = I->first(); } /// ValueIsCloned - This handler is used to update metadata store @@ -520,9 +521,8 @@ /// getHandlerNames - Populate client supplied smallvector using custome /// metadata name and ID. -void MetadataContext:: -getHandlerNames(SmallVectorImpl >&N) const { - pImpl->getHandlerNames(N); +void MetadataContext::getMDKindNames(SmallVectorImpl &N) const { + pImpl->getMDKindNames(N); } /// ValueIsDeleted - This handler is used to update metadata store From sabre at nondot.org Mon Dec 28 14:45:52 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 20:45:52 -0000 Subject: [llvm-commits] [llvm] r92225 - in /llvm/trunk: include/llvm/Metadata.h include/llvm/Support/IRBuilder.h lib/Analysis/DebugInfo.cpp lib/AsmParser/LLParser.cpp lib/Bitcode/Reader/BitcodeReader.cpp lib/CodeGen/SelectionDAG/FastISel.cpp lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp lib/Transforms/IPO/StripSymbols.cpp lib/Transforms/Utils/CloneFunction.cpp lib/VMCore/Metadata.cpp Message-ID: <200912282045.nBSKjq3h010385@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 14:45:51 2009 New Revision: 92225 URL: http://llvm.org/viewvc/llvm-project?rev=92225&view=rev Log: rename getMDKind -> getMDKindID, make it autoinsert if an MD Kind doesn't exist already, eliminate registerMDKind. Tidy up a bunch of random stuff. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/include/llvm/Support/IRBuilder.h llvm/trunk/lib/Analysis/DebugInfo.cpp llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 14:45:51 2009 @@ -197,32 +197,25 @@ }; //===----------------------------------------------------------------------===// -/// MetadataContext - -/// MetadataContext handles uniquing and assignment of IDs for custom metadata -/// types. Custom metadata handler names do not contain spaces. And the name -/// must start with an alphabet. The regular expression used to check name -/// is [a-zA-Z$._][a-zA-Z$._0-9]* +/// MetadataContext - MetadataContext handles uniquing and assignment of IDs for +/// custom metadata types. +/// class MetadataContext { - // DO NOT IMPLEMENT - MetadataContext(MetadataContext&); - void operator=(MetadataContext&); + MetadataContext(MetadataContext&); // DO NOT IMPLEMENT + void operator=(MetadataContext&); // DO NOT IMPLEMENT MetadataContextImpl *const pImpl; public: MetadataContext(); ~MetadataContext(); - /// registerMDKind - Register a new metadata kind and return its ID. - /// A metadata kind can be registered only once. - unsigned registerMDKind(StringRef Name); - - /// getMDKind - Return metadata kind. If the requested metadata kind - /// is not registered then return 0. - unsigned getMDKind(StringRef Name) const; + /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. + unsigned getMDKindID(StringRef Name) const; /// isValidName - Return true if Name is a valid custom metadata handler name. static bool isValidName(StringRef Name); +#if 1 /// getMD - Get the metadata of given kind attached to an Instruction. /// If the metadata is not found then return 0. MDNode *getMD(unsigned Kind, const Instruction *Inst); @@ -239,6 +232,7 @@ /// removeAllMetadata - Remove all metadata attached with an instruction. void removeAllMetadata(Instruction *Inst); +#endif /// copyMD - If metadata is attached with Instruction In1 then attach /// the same metadata to In2. Modified: llvm/trunk/include/llvm/Support/IRBuilder.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/IRBuilder.h?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/include/llvm/Support/IRBuilder.h (original) +++ llvm/trunk/include/llvm/Support/IRBuilder.h Mon Dec 28 14:45:51 2009 @@ -137,9 +137,7 @@ /// information. void SetCurrentDebugLocation(MDNode *L) { if (MDKind == 0) - MDKind = Context.getMetadata().getMDKind("dbg"); - if (MDKind == 0) - MDKind = Context.getMetadata().registerMDKind("dbg"); + MDKind = Context.getMetadata().getMDKindID("dbg"); CurDbgLocation = L; } @@ -154,9 +152,7 @@ /// SetDebugLocation - Set location information for the given instruction. void SetDebugLocation(Instruction *I, MDNode *Loc) { if (MDKind == 0) - MDKind = Context.getMetadata().getMDKind("dbg"); - if (MDKind == 0) - MDKind = Context.getMetadata().registerMDKind("dbg"); + MDKind = Context.getMetadata().getMDKindID("dbg"); Context.getMetadata().addMD(MDKind, Loc, I); } Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Mon Dec 28 14:45:51 2009 @@ -1119,7 +1119,7 @@ void DebugInfoFinder::processModule(Module &M) { MetadataContext &TheMetadata = M.getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKind("dbg"); + unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI) @@ -1127,9 +1127,8 @@ ++BI) { if (DbgDeclareInst *DDI = dyn_cast(BI)) processDeclare(DDI); - else if (MDDbgKind) - if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI)) - processLocation(DILocation(L)); + else if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI)) + processLocation(DILocation(L)); } NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv"); Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Mon Dec 28 14:45:51 2009 @@ -1123,11 +1123,8 @@ if (ParseMDNode(Node)) return true; MetadataContext &TheMetadata = M->getContext().getMetadata(); - unsigned MDK = TheMetadata.getMDKind(Name.c_str()); - if (!MDK) - MDK = TheMetadata.registerMDKind(Name.c_str()); + unsigned MDK = TheMetadata.getMDKindID(Name.c_str()); MDsOnInst.push_back(std::make_pair(MDK, cast(Node))); - return false; } Modified: llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp (original) +++ llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp Mon Dec 28 14:45:51 2009 @@ -840,17 +840,10 @@ (void) Kind; for (unsigned i = 1; i != RecordLength; ++i) Name[i-1] = Record[i]; - MetadataContext &TheMetadata = Context.getMetadata(); - unsigned ExistingKind = TheMetadata.getMDKind(Name.str()); - if (ExistingKind == 0) { - unsigned NewKind = TheMetadata.registerMDKind(Name.str()); - (void) NewKind; - assert (Kind == NewKind - && "Unable to handle custom metadata mismatch!"); - } else { - assert (ExistingKind == Kind - && "Unable to handle custom metadata mismatch!"); - } + + unsigned NewKind = Context.getMetadata().getMDKindID(Name.str()); + assert(Kind == NewKind && + "FIXME: Unable to handle custom metadata mismatch!");(void)NewKind; break; } } Modified: llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp Mon Dec 28 14:45:51 2009 @@ -351,9 +351,9 @@ if (MMI) { MetadataContext &TheMetadata = DI->getParent()->getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKind("dbg"); - MDNode *Dbg = TheMetadata.getMD(MDDbgKind, DI); - MMI->setVariableDbgInfo(DI->getVariable(), FI, Dbg); + unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); + if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, DI)) + MMI->setVariableDbgInfo(DI->getVariable(), FI, Dbg); } return true; } Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Mon Dec 28 14:45:51 2009 @@ -4383,9 +4383,9 @@ if (MMI) { MetadataContext &TheMetadata = DI.getParent()->getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKind("dbg"); - MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI); - MMI->setVariableDbgInfo(Variable, FI, Dbg); + unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); + if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI)) + MMI->setVariableDbgInfo(Variable, FI, Dbg); } return 0; } Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp Mon Dec 28 14:45:51 2009 @@ -362,27 +362,25 @@ /// SetDebugLoc - Update MF's and SDB's DebugLocs if debug information is /// attached with this instruction. -static void SetDebugLoc(unsigned MDDbgKind, - MetadataContext &TheMetadata, - Instruction *I, - SelectionDAGBuilder *SDB, - FastISel *FastIS, - MachineFunction *MF) { - if (!isa(I)) - if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, I)) { - DILocation DILoc(Dbg); - DebugLoc Loc = ExtractDebugLocation(DILoc, MF->getDebugLocInfo()); - - SDB->setCurDebugLoc(Loc); - - if (FastIS) - FastIS->setCurDebugLoc(Loc); - - // If the function doesn't have a default debug location yet, set - // it. This is kind of a hack. - if (MF->getDefaultDebugLoc().isUnknown()) - MF->setDefaultDebugLoc(Loc); - } +static void SetDebugLoc(unsigned MDDbgKind, MetadataContext &TheMetadata, + Instruction *I, SelectionDAGBuilder *SDB, + FastISel *FastIS, MachineFunction *MF) { + if (isa(I)) return; + + if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, I)) { + DILocation DILoc(Dbg); + DebugLoc Loc = ExtractDebugLocation(DILoc, MF->getDebugLocInfo()); + + SDB->setCurDebugLoc(Loc); + + if (FastIS) + FastIS->setCurDebugLoc(Loc); + + // If the function doesn't have a default debug location yet, set + // it. This is kind of a hack. + if (MF->getDefaultDebugLoc().isUnknown()) + MF->setDefaultDebugLoc(Loc); + } } /// ResetDebugLoc - Set MF's and SDB's DebugLocs to Unknown. @@ -398,14 +396,13 @@ BasicBlock::iterator End, bool &HadTailCall) { SDB->setCurrentBasicBlock(BB); - MetadataContext &TheMetadata = LLVMBB->getParent()->getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKind("dbg"); + MetadataContext &TheMetadata =LLVMBB->getParent()->getContext().getMetadata(); + unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); // Lower all of the non-terminator instructions. If a call is emitted // as a tail call, cease emitting nodes for this block. for (BasicBlock::iterator I = Begin; I != End && !SDB->HasTailCall; ++I) { - if (MDDbgKind) - SetDebugLoc(MDDbgKind, TheMetadata, I, SDB, 0, MF); + SetDebugLoc(MDDbgKind, TheMetadata, I, SDB, 0, MF); if (!isa(I)) { SDB->visit(*I); @@ -681,7 +678,7 @@ ); MetadataContext &TheMetadata = Fn.getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKind("dbg"); + unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); // Iterate over all basic blocks in the function. for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { @@ -779,8 +776,7 @@ break; } - if (MDDbgKind) - SetDebugLoc(MDDbgKind, TheMetadata, BI, SDB, FastIS, &MF); + SetDebugLoc(MDDbgKind, TheMetadata, BI, SDB, FastIS, &MF); // First try normal tablegen-generated "fast" selection. if (FastIS->SelectInstruction(BI)) { Modified: llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp (original) +++ llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp Mon Dec 28 14:45:51 2009 @@ -221,9 +221,7 @@ NMD->eraseFromParent(); } MetadataContext &TheMetadata = M.getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKind("dbg"); - if (!MDDbgKind) - return Changed; + unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI) for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; Modified: llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp (original) +++ llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Mon Dec 28 14:45:51 2009 @@ -422,7 +422,7 @@ BasicBlock::iterator I = NewBB->begin(); LLVMContext &Context = OldFunc->getContext(); - unsigned DbgKind = Context.getMetadata().getMDKind("dbg"); + unsigned DbgKind = Context.getMetadata().getMDKindID("dbg"); MDNode *TheCallMD = NULL; SmallVector MDVs; if (TheCall && TheCall->hasMetadata()) Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92225&r1=92224&r2=92225&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 14:45:51 2009 @@ -261,13 +261,7 @@ StringMap MDHandlerNames; public: - /// registerMDKind - Register a new metadata kind and return its ID. - /// A metadata kind can be registered only once. - unsigned registerMDKind(StringRef Name); - - /// getMDKind - Return metadata kind. If the requested metadata kind - /// is not registered then return 0. - unsigned getMDKind(StringRef Name) const; + unsigned getMDKindID(StringRef Name); /// getMD - Get the metadata of given kind attached to an Instruction. /// If the metadata is not found then return 0. @@ -308,22 +302,14 @@ }; } -/// registerMDKind - Register a new metadata kind and return its ID. -/// A metadata kind can be registered only once. -unsigned MetadataContextImpl::registerMDKind(StringRef Name) { - unsigned Count = MDHandlerNames.size(); - assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!"); - return MDHandlerNames[Name] = Count + 1; -} - -/// getMDKind - Return metadata kind. If the requested metadata kind -/// is not registered then return 0. -unsigned MetadataContextImpl::getMDKind(StringRef Name) const { - StringMap::const_iterator I = MDHandlerNames.find(Name); - if (I == MDHandlerNames.end()) - return 0; +/// getMDKindID - Return a unique non-zero ID for the specified metadata kind. +unsigned MetadataContextImpl::getMDKindID(StringRef Name) { + unsigned &Entry = MDHandlerNames[Name]; - return I->getValue(); + // If this is new, assign it its ID. + if (Entry == 0) Entry = MDHandlerNames.size(); + + return Entry; } /// addMD - Attach the metadata of given kind to an Instruction. @@ -472,17 +458,9 @@ return true; } -/// registerMDKind - Register a new metadata kind and return its ID. -/// A metadata kind can be registered only once. -unsigned MetadataContext::registerMDKind(StringRef Name) { - assert(isValidName(Name) && "Invalid custome metadata name!"); - return pImpl->registerMDKind(Name); -} - -/// getMDKind - Return metadata kind. If the requested metadata kind -/// is not registered then return 0. -unsigned MetadataContext::getMDKind(StringRef Name) const { - return pImpl->getMDKind(Name); +/// getMDKindID - Return a unique non-zero ID for the specified metadata kind. +unsigned MetadataContext::getMDKindID(StringRef Name) const { + return pImpl->getMDKindID(Name); } /// getMD - Get the metadata of given kind attached to an Instruction. From sabre at nondot.org Mon Dec 28 15:12:29 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 21:12:29 -0000 Subject: [llvm-commits] [llvm] r92226 - /llvm/trunk/include/llvm/Support/IRBuilder.h Message-ID: <200912282112.nBSLCTJj011209@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 15:12:29 2009 New Revision: 92226 URL: http://llvm.org/viewvc/llvm-project?rev=92226&view=rev Log: rename ivar to be more descriptive. Modified: llvm/trunk/include/llvm/Support/IRBuilder.h Modified: llvm/trunk/include/llvm/Support/IRBuilder.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/IRBuilder.h?rev=92226&r1=92225&r2=92226&view=diff ============================================================================== --- llvm/trunk/include/llvm/Support/IRBuilder.h (original) +++ llvm/trunk/include/llvm/Support/IRBuilder.h Mon Dec 28 15:12:29 2009 @@ -61,39 +61,39 @@ class IRBuilder : public Inserter { BasicBlock *BB; BasicBlock::iterator InsertPt; - unsigned MDKind; + unsigned DbgMDKind; MDNode *CurDbgLocation; LLVMContext &Context; T Folder; public: IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter()) - : Inserter(I), MDKind(0), CurDbgLocation(0), Context(C), Folder(F) { + : Inserter(I), DbgMDKind(0), CurDbgLocation(0), Context(C), Folder(F) { ClearInsertionPoint(); } explicit IRBuilder(LLVMContext &C) - : MDKind(0), CurDbgLocation(0), Context(C), Folder(C) { + : DbgMDKind(0), CurDbgLocation(0), Context(C), Folder(C) { ClearInsertionPoint(); } explicit IRBuilder(BasicBlock *TheBB, const T &F) - : MDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(F) { + : DbgMDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(F) { SetInsertPoint(TheBB); } explicit IRBuilder(BasicBlock *TheBB) - : MDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), + : DbgMDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(Context) { SetInsertPoint(TheBB); } IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F) - : MDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(F) { + : DbgMDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(F) { SetInsertPoint(TheBB, IP); } IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP) - : MDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), + : DbgMDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(Context) { SetInsertPoint(TheBB, IP); } @@ -136,8 +136,8 @@ /// SetCurrentDebugLocation - Set location information used by debugging /// information. void SetCurrentDebugLocation(MDNode *L) { - if (MDKind == 0) - MDKind = Context.getMetadata().getMDKindID("dbg"); + if (DbgMDKind == 0) + DbgMDKind = Context.getMetadata().getMDKindID("dbg"); CurDbgLocation = L; } @@ -146,14 +146,14 @@ /// SetDebugLocation - Set location information for the given instruction. void SetDebugLocation(Instruction *I) { if (CurDbgLocation) - Context.getMetadata().addMD(MDKind, CurDbgLocation, I); + Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); } /// SetDebugLocation - Set location information for the given instruction. void SetDebugLocation(Instruction *I, MDNode *Loc) { - if (MDKind == 0) - MDKind = Context.getMetadata().getMDKindID("dbg"); - Context.getMetadata().addMD(MDKind, Loc, I); + if (DbgMDKind == 0) + DbgMDKind = Context.getMetadata().getMDKindID("dbg"); + Context.getMetadata().addMD(DbgMDKind, Loc, I); } /// Insert - Insert and return the specified instruction. @@ -161,7 +161,7 @@ InstTy *Insert(InstTy *I, const Twine &Name = "") const { this->InsertHelper(I, Name, BB, InsertPt); if (CurDbgLocation) - Context.getMetadata().addMD(MDKind, CurDbgLocation, I); + Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); return I; } From sabre at nondot.org Mon Dec 28 15:28:46 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 21:28:46 -0000 Subject: [llvm-commits] [llvm] r92227 - in /llvm/trunk: include/llvm/Support/IRBuilder.h lib/Transforms/Scalar/GVN.cpp lib/VMCore/IRBuilder.cpp Message-ID: <200912282128.nBSLSknf011731@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 15:28:46 2009 New Revision: 92227 URL: http://llvm.org/viewvc/llvm-project?rev=92227&view=rev Log: split code that doesn't need to be templated out of IRBuilder into a new non-templated IRBuilderBase class. Move that large CreateGlobalString out of line, eliminating the need to #include GlobalVariable.h in IRBuilder.h Added: llvm/trunk/lib/VMCore/IRBuilder.cpp Modified: llvm/trunk/include/llvm/Support/IRBuilder.h llvm/trunk/lib/Transforms/Scalar/GVN.cpp Modified: llvm/trunk/include/llvm/Support/IRBuilder.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/IRBuilder.h?rev=92227&r1=92226&r2=92227&view=diff ============================================================================== --- llvm/trunk/include/llvm/Support/IRBuilder.h (original) +++ llvm/trunk/include/llvm/Support/IRBuilder.h Mon Dec 28 15:28:46 2009 @@ -17,8 +17,6 @@ #include "llvm/Constants.h" #include "llvm/Instructions.h" -#include "llvm/GlobalAlias.h" -#include "llvm/GlobalVariable.h" #include "llvm/Function.h" #include "llvm/Metadata.h" #include "llvm/LLVMContext.h" @@ -41,98 +39,49 @@ I->setName(Name); } }; - - -/// IRBuilder - This provides a uniform API for creating instructions and -/// inserting them into a basic block: either at the end of a BasicBlock, or -/// at a specific iterator location in a block. -/// -/// Note that the builder does not expose the full generality of LLVM -/// instructions. For access to extra instruction properties, use the mutators -/// (e.g. setVolatile) on the instructions after they have been created. -/// The first template argument handles whether or not to preserve names in the -/// final instruction output. This defaults to on. The second template argument -/// specifies a class to use for creating constants. This defaults to creating -/// minimally folded constants. The fourth template argument allows clients to -/// specify custom insertion hooks that are called on every newly created -/// insertion. -template > -class IRBuilder : public Inserter { + +/// IRBuilderBase - Common base class shared among various IRBuilders. +class IRBuilderBase { +protected: BasicBlock *BB; BasicBlock::iterator InsertPt; unsigned DbgMDKind; MDNode *CurDbgLocation; LLVMContext &Context; - T Folder; public: - IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter()) - : Inserter(I), DbgMDKind(0), CurDbgLocation(0), Context(C), Folder(F) { - ClearInsertionPoint(); - } - explicit IRBuilder(LLVMContext &C) - : DbgMDKind(0), CurDbgLocation(0), Context(C), Folder(C) { + IRBuilderBase(LLVMContext &context) + : DbgMDKind(0), CurDbgLocation(0), Context(context) { ClearInsertionPoint(); } - explicit IRBuilder(BasicBlock *TheBB, const T &F) - : DbgMDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(F) { - SetInsertPoint(TheBB); - } - - explicit IRBuilder(BasicBlock *TheBB) - : DbgMDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), - Folder(Context) { - SetInsertPoint(TheBB); - } - - IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F) - : DbgMDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(F) { - SetInsertPoint(TheBB, IP); - } - - IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP) - : DbgMDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), - Folder(Context) { - SetInsertPoint(TheBB, IP); - } - - /// getFolder - Get the constant folder being used. - const T &getFolder() { return Folder; } - - /// isNamePreserving - Return true if this builder is configured to actually - /// add the requested names to IR created through it. - bool isNamePreserving() const { return preserveNames; } - //===--------------------------------------------------------------------===// // Builder configuration methods //===--------------------------------------------------------------------===// - + /// ClearInsertionPoint - Clear the insertion point: created instructions will /// not be inserted into a block. void ClearInsertionPoint() { BB = 0; } - + BasicBlock *GetInsertBlock() const { return BB; } - BasicBlock::iterator GetInsertPoint() const { return InsertPt; } - + /// SetInsertPoint - This specifies that created instructions should be /// appended to the end of the specified block. void SetInsertPoint(BasicBlock *TheBB) { BB = TheBB; InsertPt = BB->end(); } - + /// SetInsertPoint - This specifies that created instructions should be /// inserted at the specified point. void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) { BB = TheBB; InsertPt = IP; } - + /// SetCurrentDebugLocation - Set location information used by debugging /// information. void SetCurrentDebugLocation(MDNode *L) { @@ -140,35 +89,36 @@ DbgMDKind = Context.getMetadata().getMDKindID("dbg"); CurDbgLocation = L; } - + MDNode *getCurrentDebugLocation() const { return CurDbgLocation; } - + /// SetDebugLocation - Set location information for the given instruction. void SetDebugLocation(Instruction *I) { if (CurDbgLocation) Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); } - + /// SetDebugLocation - Set location information for the given instruction. void SetDebugLocation(Instruction *I, MDNode *Loc) { if (DbgMDKind == 0) DbgMDKind = Context.getMetadata().getMDKindID("dbg"); Context.getMetadata().addMD(DbgMDKind, Loc, I); } - - /// Insert - Insert and return the specified instruction. - template - InstTy *Insert(InstTy *I, const Twine &Name = "") const { - this->InsertHelper(I, Name, BB, InsertPt); - if (CurDbgLocation) - Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); - return I; - } - + + //===--------------------------------------------------------------------===// + // Miscellaneous creation methods. + //===--------------------------------------------------------------------===// + + /// CreateGlobalString - Make a new global variable with an initializer that + /// has array of i8 type filled in the the nul terminated string value + /// specified. If Name is specified, it is the name of the global variable + /// created. + Value *CreateGlobalString(const char *Str = "", const Twine &Name = ""); + //===--------------------------------------------------------------------===// // Type creation methods //===--------------------------------------------------------------------===// - + /// getInt1Ty - Fetch the type representing a single bit const Type *getInt1Ty() { return Type::getInt1Ty(Context); @@ -193,7 +143,7 @@ const Type *getInt64Ty() { return Type::getInt64Ty(Context); } - + /// getFloatTy - Fetch the type representing a 32-bit floating point value. const Type *getFloatTy() { return Type::getFloatTy(Context); @@ -208,6 +158,68 @@ const Type *getVoidTy() { return Type::getVoidTy(Context); } +}; + +/// IRBuilder - This provides a uniform API for creating instructions and +/// inserting them into a basic block: either at the end of a BasicBlock, or +/// at a specific iterator location in a block. +/// +/// Note that the builder does not expose the full generality of LLVM +/// instructions. For access to extra instruction properties, use the mutators +/// (e.g. setVolatile) on the instructions after they have been created. +/// The first template argument handles whether or not to preserve names in the +/// final instruction output. This defaults to on. The second template argument +/// specifies a class to use for creating constants. This defaults to creating +/// minimally folded constants. The fourth template argument allows clients to +/// specify custom insertion hooks that are called on every newly created +/// insertion. +template > +class IRBuilder : public IRBuilderBase, public Inserter { + T Folder; +public: + IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter()) + : IRBuilderBase(C), Inserter(I), Folder(F) { + } + + explicit IRBuilder(LLVMContext &C) : IRBuilderBase(C), Folder(C) { + } + + explicit IRBuilder(BasicBlock *TheBB, const T &F) + : IRBuilderBase(TheBB->getContext()), Folder(F) { + SetInsertPoint(TheBB); + } + + explicit IRBuilder(BasicBlock *TheBB) + : IRBuilderBase(TheBB->getContext()), Folder(Context) { + SetInsertPoint(TheBB); + } + + IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F) + : IRBuilderBase(TheBB->getContext()), Folder(F) { + SetInsertPoint(TheBB, IP); + } + + IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP) + : IRBuilderBase(TheBB->getContext()), Folder(Context) { + SetInsertPoint(TheBB, IP); + } + + /// getFolder - Get the constant folder being used. + const T &getFolder() { return Folder; } + + /// isNamePreserving - Return true if this builder is configured to actually + /// add the requested names to IR created through it. + bool isNamePreserving() const { return preserveNames; } + + /// Insert - Insert and return the specified instruction. + template + InstTy *Insert(InstTy *I, const Twine &Name = "") const { + this->InsertHelper(I, Name, BB, InsertPt); + if (CurDbgLocation) + Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); + return I; + } //===--------------------------------------------------------------------===// // Instruction creation methods: Terminators @@ -646,26 +658,16 @@ Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") { return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name); } - Value *CreateGlobalString(const char *Str = "", const Twine &Name = "") { - Constant *StrConstant = ConstantArray::get(Context, Str, true); - Module &M = *BB->getParent()->getParent(); - GlobalVariable *gv = new GlobalVariable(M, - StrConstant->getType(), - true, - GlobalValue::InternalLinkage, - StrConstant, - "", - 0, - false); - gv->setName(Name); - return gv; - } + + /// CreateGlobalStringPtr - Same as CreateGlobalString, but return a pointer + /// with "i8*" type instead of a pointer to array of i8. Value *CreateGlobalStringPtr(const char *Str = "", const Twine &Name = "") { Value *gv = CreateGlobalString(Str, Name); Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0); Value *Args[] = { zero, zero }; return CreateInBoundsGEP(gv, Args, Args+2, Name); } + //===--------------------------------------------------------------------===// // Instruction creation methods: Cast/Conversion Operators //===--------------------------------------------------------------------===// Modified: llvm/trunk/lib/Transforms/Scalar/GVN.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/GVN.cpp?rev=92227&r1=92226&r2=92227&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/GVN.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/GVN.cpp Mon Dec 28 15:28:46 2009 @@ -20,6 +20,7 @@ #include "llvm/BasicBlock.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" +#include "llvm/GlobalVariable.h" #include "llvm/Function.h" #include "llvm/IntrinsicInst.h" #include "llvm/LLVMContext.h" Added: llvm/trunk/lib/VMCore/IRBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/IRBuilder.cpp?rev=92227&view=auto ============================================================================== --- llvm/trunk/lib/VMCore/IRBuilder.cpp (added) +++ llvm/trunk/lib/VMCore/IRBuilder.cpp Mon Dec 28 15:28:46 2009 @@ -0,0 +1,31 @@ +//===---- IRBuilder.cpp - Builder for LLVM Instrs -------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file implements the IRBuilder class, which is used as a convenient way +// to create LLVM instructions with a consistent and simplified interface. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Support/IRBuilder.h" +#include "llvm/GlobalVariable.h" +using namespace llvm; + +/// CreateGlobalString - Make a new global variable with an initializer that +/// has array of i8 type filled in the the nul terminated string value +/// specified. If Name is specified, it is the name of the global variable +/// created. +Value *IRBuilderBase::CreateGlobalString(const char *Str, const Twine &Name) { + Constant *StrConstant = ConstantArray::get(Context, Str, true); + Module &M = *BB->getParent()->getParent(); + GlobalVariable *GV = new GlobalVariable(M, StrConstant->getType(), + true, GlobalValue::InternalLinkage, + StrConstant, "", 0, false); + GV->setName(Name); + return GV; +} From sabre at nondot.org Mon Dec 28 15:44:56 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 21:44:56 -0000 Subject: [llvm-commits] [llvm-gcc-4.2] r92229 - in /llvm-gcc-4.2/trunk/gcc: llvm-abi.h llvm-debug.cpp Message-ID: <200912282144.nBSLiurZ012234@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 15:44:56 2009 New Revision: 92229 URL: http://llvm.org/viewvc/llvm-project?rev=92229&view=rev Log: this form of SetDebugLocation is about to go away, add some #includes that are about to not come in implicitly. Modified: llvm-gcc-4.2/trunk/gcc/llvm-abi.h llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp Modified: llvm-gcc-4.2/trunk/gcc/llvm-abi.h URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/gcc/llvm-abi.h?rev=92229&r1=92228&r2=92229&view=diff ============================================================================== --- llvm-gcc-4.2/trunk/gcc/llvm-abi.h (original) +++ llvm-gcc-4.2/trunk/gcc/llvm-abi.h Mon Dec 28 15:44:56 2009 @@ -35,6 +35,7 @@ #include "llvm/CallingConv.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" +#include "llvm/LLVMContext.h" #include "llvm/Target/TargetData.h" namespace llvm { Modified: llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp?rev=92229&r1=92228&r2=92229&view=diff ============================================================================== --- llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp (original) +++ llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp Mon Dec 28 15:44:56 2009 @@ -351,8 +351,7 @@ /// EmitDeclare - Constructs the debug code for allocation of a new variable. /// region - "llvm.dbg.declare." void DebugInfo::EmitDeclare(tree decl, unsigned Tag, const char *Name, - tree type, Value *AI, - LLVMBuilder &Builder) { + tree type, Value *AI, LLVMBuilder &Builder) { // Do not emit variable declaration info, for now. if (optimize) @@ -382,7 +381,10 @@ llvm::DILocation DO(NULL); llvm::DILocation DL = DebugFactory.CreateLocation(CurLineNo, 0 /* column */, VarScope, DO); - Builder.SetDebugLocation(Call, DL.getNode()); + + llvm::LLVMContext &Context = Call->getContext(); + unsigned DbgMDKind = Context.getMetadata().getMDKindID("dbg"); + Context.getMetadata().addMD(DbgMDKind, DL.getNode(), Call); } From sabre at nondot.org Mon Dec 28 15:45:40 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 21:45:40 -0000 Subject: [llvm-commits] [llvm] r92230 - in /llvm/trunk: include/llvm/Support/IRBuilder.h lib/Target/Target.cpp lib/VMCore/IRBuilder.cpp Message-ID: <200912282145.nBSLjejV012277@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 15:45:40 2009 New Revision: 92230 URL: http://llvm.org/viewvc/llvm-project?rev=92230&view=rev Log: move debug info stuff out of line, allowing two #includes to go away from IRBuilder.h Modified: llvm/trunk/include/llvm/Support/IRBuilder.h llvm/trunk/lib/Target/Target.cpp llvm/trunk/lib/VMCore/IRBuilder.cpp Modified: llvm/trunk/include/llvm/Support/IRBuilder.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/IRBuilder.h?rev=92230&r1=92229&r2=92230&view=diff ============================================================================== --- llvm/trunk/include/llvm/Support/IRBuilder.h (original) +++ llvm/trunk/include/llvm/Support/IRBuilder.h Mon Dec 28 15:45:40 2009 @@ -18,12 +18,11 @@ #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Function.h" -#include "llvm/Metadata.h" -#include "llvm/LLVMContext.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/ConstantFolder.h" namespace llvm { + class MDNode; /// IRBuilderDefaultInserter - This provides the default implementation of the /// IRBuilder 'InsertHelper' method that is called whenever an instruction is @@ -42,11 +41,11 @@ /// IRBuilderBase - Common base class shared among various IRBuilders. class IRBuilderBase { + unsigned DbgMDKind; + MDNode *CurDbgLocation; protected: BasicBlock *BB; BasicBlock::iterator InsertPt; - unsigned DbgMDKind; - MDNode *CurDbgLocation; LLVMContext &Context; public: @@ -84,27 +83,13 @@ /// SetCurrentDebugLocation - Set location information used by debugging /// information. - void SetCurrentDebugLocation(MDNode *L) { - if (DbgMDKind == 0) - DbgMDKind = Context.getMetadata().getMDKindID("dbg"); - CurDbgLocation = L; - } - + void SetCurrentDebugLocation(MDNode *L); MDNode *getCurrentDebugLocation() const { return CurDbgLocation; } - /// SetDebugLocation - Set location information for the given instruction. - void SetDebugLocation(Instruction *I) { - if (CurDbgLocation) - Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); - } - - /// SetDebugLocation - Set location information for the given instruction. - void SetDebugLocation(Instruction *I, MDNode *Loc) { - if (DbgMDKind == 0) - DbgMDKind = Context.getMetadata().getMDKindID("dbg"); - Context.getMetadata().addMD(DbgMDKind, Loc, I); - } - + /// SetInstDebugLocation - If this builder has a current debug location, set + /// it on the specified instruction. + void SetInstDebugLocation(Instruction *I) const; + //===--------------------------------------------------------------------===// // Miscellaneous creation methods. //===--------------------------------------------------------------------===// @@ -216,8 +201,8 @@ template InstTy *Insert(InstTy *I, const Twine &Name = "") const { this->InsertHelper(I, Name, BB, InsertPt); - if (CurDbgLocation) - Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); + if (getCurrentDebugLocation() != 0) + this->SetInstDebugLocation(I); return I; } Modified: llvm/trunk/lib/Target/Target.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/Target.cpp?rev=92230&r1=92229&r2=92230&view=diff ============================================================================== --- llvm/trunk/lib/Target/Target.cpp (original) +++ llvm/trunk/lib/Target/Target.cpp Mon Dec 28 15:45:40 2009 @@ -15,6 +15,7 @@ #include "llvm-c/Target.h" #include "llvm/PassManager.h" #include "llvm/Target/TargetData.h" +#include "llvm/LLVMContext.h" #include using namespace llvm; Modified: llvm/trunk/lib/VMCore/IRBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/IRBuilder.cpp?rev=92230&r1=92229&r2=92230&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/IRBuilder.cpp (original) +++ llvm/trunk/lib/VMCore/IRBuilder.cpp Mon Dec 28 15:45:40 2009 @@ -14,6 +14,8 @@ #include "llvm/Support/IRBuilder.h" #include "llvm/GlobalVariable.h" +#include "llvm/Metadata.h" +#include "llvm/LLVMContext.h" using namespace llvm; /// CreateGlobalString - Make a new global variable with an initializer that @@ -29,3 +31,16 @@ GV->setName(Name); return GV; } + +/// SetCurrentDebugLocation - Set location information used by debugging +/// information. +void IRBuilderBase::SetCurrentDebugLocation(MDNode *L) { + if (DbgMDKind == 0) + DbgMDKind = Context.getMetadata().getMDKindID("dbg"); + CurDbgLocation = L; +} + +void IRBuilderBase::SetInstDebugLocation(Instruction *I) const { + if (CurDbgLocation) + Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); +} From sabre at nondot.org Mon Dec 28 15:50:56 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 21:50:56 -0000 Subject: [llvm-commits] [llvm] r92231 - in /llvm/trunk: include/llvm/Support/IRBuilder.h lib/VMCore/IRBuilder.cpp Message-ID: <200912282150.nBSLouVT012459@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 15:50:56 2009 New Revision: 92231 URL: http://llvm.org/viewvc/llvm-project?rev=92231&view=rev Log: remove #include of Function.h from IRBuilder Modified: llvm/trunk/include/llvm/Support/IRBuilder.h llvm/trunk/lib/VMCore/IRBuilder.cpp Modified: llvm/trunk/include/llvm/Support/IRBuilder.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/IRBuilder.h?rev=92231&r1=92230&r2=92231&view=diff ============================================================================== --- llvm/trunk/include/llvm/Support/IRBuilder.h (original) +++ llvm/trunk/include/llvm/Support/IRBuilder.h Mon Dec 28 15:50:56 2009 @@ -17,7 +17,7 @@ #include "llvm/Constants.h" #include "llvm/Instructions.h" -#include "llvm/Function.h" +#include "llvm/BasicBlock.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/ConstantFolder.h" @@ -143,6 +143,10 @@ const Type *getVoidTy() { return Type::getVoidTy(Context); } + + /// getCurrentFunctionReturnType - Get the return type of the current function + /// that we're emitting into. + const Type *getCurrentFunctionReturnType() const; }; /// IRBuilder - This provides a uniform API for creating instructions and @@ -221,7 +225,7 @@ ReturnInst *CreateRet(Value *V) { return Insert(ReturnInst::Create(Context, V)); } - + /// CreateAggregateRet - Create a sequence of N insertvalue instructions, /// with one Value from the retVals array each, that build a aggregate /// return value one value at a time, and a ret instruction to return @@ -229,9 +233,8 @@ /// code that uses aggregate return values as a vehicle for having /// multiple return values. /// - ReturnInst *CreateAggregateRet(Value * const* retVals, unsigned N) { - const Type *RetType = BB->getParent()->getReturnType(); - Value *V = UndefValue::get(RetType); + ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) { + Value *V = UndefValue::get(getCurrentFunctionReturnType()); for (unsigned i = 0; i != N; ++i) V = CreateInsertValue(V, retVals[i], i, "mrv"); return Insert(ReturnInst::Create(Context, V)); Modified: llvm/trunk/lib/VMCore/IRBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/IRBuilder.cpp?rev=92231&r1=92230&r2=92231&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/IRBuilder.cpp (original) +++ llvm/trunk/lib/VMCore/IRBuilder.cpp Mon Dec 28 15:50:56 2009 @@ -14,6 +14,7 @@ #include "llvm/Support/IRBuilder.h" #include "llvm/GlobalVariable.h" +#include "llvm/Function.h" #include "llvm/Metadata.h" #include "llvm/LLVMContext.h" using namespace llvm; @@ -44,3 +45,8 @@ if (CurDbgLocation) Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); } + +const Type *IRBuilderBase::getCurrentFunctionReturnType() const { + assert(BB && BB->getParent() && "No current function!"); + return BB->getParent()->getReturnType(); +} From sabre at nondot.org Mon Dec 28 15:52:06 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 21:52:06 -0000 Subject: [llvm-commits] [llvm] r92232 - /llvm/trunk/include/llvm/Support/IRBuilder.h Message-ID: <200912282152.nBSLq6A6012513@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 15:52:06 2009 New Revision: 92232 URL: http://llvm.org/viewvc/llvm-project?rev=92232&view=rev Log: remove #include that comes in from ConstantFolder.h Modified: llvm/trunk/include/llvm/Support/IRBuilder.h Modified: llvm/trunk/include/llvm/Support/IRBuilder.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/IRBuilder.h?rev=92232&r1=92231&r2=92232&view=diff ============================================================================== --- llvm/trunk/include/llvm/Support/IRBuilder.h (original) +++ llvm/trunk/include/llvm/Support/IRBuilder.h Mon Dec 28 15:52:06 2009 @@ -15,7 +15,6 @@ #ifndef LLVM_SUPPORT_IRBUILDER_H #define LLVM_SUPPORT_IRBUILDER_H -#include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/BasicBlock.h" #include "llvm/ADT/Twine.h" From sabre at nondot.org Mon Dec 28 15:52:41 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 21:52:41 -0000 Subject: [llvm-commits] [llvm] r92233 - /llvm/trunk/lib/VMCore/CMakeLists.txt Message-ID: <200912282152.nBSLqfFk012545@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 15:52:41 2009 New Revision: 92233 URL: http://llvm.org/viewvc/llvm-project?rev=92233&view=rev Log: add IRBuilder.cpp to cmake Modified: llvm/trunk/lib/VMCore/CMakeLists.txt Modified: llvm/trunk/lib/VMCore/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/CMakeLists.txt?rev=92233&r1=92232&r2=92233&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/CMakeLists.txt (original) +++ llvm/trunk/lib/VMCore/CMakeLists.txt Mon Dec 28 15:52:41 2009 @@ -13,6 +13,7 @@ Instruction.cpp Instructions.cpp IntrinsicInst.cpp + IRBuilder.cpp LLVMContext.cpp LeakDetector.cpp Mangler.cpp From sabre at nondot.org Mon Dec 28 15:56:07 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 21:56:07 -0000 Subject: [llvm-commits] [llvm] r92234 - /llvm/trunk/include/llvm/Instruction.h Message-ID: <200912282156.nBSLu7j1012644@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 15:56:07 2009 New Revision: 92234 URL: http://llvm.org/viewvc/llvm-project?rev=92234&view=rev Log: rearrange some code. Modified: llvm/trunk/include/llvm/Instruction.h Modified: llvm/trunk/include/llvm/Instruction.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Instruction.h?rev=92234&r1=92233&r2=92234&view=diff ============================================================================== --- llvm/trunk/include/llvm/Instruction.h (original) +++ llvm/trunk/include/llvm/Instruction.h Mon Dec 28 15:56:07 2009 @@ -43,47 +43,11 @@ // Out of line virtual method, so the vtable, etc has a home. ~Instruction(); - /// clone() - Create a copy of 'this' instruction that is identical in all - /// ways except the following: - /// * The instruction has no parent - /// * The instruction has no name - /// - Instruction *clone() const; - - /// isIdenticalTo - Return true if the specified instruction is exactly - /// identical to the current one. This means that all operands match and any - /// extra information (e.g. load is volatile) agree. - bool isIdenticalTo(const Instruction *I) const; - - /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it - /// ignores the SubclassOptionalData flags, which specify conditions - /// under which the instruction's result is undefined. - bool isIdenticalToWhenDefined(const Instruction *I) const; - - /// This function determines if the specified instruction executes the same - /// operation as the current one. This means that the opcodes, type, operand - /// types and any other factors affecting the operation must be the same. This - /// is similar to isIdenticalTo except the operands themselves don't have to - /// be identical. - /// @returns true if the specified instruction is the same operation as - /// the current one. - /// @brief Determine if one instruction is the same operation as another. - bool isSameOperationAs(const Instruction *I) const; - - /// isUsedOutsideOfBlock - Return true if there are any uses of this - /// instruction in blocks other than the specified block. Note that PHI nodes - /// are considered to evaluate their operands in the corresponding predecessor - /// block. - bool isUsedOutsideOfBlock(const BasicBlock *BB) const; - - /// use_back - Specialize the methods defined in Value, as we know that an /// instruction can only be used by other instructions. Instruction *use_back() { return cast(*use_begin());} const Instruction *use_back() const { return cast(*use_begin());} - // Accessor methods... - // inline const BasicBlock *getParent() const { return Parent; } inline BasicBlock *getParent() { return Parent; } @@ -216,6 +180,40 @@ /// for such instructions, moving them may change the resulting value. bool isSafeToSpeculativelyExecute() const; + /// clone() - Create a copy of 'this' instruction that is identical in all + /// ways except the following: + /// * The instruction has no parent + /// * The instruction has no name + /// + Instruction *clone() const; + + /// isIdenticalTo - Return true if the specified instruction is exactly + /// identical to the current one. This means that all operands match and any + /// extra information (e.g. load is volatile) agree. + bool isIdenticalTo(const Instruction *I) const; + + /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it + /// ignores the SubclassOptionalData flags, which specify conditions + /// under which the instruction's result is undefined. + bool isIdenticalToWhenDefined(const Instruction *I) const; + + /// This function determines if the specified instruction executes the same + /// operation as the current one. This means that the opcodes, type, operand + /// types and any other factors affecting the operation must be the same. This + /// is similar to isIdenticalTo except the operands themselves don't have to + /// be identical. + /// @returns true if the specified instruction is the same operation as + /// the current one. + /// @brief Determine if one instruction is the same operation as another. + bool isSameOperationAs(const Instruction *I) const; + + /// isUsedOutsideOfBlock - Return true if there are any uses of this + /// instruction in blocks other than the specified block. Note that PHI nodes + /// are considered to evaluate their operands in the corresponding predecessor + /// block. + bool isUsedOutsideOfBlock(const BasicBlock *BB) const; + + /// Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const Instruction *) { return true; } static inline bool classof(const Value *V) { @@ -223,7 +221,7 @@ } //---------------------------------------------------------------------- - // Exported enumerations... + // Exported enumerations. // enum TermOps { // These terminate basic blocks #define FIRST_TERM_INST(N) TermOpsBegin = N, From sabre at nondot.org Mon Dec 28 17:41:33 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 23:41:33 -0000 Subject: [llvm-commits] [llvm] r92235 - in /llvm/trunk: include/llvm/ lib/Analysis/ lib/AsmParser/ lib/Bitcode/Reader/ lib/Bitcode/Writer/ lib/CodeGen/SelectionDAG/ lib/Transforms/IPO/ lib/Transforms/Utils/ lib/VMCore/ Message-ID: <200912282341.nBSNfXSv015925@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 17:41:32 2009 New Revision: 92235 URL: http://llvm.org/viewvc/llvm-project?rev=92235&view=rev Log: This is a major cleanup of the instruction metadata interfaces that I asked Devang to do back on Sep 27. Instead of going through the MetadataContext class with methods like getMD() and getMDs(), just ask the instruction directly for its metadata with getMetadata() and getAllMetadata(). This includes a variety of other fixes and improvements: previously all Value*'s were bloated because the HasMetadata bit was thrown into value, adding a 9th bit to a byte. Now this is properly sunk down to the Instruction class (the only place where it makes sense) and it will be folded away somewhere soon. This also fixes some confusion in getMDs and its clients about whether the returned list is indexed by the MDID or densely packed. This is now returned sorted and densely packed and the comments make this clear. This introduces a number of fixme's which I'll follow up on. Modified: llvm/trunk/include/llvm/Instruction.h llvm/trunk/include/llvm/Metadata.h llvm/trunk/include/llvm/Value.h llvm/trunk/lib/Analysis/DebugInfo.cpp llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp llvm/trunk/lib/VMCore/AsmWriter.cpp llvm/trunk/lib/VMCore/IRBuilder.cpp llvm/trunk/lib/VMCore/Instruction.cpp llvm/trunk/lib/VMCore/Metadata.cpp llvm/trunk/lib/VMCore/Value.cpp Modified: llvm/trunk/include/llvm/Instruction.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Instruction.h?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/include/llvm/Instruction.h (original) +++ llvm/trunk/include/llvm/Instruction.h Mon Dec 28 17:41:32 2009 @@ -21,6 +21,8 @@ namespace llvm { class LLVMContext; +class MDNode; +class MetadataContextImpl; template class SymbolTableListTraits; @@ -30,6 +32,10 @@ Instruction(const Instruction &); // Do not implement BasicBlock *Parent; + + // FIXME: Bitfieldize this. + bool HasMetadata; + friend class MetadataContextImpl; friend class SymbolTableListTraits; void setParent(BasicBlock *P); @@ -74,19 +80,19 @@ /// MovePos. void moveBefore(Instruction *MovePos); - // --------------------------------------------------------------------------- - /// Subclass classification... getOpcode() returns a member of - /// one of the enums that is coming soon (down below)... - /// + //===--------------------------------------------------------------------===// + // Subclass classification. + //===--------------------------------------------------------------------===// + + /// getOpcode() returns a member of one of the enums like Instruction::Add. unsigned getOpcode() const { return getValueID() - InstructionVal; } + const char *getOpcodeName() const { return getOpcodeName(getOpcode()); } bool isTerminator() const { return isTerminator(getOpcode()); } bool isBinaryOp() const { return isBinaryOp(getOpcode()); } bool isShift() { return isShift(getOpcode()); } bool isCast() const { return isCast(getOpcode()); } - - static const char* getOpcodeName(unsigned OpCode); static inline bool isTerminator(unsigned OpCode) { @@ -118,6 +124,55 @@ return OpCode >= CastOpsBegin && OpCode < CastOpsEnd; } + //===--------------------------------------------------------------------===// + // Metadata manipulation. + //===--------------------------------------------------------------------===// + + /// hasMetadata() - Return true if this instruction has any metadata attached + /// to it. + bool hasMetadata() const { + return HasMetadata; + } + + /// getMetadata - Get the metadata of given kind attached to this Instruction. + /// If the metadata is not found then return null. + MDNode *getMetadata(unsigned KindID) const { + if (!hasMetadata()) return 0; + return getMetadataImpl(KindID); + } + + /// getMetadata - Get the metadata of given kind attached to this Instruction. + /// If the metadata is not found then return null. + MDNode *getMetadata(const char *Kind) const { + if (!hasMetadata()) return 0; + return getMetadataImpl(Kind); + } + + /// getAllMetadata - Get all metadata attached to this Instruction. The first + /// element of each pair returned is the KindID, the second element is the + /// metadata value. This list is returned sorted by the KindID. + void getAllMetadata(SmallVectorImpl > &MDs)const{ + if (hasMetadata()) + getAllMetadataImpl(MDs); + } + + /// setMetadata - Set the metadata of of the specified kind to the specified + /// node. This updates/replaces metadata if already present, or removes it if + /// Node is null. + void setMetadata(unsigned KindID, MDNode *Node); + void setMetadata(const char *Kind, MDNode *Node); + +private: + // These are all implemented in Metadata.cpp. + MDNode *getMetadataImpl(unsigned KindID) const; + MDNode *getMetadataImpl(const char *Kind) const; + void getAllMetadataImpl(SmallVectorImpl > &)const; +public: + //===--------------------------------------------------------------------===// + // Predicates and helper methods. + //===--------------------------------------------------------------------===// + + /// isAssociative - Return true if the instruction is associative: /// /// Associative operators satisfy: x op (y op z) === (x op y) op z Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 17:41:32 2009 @@ -205,6 +205,7 @@ void operator=(MetadataContext&); // DO NOT IMPLEMENT MetadataContextImpl *const pImpl; + friend class Instruction; public: MetadataContext(); ~MetadataContext(); @@ -215,25 +216,6 @@ /// isValidName - Return true if Name is a valid custom metadata handler name. static bool isValidName(StringRef Name); -#if 1 - /// getMD - Get the metadata of given kind attached to an Instruction. - /// If the metadata is not found then return 0. - MDNode *getMD(unsigned Kind, const Instruction *Inst); - - /// getMDs - Get the metadata attached to an Instruction. - void getMDs(const Instruction *Inst, - SmallVectorImpl > &MDs) const; - - /// addMD - Attach the metadata of given kind to an Instruction. - void addMD(unsigned Kind, MDNode *Node, Instruction *Inst); - - /// removeMD - Remove metadata of given kind attached with an instuction. - void removeMD(unsigned Kind, Instruction *Inst); - - /// removeAllMetadata - Remove all metadata attached with an instruction. - void removeAllMetadata(Instruction *Inst); -#endif - /// copyMD - If metadata is attached with Instruction In1 then attach /// the same metadata to In2. void copyMD(Instruction *In1, Instruction *In2); Modified: llvm/trunk/include/llvm/Value.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Value.h?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/include/llvm/Value.h (original) +++ llvm/trunk/include/llvm/Value.h Mon Dec 28 17:41:32 2009 @@ -64,7 +64,6 @@ class Value { const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast) unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this? - unsigned char HasMetadata : 1; // Has a metadata attached to this ? protected: /// SubclassOptionalData - This member is similar to SubclassData, however it /// is for holding information which may be used to aid optimization, but @@ -81,9 +80,7 @@ Use *UseList; friend class ValueSymbolTable; // Allow ValueSymbolTable to directly mod Name. - friend class SymbolTable; // Allow SymbolTable to directly poke Name. friend class ValueHandleBase; - friend class MetadataContextImpl; friend class AbstractTypeUser; ValueName *Name; @@ -303,9 +300,6 @@ const BasicBlock *PredBB) const{ return const_cast(this)->DoPHITranslation(CurBB, PredBB); } - - /// hasMetadata - Return true if metadata is attached with this value. - bool hasMetadata() const { return HasMetadata; } }; inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) { Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Mon Dec 28 17:41:32 2009 @@ -1117,9 +1117,7 @@ /// processModule - Process entire module and collect debug info. void DebugInfoFinder::processModule(Module &M) { - - MetadataContext &TheMetadata = M.getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); + unsigned MDDbgKind = M.getContext().getMetadata().getMDKindID("dbg"); for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI) @@ -1127,7 +1125,7 @@ ++BI) { if (DbgDeclareInst *DDI = dyn_cast(BI)) processDeclare(DDI); - else if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI)) + else if (MDNode *L = BI->getMetadata(MDDbgKind)) processLocation(DILocation(L)); } Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Mon Dec 28 17:41:32 2009 @@ -2826,10 +2826,9 @@ ParseOptionalCustomMetadata(); // Set metadata attached with this instruction. - MetadataContext &TheMetadata = M->getContext().getMetadata(); for (SmallVector, 2>::iterator MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI) - TheMetadata.addMD(MDI->first, MDI->second, Inst); + Inst->setMetadata(MDI->first, MDI->second); MDsOnInst.clear(); BB->getInstList().push_back(Inst); Modified: llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp (original) +++ llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp Mon Dec 28 17:41:32 2009 @@ -18,7 +18,6 @@ #include "llvm/InlineAsm.h" #include "llvm/IntrinsicInst.h" #include "llvm/LLVMContext.h" -#include "llvm/Metadata.h" #include "llvm/Module.h" #include "llvm/Operator.h" #include "llvm/AutoUpgrade.h" @@ -1573,7 +1572,6 @@ if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) return Error("Malformed block record"); - MetadataContext &TheMetadata = Context.getMetadata(); SmallVector Record; while(1) { unsigned Code = Stream.ReadCode(); @@ -1599,7 +1597,7 @@ for (unsigned i = 1; i != RecordLength; i = i+2) { unsigned Kind = Record[i]; Value *Node = MDValueList.getValueFwdRef(Record[i+1]); - TheMetadata.addMD(Kind, cast(Node), Inst); + Inst->setMetadata(Kind, cast(Node)); } break; } Modified: llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp Mon Dec 28 17:41:32 2009 @@ -561,32 +561,29 @@ // Write metadata attachments // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] - MetadataContext &TheMetadata = F.getContext().getMetadata(); - typedef SmallVector, 2> MDMapTy; - MDMapTy MDs; + SmallVector, 4> MDs; + for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { MDs.clear(); - TheMetadata.getMDs(I, MDs); - bool RecordedInstruction = false; - for (MDMapTy::const_iterator PI = MDs.begin(), PE = MDs.end(); - PI != PE; ++PI) { - if (RecordedInstruction == false) { - Record.push_back(VE.getInstructionID(I)); - RecordedInstruction = true; - } - Record.push_back(PI->first); - Record.push_back(VE.getValueID(PI->second)); - } - if (!Record.empty()) { - if (!StartedMetadataBlock) { - Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); - StartedMetadataBlock = true; - } - Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); - Record.clear(); + I->getAllMetadata(MDs); + + // If no metadata, ignore instruction. + if (MDs.empty()) continue; + + Record.push_back(VE.getInstructionID(I)); + + for (unsigned i = 0, e = MDs.size(); i != e; ++i) { + Record.push_back(MDs[i].first); + Record.push_back(VE.getValueID(MDs[i].second)); + } + if (!StartedMetadataBlock) { + Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); + StartedMetadataBlock = true; } + Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); + Record.clear(); } if (StartedMetadataBlock) @@ -1208,7 +1205,7 @@ for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { WriteInstruction(*I, InstID, VE, Stream, Vals); - if (I->getType() != Type::getVoidTy(F.getContext())) + if (!I->getType()->isVoidTy()) ++InstID; } Modified: llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp Mon Dec 28 17:41:32 2009 @@ -14,8 +14,6 @@ #include "ValueEnumerator.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" -#include "llvm/LLVMContext.h" -#include "llvm/Metadata.h" #include "llvm/Module.h" #include "llvm/TypeSymbolTable.h" #include "llvm/ValueSymbolTable.h" @@ -87,9 +85,7 @@ I != E; ++I) EnumerateType(I->getType()); - MetadataContext &TheMetadata = F->getContext().getMetadata(); - typedef SmallVector, 2> MDMapTy; - MDMapTy MDs; + SmallVector, 2> MDs; for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){ for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); @@ -103,10 +99,9 @@ // Enumerate metadata attached with this instruction. MDs.clear(); - TheMetadata.getMDs(I, MDs); - for (MDMapTy::const_iterator MI = MDs.begin(), ME = MDs.end(); MI != ME; - ++MI) - EnumerateMetadata(MI->second); + I->getAllMetadata(MDs); + for (unsigned i = 0, e = MDs.size(); i != e; ++i) + EnumerateMetadata(MDs[i].second); } } Modified: llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp Mon Dec 28 17:41:32 2009 @@ -43,7 +43,6 @@ #include "llvm/GlobalVariable.h" #include "llvm/Instructions.h" #include "llvm/IntrinsicInst.h" -#include "llvm/LLVMContext.h" #include "llvm/CodeGen/FastISel.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" @@ -349,10 +348,7 @@ if (SI == StaticAllocaMap.end()) break; // VLAs. int FI = SI->second; if (MMI) { - MetadataContext &TheMetadata = - DI->getParent()->getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); - if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, DI)) + if (MDNode *Dbg = DI->getMetadata("dbg")) MMI->setVariableDbgInfo(DI->getVariable(), FI, Dbg); } return true; Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Mon Dec 28 17:41:32 2009 @@ -27,7 +27,6 @@ #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/IntrinsicInst.h" -#include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/CodeGen/FastISel.h" #include "llvm/CodeGen/GCStrategy.h" @@ -4379,14 +4378,9 @@ return 0; // VLAs. int FI = SI->second; - MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); - if (MMI) { - MetadataContext &TheMetadata = - DI.getParent()->getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); - if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI)) + if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) + if (MDNode *Dbg = DI.getMetadata("dbg")) MMI->setVariableDbgInfo(Variable, FI, Dbg); - } return 0; } case Intrinsic::eh_exception: { Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp Mon Dec 28 17:41:32 2009 @@ -362,12 +362,12 @@ /// SetDebugLoc - Update MF's and SDB's DebugLocs if debug information is /// attached with this instruction. -static void SetDebugLoc(unsigned MDDbgKind, MetadataContext &TheMetadata, - Instruction *I, SelectionDAGBuilder *SDB, +static void SetDebugLoc(unsigned MDDbgKind, Instruction *I, + SelectionDAGBuilder *SDB, FastISel *FastIS, MachineFunction *MF) { if (isa(I)) return; - if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, I)) { + if (MDNode *Dbg = I->getMetadata(MDDbgKind)) { DILocation DILoc(Dbg); DebugLoc Loc = ExtractDebugLocation(DILoc, MF->getDebugLocInfo()); @@ -384,8 +384,7 @@ } /// ResetDebugLoc - Set MF's and SDB's DebugLocs to Unknown. -static void ResetDebugLoc(SelectionDAGBuilder *SDB, - FastISel *FastIS) { +static void ResetDebugLoc(SelectionDAGBuilder *SDB, FastISel *FastIS) { SDB->setCurDebugLoc(DebugLoc::getUnknownLoc()); if (FastIS) FastIS->setCurDebugLoc(DebugLoc::getUnknownLoc()); @@ -402,7 +401,7 @@ // Lower all of the non-terminator instructions. If a call is emitted // as a tail call, cease emitting nodes for this block. for (BasicBlock::iterator I = Begin; I != End && !SDB->HasTailCall; ++I) { - SetDebugLoc(MDDbgKind, TheMetadata, I, SDB, 0, MF); + SetDebugLoc(MDDbgKind, I, SDB, 0, MF); if (!isa(I)) { SDB->visit(*I); @@ -425,7 +424,7 @@ HandlePHINodesInSuccessorBlocks(LLVMBB); // Lower the terminator after the copies are emitted. - SetDebugLoc(MDDbgKind, TheMetadata, LLVMBB->getTerminator(), SDB, 0, MF); + SetDebugLoc(MDDbgKind, LLVMBB->getTerminator(), SDB, 0, MF); SDB->visit(*LLVMBB->getTerminator()); ResetDebugLoc(SDB, 0); } @@ -776,7 +775,7 @@ break; } - SetDebugLoc(MDDbgKind, TheMetadata, BI, SDB, FastIS, &MF); + SetDebugLoc(MDDbgKind, BI, SDB, FastIS, &MF); // First try normal tablegen-generated "fast" selection. if (FastIS->SelectInstruction(BI)) { Modified: llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp (original) +++ llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp Mon Dec 28 17:41:32 2009 @@ -228,7 +228,7 @@ ++FI) for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) - TheMetadata.removeMD(MDDbgKind, BI); + BI->setMetadata(MDDbgKind, 0); return true; } Modified: llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp (original) +++ llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Mon Dec 28 17:41:32 2009 @@ -426,7 +426,7 @@ MDNode *TheCallMD = NULL; SmallVector MDVs; if (TheCall && TheCall->hasMetadata()) - TheCallMD = Context.getMetadata().getMD(DbgKind, TheCall); + TheCallMD = TheCall->getMetadata(DbgKind); // Handle PHI nodes specially, as we have to remove references to dead // blocks. @@ -436,32 +436,38 @@ for (; (PN = dyn_cast(I)); ++I, ++OldI) { if (I->hasMetadata()) { if (TheCallMD) { - if (MDNode *IMD = Context.getMetadata().getMD(DbgKind, I)) { + if (MDNode *IMD = I->getMetadata(DbgKind)) { MDNode *NewMD = UpdateInlinedAtInfo(IMD, TheCallMD, Context); - Context.getMetadata().addMD(DbgKind, NewMD, I); + I->setMetadata(DbgKind, NewMD); } } else { // The cloned instruction has dbg info but the call instruction // does not have dbg info. Remove dbg info from cloned instruction. - Context.getMetadata().removeMD(DbgKind, I); + I->setMetadata(DbgKind, 0); } } PHIToResolve.push_back(cast(OldI)); } } + // FIXME: + // FIXME: + // FIXME: Unclone all this metadata stuff. + // FIXME: + // FIXME: + // Otherwise, remap the rest of the instructions normally. for (; I != NewBB->end(); ++I) { if (I->hasMetadata()) { if (TheCallMD) { - if (MDNode *IMD = Context.getMetadata().getMD(DbgKind, I)) { + if (MDNode *IMD = I->getMetadata(DbgKind)) { MDNode *NewMD = UpdateInlinedAtInfo(IMD, TheCallMD, Context); - Context.getMetadata().addMD(DbgKind, NewMD, I); + I->setMetadata(DbgKind, NewMD); } } else { // The cloned instruction has dbg info but the call instruction // does not have dbg info. Remove dbg info from cloned instruction. - Context.getMetadata().removeMD(DbgKind, I); + I->setMetadata(DbgKind, 0); } } RemapInstruction(I, ValueMap); Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Mon Dec 28 17:41:32 2009 @@ -21,11 +21,9 @@ #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/InlineAsm.h" -#include "llvm/Instruction.h" -#include "llvm/Instructions.h" +#include "llvm/IntrinsicInst.h" #include "llvm/LLVMContext.h" #include "llvm/Operator.h" -#include "llvm/Metadata.h" #include "llvm/Module.h" #include "llvm/ValueSymbolTable.h" #include "llvm/TypeSymbolTable.h" @@ -680,30 +678,30 @@ ST_DEBUG("Inserting Instructions:\n"); - MetadataContext &TheMetadata = TheFunction->getContext().getMetadata(); - typedef SmallVector, 2> MDMapTy; - MDMapTy MDs; + SmallVector, 2> MDForInst; // Add all of the basic blocks and instructions with no names. for (Function::const_iterator BB = TheFunction->begin(), E = TheFunction->end(); BB != E; ++BB) { if (!BB->hasName()) CreateFunctionSlot(BB); + for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { - if (I->getType() != Type::getVoidTy(TheFunction->getContext()) && - !I->hasName()) + if (!I->getType()->isVoidTy() && !I->hasName()) CreateFunctionSlot(I); - for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) - if (MDNode *N = dyn_cast_or_null(I->getOperand(i))) - CreateMetadataSlot(N); + + // Intrinsics can directly use metadata. + if (isa(I)) + for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) + if (MDNode *N = dyn_cast_or_null(I->getOperand(i))) + CreateMetadataSlot(N); // Process metadata attached with this instruction. - MDs.clear(); - TheMetadata.getMDs(I, MDs); - for (MDMapTy::const_iterator MI = MDs.begin(), ME = MDs.end(); MI != ME; - ++MI) - CreateMetadataSlot(MI->second); + MDForInst.clear(); + I->getAllMetadata(MDForInst); + for (unsigned i = 0, e = MDForInst.size(); i != e; ++i) + CreateMetadataSlot(MDForInst[i].second); } } @@ -2076,14 +2074,11 @@ // Print Metadata info. if (!MDNames.empty()) { - MetadataContext &TheMetadata = I.getContext().getMetadata(); - typedef SmallVector, 2> MDMapTy; - MDMapTy MDs; - TheMetadata.getMDs(&I, MDs); - for (MDMapTy::const_iterator MI = MDs.begin(), ME = MDs.end(); MI != ME; - ++MI) - Out << ", !" << MDNames[MI->first] - << " !" << Machine.getMetadataSlot(MI->second); + SmallVector, 4> InstMD; + I.getAllMetadata(InstMD); + for (unsigned i = 0, e = InstMD.size(); i != e; ++i) + Out << ", !" << MDNames[InstMD[i].first] + << " !" << Machine.getMetadataSlot(InstMD[i].second); } printInfoComment(I); } Modified: llvm/trunk/lib/VMCore/IRBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/IRBuilder.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/IRBuilder.cpp (original) +++ llvm/trunk/lib/VMCore/IRBuilder.cpp Mon Dec 28 17:41:32 2009 @@ -43,7 +43,7 @@ void IRBuilderBase::SetInstDebugLocation(Instruction *I) const { if (CurDbgLocation) - Context.getMetadata().addMD(DbgMDKind, CurDbgLocation, I); + I->setMetadata(DbgMDKind, CurDbgLocation); } const Type *IRBuilderBase::getCurrentFunctionReturnType() const { Modified: llvm/trunk/lib/VMCore/Instruction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Instruction.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Instruction.cpp (original) +++ llvm/trunk/lib/VMCore/Instruction.cpp Mon Dec 28 17:41:32 2009 @@ -24,7 +24,8 @@ Instruction::Instruction(const Type *ty, unsigned it, Use *Ops, unsigned NumOps, Instruction *InsertBefore) - : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0) { + : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0), + HasMetadata(false) { // Make sure that we get added to a basicblock LeakDetector::addGarbageObject(this); @@ -38,7 +39,8 @@ Instruction::Instruction(const Type *ty, unsigned it, Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd) - : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0) { + : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0), + HasMetadata(false) { // Make sure that we get added to a basicblock LeakDetector::addGarbageObject(this); @@ -51,10 +53,8 @@ // Out of line virtual method, so the vtable, etc has a home. Instruction::~Instruction() { assert(Parent == 0 && "Instruction still linked in the program!"); - if (hasMetadata()) { - LLVMContext &Context = getContext(); - Context.pImpl->TheMetadata.ValueIsDeleted(this); - } + if (HasMetadata) + getContext().pImpl->TheMetadata.ValueIsDeleted(this); } @@ -464,7 +464,7 @@ Instruction *Instruction::clone() const { Instruction *New = clone_impl(); New->SubclassOptionalData = SubclassOptionalData; - if (hasMetadata()) + if (HasMetadata) getContext().pImpl->TheMetadata.ValueIsCloned(this, New); return New; } Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 17:41:32 2009 @@ -261,32 +261,27 @@ StringMap MDHandlerNames; public: + // Name <-> ID mapping methods. unsigned getMDKindID(StringRef Name); - - /// getMD - Get the metadata of given kind attached to an Instruction. - /// If the metadata is not found then return 0. - MDNode *getMD(unsigned Kind, const Instruction *Inst); - - /// getMDs - Get the metadata attached to an Instruction. - void getMDs(const Instruction *Inst, - SmallVectorImpl > &MDs) const; - - /// addMD - Attach the metadata of given kind to an Instruction. - void addMD(unsigned Kind, MDNode *Node, Instruction *Inst); + void getMDKindNames(SmallVectorImpl &) const; - /// removeMD - Remove metadata of given kind attached with an instruction. - void removeMD(unsigned Kind, Instruction *Inst); + // Instruction metadata methods. + MDNode *getMetadata(const Instruction *Inst, unsigned Kind); + void getAllMetadata(const Instruction *Inst, + SmallVectorImpl > &MDs)const; + + void setMetadata(Instruction *Inst, unsigned Kind, MDNode *Node); + /// removeAllMetadata - Remove all metadata attached with an instruction. void removeAllMetadata(Instruction *Inst); - + + + /// copyMD - If metadata is attached with Instruction In1 then attach /// the same metadata to In2. void copyMD(Instruction *In1, Instruction *In2); - - /// getMDKindNames - Populate client-supplied smallvector using custom - /// metadata name and ID. - void getMDKindNames(SmallVectorImpl &) const; + /// ValueIsDeleted - This handler is used to update metadata store /// when a value is deleted. @@ -308,49 +303,96 @@ // If this is new, assign it its ID. if (Entry == 0) Entry = MDHandlerNames.size(); - return Entry; } -/// addMD - Attach the metadata of given kind to an Instruction. -void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node, - Instruction *Inst) { - assert(Node && "Invalid null MDNode"); - Inst->HasMetadata = true; +/// getHandlerNames - Populate client supplied smallvector using custome +/// metadata name and ID. +void MetadataContextImpl:: +getMDKindNames(SmallVectorImpl &Names) const { + Names.resize(MDHandlerNames.size()+1); + Names[0] = ""; + for (StringMap::const_iterator I = MDHandlerNames.begin(), + E = MDHandlerNames.end(); I != E; ++I) + // MD Handlers are numbered from 1. + Names[I->second] = I->first(); +} + + +/// getMetadata - Get the metadata of given kind attached to an Instruction. +/// If the metadata is not found then return 0. +MDNode *MetadataContextImpl:: +getMetadata(const Instruction *Inst, unsigned MDKind) { MDMapTy &Info = MetadataStore[Inst]; - if (Info.empty()) { - Info.push_back(std::make_pair(MDKind, Node)); - MetadataStore.insert(std::make_pair(Inst, Info)); - return; - } + assert(Inst->hasMetadata() && !Info.empty() && "Shouldn't have called this"); + + for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I) + if (I->first == MDKind) + return I->second; + return 0; +} - // If there is an entry for this MDKind then replace it. - for (unsigned i = 0, e = Info.size(); i != e; ++i) { - MDPairTy &P = Info[i]; - if (P.first == MDKind) { - Info[i] = std::make_pair(MDKind, Node); - return; - } - } +/// getAllMetadata - Get all of the metadata attached to an Instruction. +void MetadataContextImpl:: +getAllMetadata(const Instruction *Inst, + SmallVectorImpl > &Result) const { + assert(Inst->hasMetadata() && MetadataStore.find(Inst) != MetadataStore.end() + && "Shouldn't have called this"); + const MDMapTy &Info = MetadataStore.find(Inst)->second; + assert(!Info.empty() && "Shouldn't have called this"); - // Otherwise add a new entry. - Info.push_back(std::make_pair(MDKind, Node)); + Result.clear(); + Result.append(Info.begin(), Info.end()); + + // Sort the resulting array so it is stable. + if (Result.size() > 1) + array_pod_sort(Result.begin(), Result.end()); } -/// removeMD - Remove metadata of given kind attached with an instruction. -void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) { - MDStoreTy::iterator I = MetadataStore.find(Inst); - if (I == MetadataStore.end()) + +void MetadataContextImpl::setMetadata(Instruction *Inst, unsigned Kind, + MDNode *Node) { + // Handle the case when we're adding/updating metadata on an instruction. + if (Node) { + MDMapTy &Info = MetadataStore[Inst]; + assert(!Info.empty() == Inst->HasMetadata && "HasMetadata bit is wonked"); + if (Info.empty()) { + Inst->HasMetadata = true; + } else { + // Handle replacement of an existing value. + for (unsigned i = 0, e = Info.size(); i != e; ++i) + if (Info[i].first == Kind) { + Info[i].second = Node; + return; + } + } + + // No replacement, just add it to the list. + Info.push_back(std::make_pair(Kind, Node)); return; + } + + // Otherwise, we're removing metadata from an instruction. + assert(Inst->HasMetadata && MetadataStore.count(Inst) && + "HasMetadata bit out of date!"); + MDMapTy &Info = MetadataStore[Inst]; - MDMapTy &Info = I->second; - for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) { - MDPairTy &P = *MI; - if (P.first == Kind) { - Info.erase(MI); + // Common case is removing the only entry. + if (Info.size() == 1 && Info[0].first == Kind) { + MetadataStore.erase(Inst); + Inst->HasMetadata = false; + return; + } + + // Handle replacement of an existing value. + for (unsigned i = 0, e = Info.size(); i != e; ++i) + if (Info[i].first == Kind) { + Info[i] = Info.back(); + Info.pop_back(); + assert(!Info.empty() && "Removing last entry should be handled above"); return; } - } + // Otherwise, removing an entry that doesn't exist on the instruction. } /// removeAllMetadata - Remove all metadata attached with an instruction. @@ -359,6 +401,7 @@ Inst->HasMetadata = false; } + /// copyMD - If metadata is attached with Instruction In1 then attach /// the same metadata to In2. void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) { @@ -366,48 +409,9 @@ MDMapTy &In1Info = MetadataStore[In1]; if (In1Info.empty()) return; - + for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I) - addMD(I->first, I->second, In2); -} - -/// getMD - Get the metadata of given kind attached to an Instruction. -/// If the metadata is not found then return 0. -MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) { - MDMapTy &Info = MetadataStore[Inst]; - if (Info.empty()) - return NULL; - - for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I) - if (I->first == MDKind) - return I->second; - return NULL; -} - -/// getMDs - Get the metadata attached to an Instruction. -void MetadataContextImpl:: -getMDs(const Instruction *Inst, - SmallVectorImpl > &MDs) const { - MDStoreTy::const_iterator I = MetadataStore.find(Inst); - if (I == MetadataStore.end()) - return; - MDs.resize(I->second.size()); - for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end(); - MI != ME; ++MI) - // MD kinds are numbered from 1. - MDs[MI->first - 1] = std::make_pair(MI->first, MI->second); -} - -/// getHandlerNames - Populate client supplied smallvector using custome -/// metadata name and ID. -void MetadataContextImpl:: -getMDKindNames(SmallVectorImpl &Names) const { - Names.resize(MDHandlerNames.size()+1); - Names[0] = ""; - for (StringMap::const_iterator I = MDHandlerNames.begin(), - E = MDHandlerNames.end(); I != E; ++I) - // MD Handlers are numbered from 1. - Names[I->second] = I->first(); + In2->setMetadata(I->first, I->second); } /// ValueIsCloned - This handler is used to update metadata store @@ -421,7 +425,7 @@ // FIXME: Give all metadata handlers a chance to adjust. MDMapTy &In1Info = I->second; for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I) - addMD(I->first, I->second, In2); + In2->setMetadata(I->first, I->second); } /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by @@ -463,34 +467,6 @@ return pImpl->getMDKindID(Name); } -/// getMD - Get the metadata of given kind attached to an Instruction. -/// If the metadata is not found then return 0. -MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) { - return pImpl->getMD(Kind, Inst); -} - -/// getMDs - Get the metadata attached to an Instruction. -void MetadataContext:: -getMDs(const Instruction *Inst, - SmallVectorImpl > &MDs) const { - return pImpl->getMDs(Inst, MDs); -} - -/// addMD - Attach the metadata of given kind to an Instruction. -void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) { - pImpl->addMD(Kind, Node, Inst); -} - -/// removeMD - Remove metadata of given kind attached with an instruction. -void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) { - pImpl->removeMD(Kind, Inst); -} - -/// removeAllMetadata - Remove all metadata attached with an instruction. -void MetadataContext::removeAllMetadata(Instruction *Inst) { - pImpl->removeAllMetadata(Inst); -} - /// copyMD - If metadata is attached with Instruction In1 then attach /// the same metadata to In2. void MetadataContext::copyMD(Instruction *In1, Instruction *In2) { @@ -517,3 +493,35 @@ void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) { pImpl->ValueIsCloned(In1, In2); } + +//===----------------------------------------------------------------------===// +// Instruction Metadata method implementations. +// + +void Instruction::setMetadata(const char *Kind, MDNode *Node) { + if (Node == 0 && !hasMetadata()) return; + setMetadata(getContext().getMetadata().getMDKindID(Kind), Node); +} + +MDNode *Instruction::getMetadataImpl(const char *Kind) const { + return getMetadataImpl(getContext().getMetadata().getMDKindID(Kind)); +} + +/// setMetadata - Set the metadata of of the specified kind to the specified +/// node. This updates/replaces metadata if already present, or removes it if +/// Node is null. +void Instruction::setMetadata(unsigned KindID, MDNode *Node) { + if (Node == 0 && !hasMetadata()) return; + + getContext().getMetadata().pImpl->setMetadata(this, KindID, Node); +} + +MDNode *Instruction::getMetadataImpl(unsigned KindID) const { + return getContext().getMetadata().pImpl->getMetadata(this, KindID); +} + +void Instruction::getAllMetadataImpl(SmallVectorImpl > &Result)const { + getContext().getMetadata().pImpl->getAllMetadata(this, Result); +} + Modified: llvm/trunk/lib/VMCore/Value.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Value.cpp?rev=92235&r1=92234&r2=92235&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Value.cpp (original) +++ llvm/trunk/lib/VMCore/Value.cpp Mon Dec 28 17:41:32 2009 @@ -41,7 +41,7 @@ } Value::Value(const Type *ty, unsigned scid) - : SubclassID(scid), HasValueHandle(0), HasMetadata(0), + : SubclassID(scid), HasValueHandle(0), SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)), UseList(0), Name(0) { if (isa(this) || isa(this)) @@ -57,11 +57,6 @@ } Value::~Value() { - if (HasMetadata) { - LLVMContext &Context = getContext(); - Context.pImpl->TheMetadata.ValueIsDeleted(this); - } - // Notify all ValueHandles (if present) that this value is going away. if (HasValueHandle) ValueHandleBase::ValueIsDeleted(this); @@ -306,10 +301,14 @@ // Notify all ValueHandles (if present) that this value is going away. if (HasValueHandle) ValueHandleBase::ValueIsRAUWd(this, New); - if (HasMetadata) { - LLVMContext &Context = getContext(); - Context.pImpl->TheMetadata.ValueIsRAUWd(this, New); - } + + // FIXME: It doesn't make sense at all for metadata to follow RAUW. + if (Instruction *I = dyn_cast(this)) + if (I->hasMetadata()) { + LLVMContext &Context = getContext(); + // FIXME: NUKE ValueIsRAUWd?? + Context.pImpl->TheMetadata.ValueIsRAUWd(this, New); + } while (!use_empty()) { Use &U = *UseList; From sabre at nondot.org Mon Dec 28 17:41:53 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 23:41:53 -0000 Subject: [llvm-commits] [llvm-gcc-4.2] r92237 - /llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp Message-ID: <200912282341.nBSNfrA0015955@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 17:41:53 2009 New Revision: 92237 URL: http://llvm.org/viewvc/llvm-project?rev=92237&view=rev Log: adjust for llvm api changes. Modified: llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp Modified: llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp?rev=92237&r1=92236&r2=92237&view=diff ============================================================================== --- llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp (original) +++ llvm-gcc-4.2/trunk/gcc/llvm-debug.cpp Mon Dec 28 17:41:53 2009 @@ -376,15 +376,11 @@ Instruction *Call = DebugFactory.InsertDeclare(AI, D, Builder.GetInsertBlock()); -// llvm::DIDescriptor DR = RegionStack.back(); -// llvm::DIScope DS = llvm::DIScope(DR.getNode()); llvm::DILocation DO(NULL); llvm::DILocation DL = DebugFactory.CreateLocation(CurLineNo, 0 /* column */, VarScope, DO); - llvm::LLVMContext &Context = Call->getContext(); - unsigned DbgMDKind = Context.getMetadata().getMDKindID("dbg"); - Context.getMetadata().addMD(DbgMDKind, DL.getNode(), Call); + Call->setMetadata("dbg", DL.getNode()); } @@ -398,8 +394,7 @@ // In an earlier part of gcc, code that sets up Apple Block by-reference // variables at the beginning of the function (which should be part of the // prologue but isn't), is assigned a source location line of one before the - // function decl. So we check for that here: - + // function decl. We check for that here. if (BLOCK_SYNTHESIZED_FUNC(cfun->decl)) { int fn_decl_line = DECL_SOURCE_LINE(cfun->decl); if (lineno == (unsigned)(fn_decl_line - 1)) From sabre at nondot.org Mon Dec 28 17:45:29 2009 From: sabre at nondot.org (Chris Lattner) Date: Mon, 28 Dec 2009 23:45:29 -0000 Subject: [llvm-commits] [llvm-gcc-4.2] r92238 - /llvm-gcc-4.2/trunk/gcc/llvm-abi.h Message-ID: <200912282345.nBSNjTmV016062@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 17:45:29 2009 New Revision: 92238 URL: http://llvm.org/viewvc/llvm-project?rev=92238&view=rev Log: 'fix' buildbot breakage by #including Compiler.h back where we used to implicitly get it before I pruned #includes. Not doing this runs into problems on some builders because we define ATTRIBUTE_UNUSED and so does GCC. Our macro isn't wrapped with #ifndef and theirs is, so we have to get ours first, yay for fragility. Modified: llvm-gcc-4.2/trunk/gcc/llvm-abi.h Modified: llvm-gcc-4.2/trunk/gcc/llvm-abi.h URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/gcc/llvm-abi.h?rev=92238&r1=92237&r2=92238&view=diff ============================================================================== --- llvm-gcc-4.2/trunk/gcc/llvm-abi.h (original) +++ llvm-gcc-4.2/trunk/gcc/llvm-abi.h Mon Dec 28 17:45:29 2009 @@ -37,6 +37,7 @@ #include "llvm/DerivedTypes.h" #include "llvm/LLVMContext.h" #include "llvm/Target/TargetData.h" +#include "llvm/Support/Compiler.h" namespace llvm { class BasicBlock; From sabre at nondot.org Mon Dec 28 20:14:09 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 02:14:09 -0000 Subject: [llvm-commits] [llvm] r92239 - in /llvm/trunk: include/llvm/BasicBlock.h include/llvm/Constants.h include/llvm/Function.h include/llvm/InstrTypes.h include/llvm/Instructions.h include/llvm/Metadata.h include/llvm/Value.h lib/VMCore/Constants.cpp lib/VMCore/Function.cpp lib/VMCore/Instructions.cpp lib/VMCore/Metadata.cpp Message-ID: <200912290214.nBT2EA9L020500@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 20:14:09 2009 New Revision: 92239 URL: http://llvm.org/viewvc/llvm-project?rev=92239&view=rev Log: add a layer of accessors around the Value::SubClassData member, and use a convention (shadowing the setter with private forwarding function) to prevent subclasses from accidentally using it. This exposed some bogosity in ConstantExprs, which was propaging the opcode of the constant expr into the NUW/NSW/Exact field in the getWithOperands/getWithOperandReplaced methods. Modified: llvm/trunk/include/llvm/BasicBlock.h llvm/trunk/include/llvm/Constants.h llvm/trunk/include/llvm/Function.h llvm/trunk/include/llvm/InstrTypes.h llvm/trunk/include/llvm/Instructions.h llvm/trunk/include/llvm/Metadata.h llvm/trunk/include/llvm/Value.h llvm/trunk/lib/VMCore/Constants.cpp llvm/trunk/lib/VMCore/Function.cpp llvm/trunk/lib/VMCore/Instructions.cpp llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/BasicBlock.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/BasicBlock.h?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/include/llvm/BasicBlock.h (original) +++ llvm/trunk/include/llvm/BasicBlock.h Mon Dec 28 20:14:09 2009 @@ -239,15 +239,21 @@ /// hasAddressTaken - returns true if there are any uses of this basic block /// other than direct branches, switches, etc. to it. - bool hasAddressTaken() const { return SubclassData != 0; } + bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; } private: /// AdjustBlockAddressRefCount - BasicBlock stores the number of BlockAddress /// objects using it. This is almost always 0, sometimes one, possibly but /// almost never 2, and inconceivably 3 or more. void AdjustBlockAddressRefCount(int Amt) { - SubclassData += Amt; - assert((int)(signed char)SubclassData >= 0 && "Refcount wrap-around"); + setValueSubclassData(getSubclassDataFromValue()+Amt); + assert((int)(signed char)getSubclassDataFromValue() >= 0 && + "Refcount wrap-around"); + } + // Shadow Value::setValueSubclassData with a private forwarding method so that + // any future subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); } }; Modified: llvm/trunk/include/llvm/Constants.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Constants.h?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/include/llvm/Constants.h (original) +++ llvm/trunk/include/llvm/Constants.h Mon Dec 28 20:14:09 2009 @@ -605,7 +605,7 @@ ConstantExpr(const Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps) : Constant(ty, ConstantExprVal, Ops, NumOps) { // Operation type (an Instruction opcode) is stored as the SubclassData. - SubclassData = Opcode; + setValueSubclassData(Opcode); } // These private methods are used by the type resolution code to create @@ -814,7 +814,7 @@ virtual bool isNullValue() const { return false; } /// getOpcode - Return the opcode at the root of this constant expression - unsigned getOpcode() const { return SubclassData; } + unsigned getOpcode() const { return getSubclassDataFromValue(); } /// getPredicate - Return the ICMP or FCMP predicate value. Assert if this is /// not an ICMP or FCMP constant expression. @@ -847,6 +847,13 @@ static inline bool classof(const Value *V) { return V->getValueID() == ConstantExprVal; } + +private: + // Shadow Value::setValueSubclassData with a private forwarding method so that + // subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } }; template <> Modified: llvm/trunk/include/llvm/Function.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Function.h?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/include/llvm/Function.h (original) +++ llvm/trunk/include/llvm/Function.h Mon Dec 28 20:14:09 2009 @@ -87,6 +87,9 @@ ValueSymbolTable *SymTab; ///< Symbol table of args/instructions AttrListPtr AttributeList; ///< Parameter attributes + // HasLazyArguments is stored in Value::SubclassData. + /*bool HasLazyArguments;*/ + // The Calling Convention is stored in Value::SubclassData. /*CallingConv::ID CallingConvention;*/ @@ -99,7 +102,7 @@ /// needs it. The hasLazyArguments predicate returns true if the arg list /// hasn't been set up yet. bool hasLazyArguments() const { - return SubclassData & 1; + return getSubclassDataFromValue() & 1; } void CheckLazyArguments() const { if (hasLazyArguments()) @@ -156,10 +159,11 @@ /// calling convention of this function. The enum values for the known /// calling conventions are defined in CallingConv.h. CallingConv::ID getCallingConv() const { - return static_cast(SubclassData >> 1); + return static_cast(getSubclassDataFromValue() >> 1); } void setCallingConv(CallingConv::ID CC) { - SubclassData = (SubclassData & 1) | (static_cast(CC) << 1); + setValueSubclassData((getSubclassDataFromValue() & 1) | + (static_cast(CC) << 1)); } /// getAttributes - Return the attribute list for this Function. @@ -407,6 +411,12 @@ /// hasAddressTaken - returns true if there are any uses of this function /// other than direct calls or invokes to it. bool hasAddressTaken() const; +private: + // Shadow Value::setValueSubclassData with a private forwarding method so that + // subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } }; inline ValueSymbolTable * Modified: llvm/trunk/include/llvm/InstrTypes.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/InstrTypes.h?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/include/llvm/InstrTypes.h (original) +++ llvm/trunk/include/llvm/InstrTypes.h Mon Dec 28 20:14:09 2009 @@ -732,10 +732,12 @@ } /// @brief Return the predicate for this instruction. - Predicate getPredicate() const { return Predicate(SubclassData); } + Predicate getPredicate() const { + return Predicate(getSubclassDataFromValue()); + } /// @brief Set the predicate for this instruction to the specified value. - void setPredicate(Predicate P) { SubclassData = P; } + void setPredicate(Predicate P) { setValueSubclassData(P); } static bool isFPPredicate(Predicate P) { return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE; @@ -856,6 +858,12 @@ } return Type::getInt1Ty(opnd_type->getContext()); } +private: + // Shadow Value::setValueSubclassData with a private forwarding method so that + // subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } }; Modified: llvm/trunk/include/llvm/Instructions.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Instructions.h?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/include/llvm/Instructions.h (original) +++ llvm/trunk/include/llvm/Instructions.h Mon Dec 28 20:14:09 2009 @@ -82,7 +82,9 @@ /// getAlignment - Return the alignment of the memory that is being allocated /// by the instruction. /// - unsigned getAlignment() const { return (1u << SubclassData) >> 1; } + unsigned getAlignment() const { + return (1u << getSubclassDataFromValue()) >> 1; + } void setAlignment(unsigned Align); /// isStaticAlloca - Return true if this alloca is in the entry block of the @@ -98,6 +100,12 @@ static inline bool classof(const Value *V) { return isa(V) && classof(cast(V)); } +private: + // Shadow Value::setValueSubclassData with a private forwarding method so that + // subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } }; @@ -134,18 +142,18 @@ /// isVolatile - Return true if this is a load from a volatile memory /// location. /// - bool isVolatile() const { return SubclassData & 1; } + bool isVolatile() const { return getSubclassDataFromValue() & 1; } /// setVolatile - Specify whether this is a volatile load or not. /// void setVolatile(bool V) { - SubclassData = (SubclassData & ~1) | (V ? 1 : 0); + setValueSubclassData((getSubclassDataFromValue() & ~1) | (V ? 1 : 0)); } /// getAlignment - Return the alignment of the access that is being performed /// unsigned getAlignment() const { - return (1 << (SubclassData>>1)) >> 1; + return (1 << (getSubclassDataFromValue() >> 1)) >> 1; } void setAlignment(unsigned Align); @@ -167,6 +175,12 @@ static inline bool classof(const Value *V) { return isa(V) && classof(cast(V)); } +private: + // Shadow Value::setValueSubclassData with a private forwarding method so that + // subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } }; @@ -200,12 +214,12 @@ /// isVolatile - Return true if this is a load from a volatile memory /// location. /// - bool isVolatile() const { return SubclassData & 1; } + bool isVolatile() const { return getSubclassDataFromValue() & 1; } /// setVolatile - Specify whether this is a volatile load or not. /// void setVolatile(bool V) { - SubclassData = (SubclassData & ~1) | (V ? 1 : 0); + setValueSubclassData((getSubclassDataFromValue() & ~1) | (V ? 1 : 0)); } /// Transparently provide more efficient getOperand methods. @@ -214,7 +228,7 @@ /// getAlignment - Return the alignment of the access that is being performed /// unsigned getAlignment() const { - return (1 << (SubclassData>>1)) >> 1; + return (1 << (getSubclassDataFromValue() >> 1)) >> 1; } void setAlignment(unsigned Align); @@ -235,6 +249,12 @@ static inline bool classof(const Value *V) { return isa(V) && classof(cast(V)); } +private: + // Shadow Value::setValueSubclassData with a private forwarding method so that + // subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } }; template <> @@ -675,7 +695,7 @@ /// (e.g. ult). /// @brief Swap operands and adjust predicate. void swapOperands() { - SubclassData = getSwappedPredicate(); + setPredicate(getSwappedPredicate()); Op<0>().swap(Op<1>()); } @@ -761,18 +781,18 @@ /// @returns true if the predicate of this instruction is EQ or NE. /// @brief Determine if this is an equality predicate. bool isEquality() const { - return SubclassData == FCMP_OEQ || SubclassData == FCMP_ONE || - SubclassData == FCMP_UEQ || SubclassData == FCMP_UNE; + return getPredicate() == FCMP_OEQ || getPredicate() == FCMP_ONE || + getPredicate() == FCMP_UEQ || getPredicate() == FCMP_UNE; } /// @returns true if the predicate of this instruction is commutative. /// @brief Determine if this is a commutative predicate. bool isCommutative() const { return isEquality() || - SubclassData == FCMP_FALSE || - SubclassData == FCMP_TRUE || - SubclassData == FCMP_ORD || - SubclassData == FCMP_UNO; + getPredicate() == FCMP_FALSE || + getPredicate() == FCMP_TRUE || + getPredicate() == FCMP_ORD || + getPredicate() == FCMP_UNO; } /// @returns true if the predicate is relational (not EQ or NE). @@ -785,7 +805,7 @@ /// (e.g. ult). /// @brief Swap operands and adjust predicate. void swapOperands() { - SubclassData = getSwappedPredicate(); + setPredicate(getSwappedPredicate()); Op<0>().swap(Op<1>()); } @@ -800,14 +820,11 @@ }; //===----------------------------------------------------------------------===// -// CallInst Class -//===----------------------------------------------------------------------===// /// CallInst - This class represents a function call, abstracting a target /// machine's calling convention. This class uses low bit of the SubClassData /// field to indicate whether or not this is a tail call. The rest of the bits /// hold the calling convention of the call. /// - class CallInst : public Instruction { AttrListPtr AttributeList; ///< parameter attributes for call CallInst(const CallInst &CI); @@ -912,9 +929,9 @@ ~CallInst(); - bool isTailCall() const { return SubclassData & 1; } + bool isTailCall() const { return getSubclassDataFromValue() & 1; } void setTailCall(bool isTC = true) { - SubclassData = (SubclassData & ~1) | unsigned(isTC); + setValueSubclassData((getSubclassDataFromValue() & ~1) | unsigned(isTC)); } /// Provide fast operand accessors @@ -923,10 +940,11 @@ /// getCallingConv/setCallingConv - Get or set the calling convention of this /// function call. CallingConv::ID getCallingConv() const { - return static_cast(SubclassData >> 1); + return static_cast(getSubclassDataFromValue() >> 1); } void setCallingConv(CallingConv::ID CC) { - SubclassData = (SubclassData & 1) | (static_cast(CC) << 1); + setValueSubclassData((getSubclassDataFromValue() & 1) | + (static_cast(CC) << 1)); } /// getAttributes - Return the parameter attributes for this call. @@ -1024,6 +1042,12 @@ static inline bool classof(const Value *V) { return isa(V) && classof(cast(V)); } +private: + // Shadow Value::setValueSubclassData with a private forwarding method so that + // subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } }; template <> @@ -2401,10 +2425,10 @@ /// getCallingConv/setCallingConv - Get or set the calling convention of this /// function call. CallingConv::ID getCallingConv() const { - return static_cast(SubclassData); + return static_cast(getSubclassDataFromValue()); } void setCallingConv(CallingConv::ID CC) { - SubclassData = static_cast(CC); + setValueSubclassData(static_cast(CC)); } /// getAttributes - Return the parameter attributes for this invoke. @@ -2528,6 +2552,12 @@ virtual BasicBlock *getSuccessorV(unsigned idx) const; virtual unsigned getNumSuccessorsV() const; virtual void setSuccessorV(unsigned idx, BasicBlock *B); + + // Shadow Value::setValueSubclassData with a private forwarding method so that + // subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } }; template <> Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 20:14:09 2009 @@ -125,7 +125,9 @@ /// Note: MDNodes are designated as function-local when created, and keep /// that designation even if their operands are modified to no longer /// refer to function-local IR. - bool isFunctionLocal() const { return SubclassData & FunctionLocalBit; } + bool isFunctionLocal() const { + return (getSubclassDataFromValue() & FunctionLocalBit) != 0; + } /// Profile - calculate a unique identifier for this MDNode to collapse /// duplicates @@ -136,6 +138,12 @@ static bool classof(const Value *V) { return V->getValueID() == MDNodeVal; } +private: + // Shadow Value::setValueSubclassData with a private forwarding method so that + // any future subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } }; //===----------------------------------------------------------------------===// Modified: llvm/trunk/include/llvm/Value.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Value.h?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/include/llvm/Value.h (original) +++ llvm/trunk/include/llvm/Value.h Mon Dec 28 20:14:09 2009 @@ -57,7 +57,7 @@ /// /// Every value has a "use list" that keeps track of which other Values are /// using this Value. A Value can also have an arbitrary number of ValueHandle -/// objects that watch it and listen to RAUW and Destroy events see +/// objects that watch it and listen to RAUW and Destroy events. See /// llvm/Support/ValueHandle.h for details. /// /// @brief LLVM Value Representation @@ -71,11 +71,12 @@ /// interpretation. unsigned char SubclassOptionalData : 7; +private: /// SubclassData - This member is defined by this class, but is not used for /// anything. Subclasses can use it to hold whatever state they find useful. /// This field is initialized to zero by the ctor. unsigned short SubclassData; -private: + PATypeHolder VTy; Use *UseList; @@ -300,6 +301,10 @@ const BasicBlock *PredBB) const{ return const_cast(this)->DoPHITranslation(CurBB, PredBB); } + +protected: + unsigned short getSubclassDataFromValue() const { return SubclassData; } + void setValueSubclassData(unsigned short D) { SubclassData = D; } }; inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) { Modified: llvm/trunk/lib/VMCore/Constants.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Constants.cpp?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Constants.cpp (original) +++ llvm/trunk/lib/VMCore/Constants.cpp Mon Dec 28 20:14:09 2009 @@ -763,14 +763,14 @@ ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size()); Ops[OpNo-1] = Op; return cast(this)->isInBounds() ? - ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0], Ops.size()) : + ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()): ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size()); } default: assert(getNumOperands() == 2 && "Must be binary operator?"); Op0 = (OpNo == 0) ? Op : getOperand(0); Op1 = (OpNo == 1) ? Op : getOperand(1); - return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassData); + return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData); } } @@ -820,7 +820,7 @@ return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]); default: assert(getNumOperands() == 2 && "Must be binary operator?"); - return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassData); + return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData); } } @@ -2196,7 +2196,7 @@ Constant *C2 = getOperand(1); if (C1 == From) C1 = To; if (C2 == From) C2 = To; - Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassData); + Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData); } else { llvm_unreachable("Unknown ConstantExpr type!"); return; Modified: llvm/trunk/lib/VMCore/Function.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Function.cpp?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Function.cpp (original) +++ llvm/trunk/lib/VMCore/Function.cpp Mon Dec 28 20:14:09 2009 @@ -160,7 +160,7 @@ // If the function has arguments, mark them as lazily built. if (Ty->getNumParams()) - SubclassData = 1; // Set the "has lazy arguments" bit. + setValueSubclassData(1); // Set the "has lazy arguments" bit. // Make sure that we get added to a function LeakDetector::addGarbageObject(this); @@ -195,7 +195,8 @@ } // Clear the lazy arguments bit. - const_cast(this)->SubclassData &= ~1; + unsigned SDC = getSubclassDataFromValue(); + const_cast(this)->setValueSubclassData(SDC &= ~1); } size_t Function::arg_size() const { Modified: llvm/trunk/lib/VMCore/Instructions.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Instructions.cpp?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Instructions.cpp (original) +++ llvm/trunk/lib/VMCore/Instructions.cpp Mon Dec 28 20:14:09 2009 @@ -413,7 +413,9 @@ OperandTraits::op_end(this) - CI.getNumOperands(), CI.getNumOperands()) { setAttributes(CI.getAttributes()); - SubclassData = CI.SubclassData; + setTailCall(CI.isTailCall()); + setCallingConv(CI.getCallingConv()); + Use *OL = OperandList; Use *InOL = CI.OperandList; for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i) @@ -637,7 +639,7 @@ - II.getNumOperands(), II.getNumOperands()) { setAttributes(II.getAttributes()); - SubclassData = II.SubclassData; + setCallingConv(II.getCallingConv()); Use *OL = OperandList, *InOL = II.OperandList; for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i) OL[i] = InOL[i]; @@ -957,7 +959,7 @@ void AllocaInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); - SubclassData = Log2_32(Align) + 1; + setValueSubclassData(Log2_32(Align) + 1); assert(getAlignment() == Align && "Alignment representation error!"); } @@ -1092,7 +1094,8 @@ void LoadInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); - SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1); + setValueSubclassData((getSubclassDataFromValue() & 1) | + ((Log2_32(Align)+1)<<1)); } //===----------------------------------------------------------------------===// @@ -1187,7 +1190,8 @@ void StoreInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); - SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1); + setValueSubclassData((getSubclassDataFromValue() & 1) | + ((Log2_32(Align)+1) << 1)); } //===----------------------------------------------------------------------===// @@ -2720,7 +2724,7 @@ InsertBefore) { Op<0>() = LHS; Op<1>() = RHS; - SubclassData = predicate; + setPredicate((Predicate)predicate); setName(Name); } @@ -2733,7 +2737,7 @@ InsertAtEnd) { Op<0>() = LHS; Op<1>() = RHS; - SubclassData = predicate; + setPredicate((Predicate)predicate); setName(Name); } Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92239&r1=92238&r2=92239&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 20:14:09 2009 @@ -103,7 +103,7 @@ Operands[i].set(Vals[i], this); if (isFunctionLocal) - SubclassData |= FunctionLocalBit; + setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit); } MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals, From sabre at nondot.org Mon Dec 28 20:46:09 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 02:46:09 -0000 Subject: [llvm-commits] [llvm] r92240 - in /llvm/trunk: include/llvm/InstrTypes.h include/llvm/Instruction.h include/llvm/Instructions.h lib/VMCore/Instruction.cpp lib/VMCore/Instructions.cpp lib/VMCore/Metadata.cpp Message-ID: <200912290246.nBT2k9kx021422@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 20:46:09 2009 New Revision: 92240 URL: http://llvm.org/viewvc/llvm-project?rev=92240&view=rev Log: sink the Instruction::HasMetadata bit into SubclassData. Modified: llvm/trunk/include/llvm/InstrTypes.h llvm/trunk/include/llvm/Instruction.h llvm/trunk/include/llvm/Instructions.h llvm/trunk/lib/VMCore/Instruction.cpp llvm/trunk/lib/VMCore/Instructions.cpp llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/InstrTypes.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/InstrTypes.h?rev=92240&r1=92239&r2=92240&view=diff ============================================================================== --- llvm/trunk/include/llvm/InstrTypes.h (original) +++ llvm/trunk/include/llvm/InstrTypes.h Mon Dec 28 20:46:09 2009 @@ -733,11 +733,11 @@ /// @brief Return the predicate for this instruction. Predicate getPredicate() const { - return Predicate(getSubclassDataFromValue()); + return Predicate(getSubclassDataFromInstruction()); } /// @brief Set the predicate for this instruction to the specified value. - void setPredicate(Predicate P) { setValueSubclassData(P); } + void setPredicate(Predicate P) { setInstructionSubclassData(P); } static bool isFPPredicate(Predicate P) { return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE; Modified: llvm/trunk/include/llvm/Instruction.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Instruction.h?rev=92240&r1=92239&r2=92240&view=diff ============================================================================== --- llvm/trunk/include/llvm/Instruction.h (original) +++ llvm/trunk/include/llvm/Instruction.h Mon Dec 28 20:46:09 2009 @@ -33,18 +33,11 @@ BasicBlock *Parent; - // FIXME: Bitfieldize this. - bool HasMetadata; - friend class MetadataContextImpl; - - friend class SymbolTableListTraits; - void setParent(BasicBlock *P); -protected: - Instruction(const Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, - Instruction *InsertBefore = 0); - Instruction(const Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, - BasicBlock *InsertAtEnd); - virtual Instruction *clone_impl() const = 0; + enum { + /// HasMetadataBit - This is a bit stored in the SubClassData field which + /// indicates whether this instruction has metadata attached to it or not. + HasMetadataBit = 1 << 15 + }; public: // Out of line virtual method, so the vtable, etc has a home. ~Instruction(); @@ -131,7 +124,7 @@ /// hasMetadata() - Return true if this instruction has any metadata attached /// to it. bool hasMetadata() const { - return HasMetadata; + return (getSubclassDataFromValue() & HasMetadataBit) != 0; } /// getMetadata - Get the metadata of given kind attached to this Instruction. @@ -312,6 +305,44 @@ #define LAST_OTHER_INST(N) OtherOpsEnd = N+1 #include "llvm/Instruction.def" }; +private: + // Shadow Value::setValueSubclassData with a private forwarding method so that + // subclasses cannot accidentally use it. + void setValueSubclassData(unsigned short D) { + Value::setValueSubclassData(D); + } + unsigned short getSubclassDataFromValue() const { + return Value::getSubclassDataFromValue(); + } + + friend class MetadataContextImpl; + void setHasMetadata(bool V) { + setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) | + (V ? HasMetadataBit : 0)); + } + + friend class SymbolTableListTraits; + void setParent(BasicBlock *P); +protected: + // Instruction subclasses can stick up to 15 bits of stuff into the + // SubclassData field of instruction with these members. + + // Verify that only the low 15 bits are used. + void setInstructionSubclassData(unsigned short D) { + assert((D & HasMetadataBit) == 0 && "Out of range value put into field"); + setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D); + } + + unsigned getSubclassDataFromInstruction() const { + return getSubclassDataFromValue() & ~HasMetadataBit; + } + + Instruction(const Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, + Instruction *InsertBefore = 0); + Instruction(const Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, + BasicBlock *InsertAtEnd); + virtual Instruction *clone_impl() const = 0; + }; // Instruction* is only 4-byte aligned. Modified: llvm/trunk/include/llvm/Instructions.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Instructions.h?rev=92240&r1=92239&r2=92240&view=diff ============================================================================== --- llvm/trunk/include/llvm/Instructions.h (original) +++ llvm/trunk/include/llvm/Instructions.h Mon Dec 28 20:46:09 2009 @@ -83,7 +83,7 @@ /// by the instruction. /// unsigned getAlignment() const { - return (1u << getSubclassDataFromValue()) >> 1; + return (1u << getSubclassDataFromInstruction()) >> 1; } void setAlignment(unsigned Align); @@ -101,10 +101,10 @@ return isa(V) && classof(cast(V)); } private: - // Shadow Value::setValueSubclassData with a private forwarding method so that - // subclasses cannot accidentally use it. - void setValueSubclassData(unsigned short D) { - Value::setValueSubclassData(D); + // Shadow Instruction::setInstructionSubclassData with a private forwarding + // method so that subclasses cannot accidentally use it. + void setInstructionSubclassData(unsigned short D) { + Instruction::setInstructionSubclassData(D); } }; @@ -142,18 +142,19 @@ /// isVolatile - Return true if this is a load from a volatile memory /// location. /// - bool isVolatile() const { return getSubclassDataFromValue() & 1; } + bool isVolatile() const { return getSubclassDataFromInstruction() & 1; } /// setVolatile - Specify whether this is a volatile load or not. /// void setVolatile(bool V) { - setValueSubclassData((getSubclassDataFromValue() & ~1) | (V ? 1 : 0)); + setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | + (V ? 1 : 0)); } /// getAlignment - Return the alignment of the access that is being performed /// unsigned getAlignment() const { - return (1 << (getSubclassDataFromValue() >> 1)) >> 1; + return (1 << (getSubclassDataFromInstruction() >> 1)) >> 1; } void setAlignment(unsigned Align); @@ -176,10 +177,10 @@ return isa(V) && classof(cast(V)); } private: - // Shadow Value::setValueSubclassData with a private forwarding method so that - // subclasses cannot accidentally use it. - void setValueSubclassData(unsigned short D) { - Value::setValueSubclassData(D); + // Shadow Instruction::setInstructionSubclassData with a private forwarding + // method so that subclasses cannot accidentally use it. + void setInstructionSubclassData(unsigned short D) { + Instruction::setInstructionSubclassData(D); } }; @@ -214,12 +215,13 @@ /// isVolatile - Return true if this is a load from a volatile memory /// location. /// - bool isVolatile() const { return getSubclassDataFromValue() & 1; } + bool isVolatile() const { return getSubclassDataFromInstruction() & 1; } /// setVolatile - Specify whether this is a volatile load or not. /// void setVolatile(bool V) { - setValueSubclassData((getSubclassDataFromValue() & ~1) | (V ? 1 : 0)); + setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | + (V ? 1 : 0)); } /// Transparently provide more efficient getOperand methods. @@ -228,7 +230,7 @@ /// getAlignment - Return the alignment of the access that is being performed /// unsigned getAlignment() const { - return (1 << (getSubclassDataFromValue() >> 1)) >> 1; + return (1 << (getSubclassDataFromInstruction() >> 1)) >> 1; } void setAlignment(unsigned Align); @@ -250,10 +252,10 @@ return isa(V) && classof(cast(V)); } private: - // Shadow Value::setValueSubclassData with a private forwarding method so that - // subclasses cannot accidentally use it. - void setValueSubclassData(unsigned short D) { - Value::setValueSubclassData(D); + // Shadow Instruction::setInstructionSubclassData with a private forwarding + // method so that subclasses cannot accidentally use it. + void setInstructionSubclassData(unsigned short D) { + Instruction::setInstructionSubclassData(D); } }; @@ -929,9 +931,10 @@ ~CallInst(); - bool isTailCall() const { return getSubclassDataFromValue() & 1; } + bool isTailCall() const { return getSubclassDataFromInstruction() & 1; } void setTailCall(bool isTC = true) { - setValueSubclassData((getSubclassDataFromValue() & ~1) | unsigned(isTC)); + setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | + unsigned(isTC)); } /// Provide fast operand accessors @@ -940,11 +943,11 @@ /// getCallingConv/setCallingConv - Get or set the calling convention of this /// function call. CallingConv::ID getCallingConv() const { - return static_cast(getSubclassDataFromValue() >> 1); + return static_cast(getSubclassDataFromInstruction() >> 1); } void setCallingConv(CallingConv::ID CC) { - setValueSubclassData((getSubclassDataFromValue() & 1) | - (static_cast(CC) << 1)); + setInstructionSubclassData((getSubclassDataFromInstruction() & 1) | + (static_cast(CC) << 1)); } /// getAttributes - Return the parameter attributes for this call. @@ -1043,10 +1046,10 @@ return isa(V) && classof(cast(V)); } private: - // Shadow Value::setValueSubclassData with a private forwarding method so that - // subclasses cannot accidentally use it. - void setValueSubclassData(unsigned short D) { - Value::setValueSubclassData(D); + // Shadow Instruction::setInstructionSubclassData with a private forwarding + // method so that subclasses cannot accidentally use it. + void setInstructionSubclassData(unsigned short D) { + Instruction::setInstructionSubclassData(D); } }; @@ -2425,10 +2428,10 @@ /// getCallingConv/setCallingConv - Get or set the calling convention of this /// function call. CallingConv::ID getCallingConv() const { - return static_cast(getSubclassDataFromValue()); + return static_cast(getSubclassDataFromInstruction()); } void setCallingConv(CallingConv::ID CC) { - setValueSubclassData(static_cast(CC)); + setInstructionSubclassData(static_cast(CC)); } /// getAttributes - Return the parameter attributes for this invoke. @@ -2553,10 +2556,10 @@ virtual unsigned getNumSuccessorsV() const; virtual void setSuccessorV(unsigned idx, BasicBlock *B); - // Shadow Value::setValueSubclassData with a private forwarding method so that - // subclasses cannot accidentally use it. - void setValueSubclassData(unsigned short D) { - Value::setValueSubclassData(D); + // Shadow Instruction::setInstructionSubclassData with a private forwarding + // method so that subclasses cannot accidentally use it. + void setInstructionSubclassData(unsigned short D) { + Instruction::setInstructionSubclassData(D); } }; Modified: llvm/trunk/lib/VMCore/Instruction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Instruction.cpp?rev=92240&r1=92239&r2=92240&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Instruction.cpp (original) +++ llvm/trunk/lib/VMCore/Instruction.cpp Mon Dec 28 20:46:09 2009 @@ -24,8 +24,7 @@ Instruction::Instruction(const Type *ty, unsigned it, Use *Ops, unsigned NumOps, Instruction *InsertBefore) - : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0), - HasMetadata(false) { + : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0) { // Make sure that we get added to a basicblock LeakDetector::addGarbageObject(this); @@ -39,8 +38,7 @@ Instruction::Instruction(const Type *ty, unsigned it, Use *Ops, unsigned NumOps, BasicBlock *InsertAtEnd) - : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0), - HasMetadata(false) { + : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0) { // Make sure that we get added to a basicblock LeakDetector::addGarbageObject(this); @@ -53,7 +51,7 @@ // Out of line virtual method, so the vtable, etc has a home. Instruction::~Instruction() { assert(Parent == 0 && "Instruction still linked in the program!"); - if (HasMetadata) + if (hasMetadata()) getContext().pImpl->TheMetadata.ValueIsDeleted(this); } @@ -464,7 +462,7 @@ Instruction *Instruction::clone() const { Instruction *New = clone_impl(); New->SubclassOptionalData = SubclassOptionalData; - if (HasMetadata) + if (hasMetadata()) getContext().pImpl->TheMetadata.ValueIsCloned(this, New); return New; } Modified: llvm/trunk/lib/VMCore/Instructions.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Instructions.cpp?rev=92240&r1=92239&r2=92240&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Instructions.cpp (original) +++ llvm/trunk/lib/VMCore/Instructions.cpp Mon Dec 28 20:46:09 2009 @@ -959,7 +959,7 @@ void AllocaInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); - setValueSubclassData(Log2_32(Align) + 1); + setInstructionSubclassData(Log2_32(Align) + 1); assert(getAlignment() == Align && "Alignment representation error!"); } @@ -1094,8 +1094,8 @@ void LoadInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); - setValueSubclassData((getSubclassDataFromValue() & 1) | - ((Log2_32(Align)+1)<<1)); + setInstructionSubclassData((getSubclassDataFromInstruction() & 1) | + ((Log2_32(Align)+1)<<1)); } //===----------------------------------------------------------------------===// @@ -1190,8 +1190,8 @@ void StoreInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); - setValueSubclassData((getSubclassDataFromValue() & 1) | - ((Log2_32(Align)+1) << 1)); + setInstructionSubclassData((getSubclassDataFromInstruction() & 1) | + ((Log2_32(Align)+1) << 1)); } //===----------------------------------------------------------------------===// Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92240&r1=92239&r2=92240&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 20:46:09 2009 @@ -355,9 +355,9 @@ // Handle the case when we're adding/updating metadata on an instruction. if (Node) { MDMapTy &Info = MetadataStore[Inst]; - assert(!Info.empty() == Inst->HasMetadata && "HasMetadata bit is wonked"); + assert(!Info.empty() == Inst->hasMetadata() && "HasMetadata bit is wonked"); if (Info.empty()) { - Inst->HasMetadata = true; + Inst->setHasMetadata(true); } else { // Handle replacement of an existing value. for (unsigned i = 0, e = Info.size(); i != e; ++i) @@ -373,14 +373,14 @@ } // Otherwise, we're removing metadata from an instruction. - assert(Inst->HasMetadata && MetadataStore.count(Inst) && + assert(Inst->hasMetadata() && MetadataStore.count(Inst) && "HasMetadata bit out of date!"); MDMapTy &Info = MetadataStore[Inst]; // Common case is removing the only entry. if (Info.size() == 1 && Info[0].first == Kind) { MetadataStore.erase(Inst); - Inst->HasMetadata = false; + Inst->setHasMetadata(false); return; } @@ -398,7 +398,7 @@ /// removeAllMetadata - Remove all metadata attached with an instruction. void MetadataContextImpl::removeAllMetadata(Instruction *Inst) { MetadataStore.erase(Inst); - Inst->HasMetadata = false; + Inst->setHasMetadata(false); } From sabre at nondot.org Mon Dec 28 20:53:52 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 02:53:52 -0000 Subject: [llvm-commits] [llvm] r92241 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp lib/VMCore/Value.cpp Message-ID: <200912290253.nBT2rqft021698@zion.cs.uiuc.edu> Author: lattner Date: Mon Dec 28 20:53:52 2009 New Revision: 92241 URL: http://llvm.org/viewvc/llvm-project?rev=92241&view=rev Log: When doing v1->RAUW(v2), don't do anything to metadata. We don't know why one was replaced with the other. Even in the specific case of debug information, it doesn't make sense to transfer the location over, this will just result in jumbled loc info. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Metadata.cpp llvm/trunk/lib/VMCore/Value.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92241&r1=92240&r2=92241&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Mon Dec 28 20:53:52 2009 @@ -234,9 +234,7 @@ /// ValueIsDeleted - This handler is used to update metadata store /// when a value is deleted. - void ValueIsDeleted(const Value *) {} void ValueIsDeleted(Instruction *Inst); - void ValueIsRAUWd(Value *V1, Value *V2); /// ValueIsCloned - This handler is used to update metadata store /// when In1 is cloned to create In2. Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92241&r1=92240&r2=92241&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Mon Dec 28 20:53:52 2009 @@ -289,7 +289,6 @@ void ValueIsDeleted(Instruction *Inst) { removeAllMetadata(Inst); } - void ValueIsRAUWd(Value *V1, Value *V2); /// ValueIsCloned - This handler is used to update metadata store /// when In1 is cloned to create In2. @@ -428,18 +427,6 @@ In2->setMetadata(I->first, I->second); } -/// ValueIsRAUWd - This handler is used when V1's all uses are replaced by -/// V2. -void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) { - Instruction *I1 = dyn_cast(V1); - Instruction *I2 = dyn_cast(V2); - if (!I1 || !I2) - return; - - // FIXME: Give custom handlers a chance to override this. - ValueIsCloned(I1, I2); -} - //===----------------------------------------------------------------------===// // MetadataContext implementation. // @@ -484,9 +471,6 @@ void MetadataContext::ValueIsDeleted(Instruction *Inst) { pImpl->ValueIsDeleted(Inst); } -void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) { - pImpl->ValueIsRAUWd(V1, V2); -} /// ValueIsCloned - This handler is used to update metadata store /// when In1 is cloned to create In2. Modified: llvm/trunk/lib/VMCore/Value.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Value.cpp?rev=92241&r1=92240&r2=92241&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Value.cpp (original) +++ llvm/trunk/lib/VMCore/Value.cpp Mon Dec 28 20:53:52 2009 @@ -19,7 +19,6 @@ #include "llvm/Instructions.h" #include "llvm/Operator.h" #include "llvm/Module.h" -#include "llvm/Metadata.h" #include "llvm/ValueSymbolTable.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Debug.h" @@ -302,14 +301,6 @@ if (HasValueHandle) ValueHandleBase::ValueIsRAUWd(this, New); - // FIXME: It doesn't make sense at all for metadata to follow RAUW. - if (Instruction *I = dyn_cast(this)) - if (I->hasMetadata()) { - LLVMContext &Context = getContext(); - // FIXME: NUKE ValueIsRAUWd?? - Context.pImpl->TheMetadata.ValueIsRAUWd(this, New); - } - while (!use_empty()) { Use &U = *UseList; // Must handle Constants specially, we cannot call replaceUsesOfWith on a From sanjiv.gupta at microchip.com Mon Dec 28 21:24:34 2009 From: sanjiv.gupta at microchip.com (Sanjiv Gupta) Date: Tue, 29 Dec 2009 03:24:34 -0000 Subject: [llvm-commits] [llvm] r92242 - in /llvm/trunk: lib/Target/PIC16/PIC16ISelLowering.cpp test/CodeGen/PIC16/C16-15.ll Message-ID: <200912290324.nBT3OYVD022529@zion.cs.uiuc.edu> Author: sgupta Date: Mon Dec 28 21:24:34 2009 New Revision: 92242 URL: http://llvm.org/viewvc/llvm-project?rev=92242&view=rev Log: Extern declaration for unordered.f32 libcall was not being emitted. Fixed that. Added: llvm/trunk/test/CodeGen/PIC16/C16-15.ll Modified: llvm/trunk/lib/Target/PIC16/PIC16ISelLowering.cpp Modified: llvm/trunk/lib/Target/PIC16/PIC16ISelLowering.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/PIC16/PIC16ISelLowering.cpp?rev=92242&r1=92241&r2=92242&view=diff ============================================================================== --- llvm/trunk/lib/Target/PIC16/PIC16ISelLowering.cpp (original) +++ llvm/trunk/lib/Target/PIC16/PIC16ISelLowering.cpp Mon Dec 28 21:24:34 2009 @@ -226,6 +226,7 @@ setLibcallName(RTLIB::DIV_F32, getIntrinsicName(RTLIB::DIV_F32)); // Floationg point comparison + setLibcallName(RTLIB::O_F32, getIntrinsicName(RTLIB::O_F32)); setLibcallName(RTLIB::UO_F32, getIntrinsicName(RTLIB::UO_F32)); setLibcallName(RTLIB::OLE_F32, getIntrinsicName(RTLIB::OLE_F32)); setLibcallName(RTLIB::OGE_F32, getIntrinsicName(RTLIB::OGE_F32)); Added: llvm/trunk/test/CodeGen/PIC16/C16-15.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/PIC16/C16-15.ll?rev=92242&view=auto ============================================================================== --- llvm/trunk/test/CodeGen/PIC16/C16-15.ll (added) +++ llvm/trunk/test/CodeGen/PIC16/C16-15.ll Mon Dec 28 21:24:34 2009 @@ -0,0 +1,44 @@ +; RUN: llc < %s -march=pic16 | grep "extern @.lib.unordered.f32" | count 3 + + at pc = global i8* inttoptr (i64 160 to i8*), align 1 ; [#uses=2] + at aa = common global i16 0, align 1 ; [#uses=0] + at c6214.auto.d = internal global float 0.000000e+00, align 4 ; [#uses=1] + at c6214.auto.l = internal global float 0.000000e+00, align 4 ; [#uses=1] + +define float @dvalue(float %f) nounwind { +entry: + ret float %f +} + +define void @_assert(i16 %line, i16 %result) nounwind { +entry: + %add = add i16 %line, %result ; [#uses=1] + %conv = trunc i16 %add to i8 ; [#uses=1] + %tmp2 = load i8** @pc ; [#uses=1] + store i8 %conv, i8* %tmp2 + ret void +} + +define i16 @main() nounwind { +entry: + %retval = alloca i16, align 1 ; [#uses=2] + store i16 0, i16* %retval + call void @c6214() + %0 = load i16* %retval ; [#uses=1] + ret i16 %0 +} + +define internal void @c6214() nounwind { +entry: + %call = call float @dvalue(float 0x3FF3C0CA40000000) ; [#uses=3] + store float %call, float* @c6214.auto.d + store float %call, float* @c6214.auto.l + %cmp = fcmp ord float %call, 0.000000e+00 ; [#uses=1] + %conv = zext i1 %cmp to i16 ; [#uses=1] + call void @_assert(i16 10, i16 %conv) + %tmp3 = load i8** @pc ; [#uses=2] + %tmp4 = load i8* %tmp3 ; [#uses=1] + %sub = add i8 %tmp4, -10 ; [#uses=1] + store i8 %sub, i8* %tmp3 + ret void +} From daniel at zuster.org Mon Dec 28 22:29:41 2009 From: daniel at zuster.org (Daniel Dunbar) Date: Tue, 29 Dec 2009 04:29:41 -0000 Subject: [llvm-commits] [test-suite] r92243 - /test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/data/hyph/english.lp Message-ID: <200912290429.nBT4Tg4W024479@zion.cs.uiuc.edu> Author: ddunbar Date: Mon Dec 28 22:29:38 2009 New Revision: 92243 URL: http://llvm.org/viewvc/llvm-project?rev=92243&view=rev Log: Remove a temp file which shouldn't be in the repo. Removed: test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/data/hyph/english.lp Removed: test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/data/hyph/english.lp URL: http://llvm.org/viewvc/llvm-project/test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/data/hyph/english.lp?rev=92242&view=auto ============================================================================== Binary files test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/data/hyph/english.lp (original) and test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/data/hyph/english.lp (removed) differ From daniel at zuster.org Mon Dec 28 22:30:02 2009 From: daniel at zuster.org (Daniel Dunbar) Date: Tue, 29 Dec 2009 04:30:02 -0000 Subject: [llvm-commits] [test-suite] r92244 - in /test-suite/trunk/MultiSource: Applications/JM/ldecod/Makefile Applications/JM/lencod/Makefile Applications/kimwitu++/Makefile Benchmarks/MiBench/consumer-typeset/Makefile Benchmarks/mafft/Makefile Benchmarks/mediabench/mpeg2/mpeg2dec/Makefile Message-ID: <200912290430.nBT4U2BZ024508@zion.cs.uiuc.edu> Author: ddunbar Date: Mon Dec 28 22:30:01 2009 New Revision: 92244 URL: http://llvm.org/viewvc/llvm-project?rev=92244&view=rev Log: Update Makefiles to clean up temp files. Modified: test-suite/trunk/MultiSource/Applications/JM/ldecod/Makefile test-suite/trunk/MultiSource/Applications/JM/lencod/Makefile test-suite/trunk/MultiSource/Applications/kimwitu++/Makefile test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/Makefile test-suite/trunk/MultiSource/Benchmarks/mafft/Makefile test-suite/trunk/MultiSource/Benchmarks/mediabench/mpeg2/mpeg2dec/Makefile Modified: test-suite/trunk/MultiSource/Applications/JM/ldecod/Makefile URL: http://llvm.org/viewvc/llvm-project/test-suite/trunk/MultiSource/Applications/JM/ldecod/Makefile?rev=92244&r1=92243&r2=92244&view=diff ============================================================================== --- test-suite/trunk/MultiSource/Applications/JM/ldecod/Makefile (original) +++ test-suite/trunk/MultiSource/Applications/JM/ldecod/Makefile Mon Dec 28 22:30:01 2009 @@ -6,3 +6,6 @@ RUN_OPTIONS = -i $(PROJ_SRC_DIR)/data/test.264 -o Output/test_dec.yuv -r $(PROJ_SRC_DIR)/data/test_rec.yuv include ../../../Makefile.multisrc + +clean:: + rm -f dataDec.txt log.dec Modified: test-suite/trunk/MultiSource/Applications/JM/lencod/Makefile URL: http://llvm.org/viewvc/llvm-project/test-suite/trunk/MultiSource/Applications/JM/lencod/Makefile?rev=92244&r1=92243&r2=92244&view=diff ============================================================================== --- test-suite/trunk/MultiSource/Applications/JM/lencod/Makefile (original) +++ test-suite/trunk/MultiSource/Applications/JM/lencod/Makefile Mon Dec 28 22:30:01 2009 @@ -11,3 +11,6 @@ endif include ../../../Makefile.multisrc + +clean:: + rm -f data.txt log.dat stats.dat Modified: test-suite/trunk/MultiSource/Applications/kimwitu++/Makefile URL: http://llvm.org/viewvc/llvm-project/test-suite/trunk/MultiSource/Applications/kimwitu%2B%2B/Makefile?rev=92244&r1=92243&r2=92244&view=diff ============================================================================== --- test-suite/trunk/MultiSource/Applications/kimwitu++/Makefile (original) +++ test-suite/trunk/MultiSource/Applications/kimwitu++/Makefile Mon Dec 28 22:30:01 2009 @@ -6,3 +6,5 @@ RUN_OPTIONS = -f test -o -v -s kcc $(PROJ_SRC_DIR)/inputs/f3.k $(PROJ_SRC_DIR)/inputs/f2.k $(PROJ_SRC_DIR)/inputs/f1.k include ../../Makefile.multisrc +clean:: + rm -f *.kcc f1.h f2.h f3.h test*.h Modified: test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/Makefile URL: http://llvm.org/viewvc/llvm-project/test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/Makefile?rev=92244&r1=92243&r2=92244&view=diff ============================================================================== --- test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/Makefile (original) +++ test-suite/trunk/MultiSource/Benchmarks/MiBench/consumer-typeset/Makefile Mon Dec 28 22:30:01 2009 @@ -5,3 +5,6 @@ LDFLAGS = -lm RUN_OPTIONS = -x -I $(PROJ_SRC_DIR)/data/include -D $(PROJ_SRC_DIR)/data/data -F $(PROJ_SRC_DIR)/data/font -C $(PROJ_SRC_DIR)/data/maps -H $(PROJ_SRC_DIR)/data/hyph $(PROJ_SRC_DIR)/large.lout include $(LEVEL)/MultiSource/Makefile.multisrc + +clean:: + rm -f $(PROJ_SRC_DIR)/data/hyph/*.lp Modified: test-suite/trunk/MultiSource/Benchmarks/mafft/Makefile URL: http://llvm.org/viewvc/llvm-project/test-suite/trunk/MultiSource/Benchmarks/mafft/Makefile?rev=92244&r1=92243&r2=92244&view=diff ============================================================================== --- test-suite/trunk/MultiSource/Benchmarks/mafft/Makefile (original) +++ test-suite/trunk/MultiSource/Benchmarks/mafft/Makefile Mon Dec 28 22:30:01 2009 @@ -12,3 +12,6 @@ LDFLAGS = -lm FP_TOLERANCE = 0.00001 include $(LEVEL)/MultiSource/Makefile.multisrc + +clean:: + rm -f pre hat2 trace Modified: test-suite/trunk/MultiSource/Benchmarks/mediabench/mpeg2/mpeg2dec/Makefile URL: http://llvm.org/viewvc/llvm-project/test-suite/trunk/MultiSource/Benchmarks/mediabench/mpeg2/mpeg2dec/Makefile?rev=92244&r1=92243&r2=92244&view=diff ============================================================================== --- test-suite/trunk/MultiSource/Benchmarks/mediabench/mpeg2/mpeg2dec/Makefile (original) +++ test-suite/trunk/MultiSource/Benchmarks/mediabench/mpeg2/mpeg2dec/Makefile Mon Dec 28 22:30:01 2009 @@ -12,5 +12,5 @@ include $(LEVEL)/MultiSource/Makefile.multisrc - - +clean:: + rm -f $(SourceDir)/../data/tmp* From sabre at nondot.org Tue Dec 29 01:12:53 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 07:12:53 -0000 Subject: [llvm-commits] [llvm] r92247 - in /llvm/trunk/include/llvm: Argument.h BasicBlock.h GlobalAlias.h GlobalValue.h GlobalVariable.h InstrTypes.h Value.h Message-ID: <200912290713.nBT7D8RX029329@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 01:12:03 2009 New Revision: 92247 URL: http://llvm.org/viewvc/llvm-project?rev=92247&view=rev Log: sink twine.h down out of Value.h. It is annoying that you need to #include Twine.h just to give a twine a default value. Modified: llvm/trunk/include/llvm/Argument.h llvm/trunk/include/llvm/BasicBlock.h llvm/trunk/include/llvm/GlobalAlias.h llvm/trunk/include/llvm/GlobalValue.h llvm/trunk/include/llvm/GlobalVariable.h llvm/trunk/include/llvm/InstrTypes.h llvm/trunk/include/llvm/Value.h Modified: llvm/trunk/include/llvm/Argument.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Argument.h?rev=92247&r1=92246&r2=92247&view=diff ============================================================================== --- llvm/trunk/include/llvm/Argument.h (original) +++ llvm/trunk/include/llvm/Argument.h Tue Dec 29 01:12:03 2009 @@ -17,6 +17,7 @@ #include "llvm/Value.h" #include "llvm/Attributes.h" #include "llvm/ADT/ilist_node.h" +#include "llvm/ADT/Twine.h" namespace llvm { Modified: llvm/trunk/include/llvm/BasicBlock.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/BasicBlock.h?rev=92247&r1=92246&r2=92247&view=diff ============================================================================== --- llvm/trunk/include/llvm/BasicBlock.h (original) +++ llvm/trunk/include/llvm/BasicBlock.h Tue Dec 29 01:12:03 2009 @@ -17,6 +17,7 @@ #include "llvm/Instruction.h" #include "llvm/SymbolTableListTraits.h" #include "llvm/ADT/ilist.h" +#include "llvm/ADT/Twine.h" #include "llvm/System/DataTypes.h" namespace llvm { Modified: llvm/trunk/include/llvm/GlobalAlias.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/GlobalAlias.h?rev=92247&r1=92246&r2=92247&view=diff ============================================================================== --- llvm/trunk/include/llvm/GlobalAlias.h (original) +++ llvm/trunk/include/llvm/GlobalAlias.h Tue Dec 29 01:12:03 2009 @@ -18,6 +18,7 @@ #include "llvm/GlobalValue.h" #include "llvm/OperandTraits.h" #include "llvm/ADT/ilist_node.h" +#include "llvm/ADT/Twine.h" namespace llvm { Modified: llvm/trunk/include/llvm/GlobalValue.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/GlobalValue.h?rev=92247&r1=92246&r2=92247&view=diff ============================================================================== --- llvm/trunk/include/llvm/GlobalValue.h (original) +++ llvm/trunk/include/llvm/GlobalValue.h Tue Dec 29 01:12:03 2009 @@ -56,7 +56,7 @@ protected: GlobalValue(const Type *ty, ValueTy vty, Use *Ops, unsigned NumOps, - LinkageTypes linkage, const Twine &Name = "") + LinkageTypes linkage, const Twine &Name) : Constant(ty, vty, Ops, NumOps), Parent(0), Linkage(linkage), Visibility(DefaultVisibility), Alignment(0) { setName(Name); Modified: llvm/trunk/include/llvm/GlobalVariable.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/GlobalVariable.h?rev=92247&r1=92246&r2=92247&view=diff ============================================================================== --- llvm/trunk/include/llvm/GlobalVariable.h (original) +++ llvm/trunk/include/llvm/GlobalVariable.h Tue Dec 29 01:12:03 2009 @@ -23,6 +23,7 @@ #include "llvm/GlobalValue.h" #include "llvm/OperandTraits.h" #include "llvm/ADT/ilist_node.h" +#include "llvm/ADT/Twine.h" namespace llvm { Modified: llvm/trunk/include/llvm/InstrTypes.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/InstrTypes.h?rev=92247&r1=92246&r2=92247&view=diff ============================================================================== --- llvm/trunk/include/llvm/InstrTypes.h (original) +++ llvm/trunk/include/llvm/InstrTypes.h Tue Dec 29 01:12:03 2009 @@ -20,6 +20,7 @@ #include "llvm/OperandTraits.h" #include "llvm/Operator.h" #include "llvm/DerivedTypes.h" +#include "llvm/ADT/Twine.h" namespace llvm { @@ -160,7 +161,7 @@ /// Instruction is allowed to be a dereferenced end iterator. /// static BinaryOperator *Create(BinaryOps Op, Value *S1, Value *S2, - const Twine &Name = "", + const Twine &Name = Twine(), Instruction *InsertBefore = 0); /// Create() - Construct a binary instruction, given the opcode and the two Modified: llvm/trunk/include/llvm/Value.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Value.h?rev=92247&r1=92246&r2=92247&view=diff ============================================================================== --- llvm/trunk/include/llvm/Value.h (original) +++ llvm/trunk/include/llvm/Value.h Tue Dec 29 01:12:03 2009 @@ -17,7 +17,6 @@ #include "llvm/AbstractTypeUser.h" #include "llvm/Use.h" #include "llvm/ADT/StringRef.h" -#include "llvm/ADT/Twine.h" #include "llvm/Support/Casting.h" #include @@ -43,6 +42,7 @@ class ValueHandleBase; class LLVMContext; class MetadataContextImpl; +class Twine; //===----------------------------------------------------------------------===// // Value Class From sabre at nondot.org Tue Dec 29 01:25:57 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 07:25:57 -0000 Subject: [llvm-commits] [llvm] r92249 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912290725.nBT7PwsQ029727@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 01:25:48 2009 New Revision: 92249 URL: http://llvm.org/viewvc/llvm-project?rev=92249&view=rev Log: tidy up debug info comments, use ->isVoidTy() where reasonable. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92249&r1=92248&r2=92249&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Tue Dec 29 01:25:48 2009 @@ -779,8 +779,7 @@ /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. void SlotTracker::CreateModuleSlot(const GlobalValue *V) { assert(V && "Can't insert a null Value into SlotTracker!"); - assert(V->getType() != Type::getVoidTy(V->getContext()) && - "Doesn't need a slot!"); + assert(!V->getType()->isVoidTy() && "Doesn't need a slot!"); assert(!V->hasName() && "Doesn't need a slot!"); unsigned DestSlot = mNext++; @@ -796,8 +795,7 @@ /// CreateSlot - Create a new slot for the specified value if it has no name. void SlotTracker::CreateFunctionSlot(const Value *V) { - assert(V->getType() != Type::getVoidTy(TheFunction->getContext()) && - !V->hasName() && "Doesn't need a slot!"); + assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!"); unsigned DestSlot = fNext++; fMap[V] = DestSlot; @@ -881,20 +879,22 @@ if (!CI) return; unsigned Val = CI->getZExtValue(); unsigned Tag = Val & ~LLVMDebugVersionMask; - if (Val >= LLVMDebugVersion) { - if (Tag == dwarf::DW_TAG_auto_variable) - Out << "; [ DW_TAG_auto_variable ]"; - else if (Tag == dwarf::DW_TAG_arg_variable) - Out << "; [ DW_TAG_arg_variable ]"; - else if (Tag == dwarf::DW_TAG_return_variable) - Out << "; [ DW_TAG_return_variable ]"; - else if (Tag == dwarf::DW_TAG_vector_type) - Out << "; [ DW_TAG_vector_type ]"; - else if (Tag == dwarf::DW_TAG_user_base) - Out << "; [ DW_TAG_user_base ]"; - else - Out << "; [" << dwarf::TagString(Tag) << " ]"; - } + if (Val < LLVMDebugVersion) + return; + + Out.PadToColumn(50); + if (Tag == dwarf::DW_TAG_auto_variable) + Out << "; [ DW_TAG_auto_variable ]"; + else if (Tag == dwarf::DW_TAG_arg_variable) + Out << "; [ DW_TAG_arg_variable ]"; + else if (Tag == dwarf::DW_TAG_return_variable) + Out << "; [ DW_TAG_return_variable ]"; + else if (Tag == dwarf::DW_TAG_vector_type) + Out << "; [ DW_TAG_vector_type ]"; + else if (Tag == dwarf::DW_TAG_user_base) + Out << "; [ DW_TAG_user_base ]"; + else + Out << "; [ " << dwarf::TagString(Tag) << " ]"; } static void WriteMDNodes(formatted_raw_ostream &Out, TypePrinting &TypePrinter, @@ -1795,12 +1795,12 @@ /// which slot it occupies. /// void AssemblyWriter::printInfoComment(const Value &V) { - if (V.getType() != Type::getVoidTy(V.getContext())) { - Out.PadToColumn(50); - Out << "; <"; - TypePrinter.print(V.getType(), Out); - Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses - } + if (V.getType()->isVoidTy()) return; + + Out.PadToColumn(50); + Out << "; <"; + TypePrinter.print(V.getType(), Out); + Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses } // This member is called for each Instruction in a function.. @@ -1814,7 +1814,7 @@ if (I.hasName()) { PrintLLVMName(Out, &I); Out << " = "; - } else if (I.getType() != Type::getVoidTy(I.getContext())) { + } else if (!I.getType()->isVoidTy()) { // Print out the def slot taken. int SlotNum = Machine.getLocalSlot(&I); if (SlotNum == -1) From sabre at nondot.org Tue Dec 29 01:28:34 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 07:28:34 -0000 Subject: [llvm-commits] [llvm] r92250 - /llvm/trunk/lib/Support/Dwarf.cpp Message-ID: <200912290728.nBT7SYdq029811@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 01:28:33 2009 New Revision: 92250 URL: http://llvm.org/viewvc/llvm-project?rev=92250&view=rev Log: fix .cpp file to not wrap the entire file in namespace blocks. Modified: llvm/trunk/lib/Support/Dwarf.cpp Modified: llvm/trunk/lib/Support/Dwarf.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Support/Dwarf.cpp?rev=92250&r1=92249&r2=92250&view=diff ============================================================================== --- llvm/trunk/lib/Support/Dwarf.cpp (original) +++ llvm/trunk/lib/Support/Dwarf.cpp Tue Dec 29 01:28:33 2009 @@ -13,16 +13,13 @@ #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" - #include - -namespace llvm { - -namespace dwarf { +using namespace llvm; +using namespace dwarf; /// TagString - Return the string for the specified tag. /// -const char *TagString(unsigned Tag) { +const char *llvm::dwarf::TagString(unsigned Tag) { switch (Tag) { case DW_TAG_array_type: return "DW_TAG_array_type"; case DW_TAG_class_type: return "DW_TAG_class_type"; @@ -90,7 +87,7 @@ /// ChildrenString - Return the string for the specified children flag. /// -const char *ChildrenString(unsigned Children) { +const char *llvm::dwarf::ChildrenString(unsigned Children) { switch (Children) { case DW_CHILDREN_no: return "CHILDREN_no"; case DW_CHILDREN_yes: return "CHILDREN_yes"; @@ -101,7 +98,7 @@ /// AttributeString - Return the string for the specified attribute. /// -const char *AttributeString(unsigned Attribute) { +const char *llvm::dwarf::AttributeString(unsigned Attribute) { switch (Attribute) { case DW_AT_sibling: return "DW_AT_sibling"; case DW_AT_location: return "DW_AT_location"; @@ -212,7 +209,7 @@ /// FormEncodingString - Return the string for the specified form encoding. /// -const char *FormEncodingString(unsigned Encoding) { +const char *llvm::dwarf::FormEncodingString(unsigned Encoding) { switch (Encoding) { case DW_FORM_addr: return "FORM_addr"; case DW_FORM_block2: return "FORM_block2"; @@ -242,7 +239,7 @@ /// OperationEncodingString - Return the string for the specified operation /// encoding. -const char *OperationEncodingString(unsigned Encoding) { +const char *llvm::dwarf::OperationEncodingString(unsigned Encoding) { switch (Encoding) { case DW_OP_addr: return "OP_addr"; case DW_OP_deref: return "OP_deref"; @@ -317,7 +314,7 @@ /// AttributeEncodingString - Return the string for the specified attribute /// encoding. -const char *AttributeEncodingString(unsigned Encoding) { +const char *llvm::dwarf::AttributeEncodingString(unsigned Encoding) { switch (Encoding) { case DW_ATE_address: return "ATE_address"; case DW_ATE_boolean: return "ATE_boolean"; @@ -343,7 +340,7 @@ /// DecimalSignString - Return the string for the specified decimal sign /// attribute. -const char *DecimalSignString(unsigned Sign) { +const char *llvm::dwarf::DecimalSignString(unsigned Sign) { switch (Sign) { case DW_DS_unsigned: return "DS_unsigned"; case DW_DS_leading_overpunch: return "DS_leading_overpunch"; @@ -357,7 +354,7 @@ /// EndianityString - Return the string for the specified endianity. /// -const char *EndianityString(unsigned Endian) { +const char *llvm::dwarf::EndianityString(unsigned Endian) { switch (Endian) { case DW_END_default: return "END_default"; case DW_END_big: return "END_big"; @@ -371,7 +368,7 @@ /// AccessibilityString - Return the string for the specified accessibility. /// -const char *AccessibilityString(unsigned Access) { +const char *llvm::dwarf::AccessibilityString(unsigned Access) { switch (Access) { // Accessibility codes case DW_ACCESS_public: return "ACCESS_public"; @@ -384,7 +381,7 @@ /// VisibilityString - Return the string for the specified visibility. /// -const char *VisibilityString(unsigned Visibility) { +const char *llvm::dwarf::VisibilityString(unsigned Visibility) { switch (Visibility) { case DW_VIS_local: return "VIS_local"; case DW_VIS_exported: return "VIS_exported"; @@ -396,7 +393,7 @@ /// VirtualityString - Return the string for the specified virtuality. /// -const char *VirtualityString(unsigned Virtuality) { +const char *llvm::dwarf::VirtualityString(unsigned Virtuality) { switch (Virtuality) { case DW_VIRTUALITY_none: return "VIRTUALITY_none"; case DW_VIRTUALITY_virtual: return "VIRTUALITY_virtual"; @@ -408,7 +405,7 @@ /// LanguageString - Return the string for the specified language. /// -const char *LanguageString(unsigned Language) { +const char *llvm::dwarf::LanguageString(unsigned Language) { switch (Language) { case DW_LANG_C89: return "LANG_C89"; case DW_LANG_C: return "LANG_C"; @@ -438,7 +435,7 @@ /// CaseString - Return the string for the specified identifier case. /// -const char *CaseString(unsigned Case) { +const char *llvm::dwarf::CaseString(unsigned Case) { switch (Case) { case DW_ID_case_sensitive: return "ID_case_sensitive"; case DW_ID_up_case: return "ID_up_case"; @@ -451,7 +448,7 @@ /// ConventionString - Return the string for the specified calling convention. /// -const char *ConventionString(unsigned Convention) { +const char *llvm::dwarf::ConventionString(unsigned Convention) { switch (Convention) { case DW_CC_normal: return "CC_normal"; case DW_CC_program: return "CC_program"; @@ -465,7 +462,7 @@ /// InlineCodeString - Return the string for the specified inline code. /// -const char *InlineCodeString(unsigned Code) { +const char *llvm::dwarf::InlineCodeString(unsigned Code) { switch (Code) { case DW_INL_not_inlined: return "INL_not_inlined"; case DW_INL_inlined: return "INL_inlined"; @@ -478,7 +475,7 @@ /// ArrayOrderString - Return the string for the specified array order. /// -const char *ArrayOrderString(unsigned Order) { +const char *llvm::dwarf::ArrayOrderString(unsigned Order) { switch (Order) { case DW_ORD_row_major: return "ORD_row_major"; case DW_ORD_col_major: return "ORD_col_major"; @@ -489,7 +486,7 @@ /// DiscriminantString - Return the string for the specified discriminant /// descriptor. -const char *DiscriminantString(unsigned Discriminant) { +const char *llvm::dwarf::DiscriminantString(unsigned Discriminant) { switch (Discriminant) { case DW_DSC_label: return "DSC_label"; case DW_DSC_range: return "DSC_range"; @@ -500,7 +497,7 @@ /// LNStandardString - Return the string for the specified line number standard. /// -const char *LNStandardString(unsigned Standard) { +const char *llvm::dwarf::LNStandardString(unsigned Standard) { switch (Standard) { case DW_LNS_copy: return "LNS_copy"; case DW_LNS_advance_pc: return "LNS_advance_pc"; @@ -521,7 +518,7 @@ /// LNExtendedString - Return the string for the specified line number extended /// opcode encodings. -const char *LNExtendedString(unsigned Encoding) { +const char *llvm::dwarf::LNExtendedString(unsigned Encoding) { switch (Encoding) { // Line Number Extended Opcode Encodings case DW_LNE_end_sequence: return "LNE_end_sequence"; @@ -536,7 +533,7 @@ /// MacinfoString - Return the string for the specified macinfo type encodings. /// -const char *MacinfoString(unsigned Encoding) { +const char *llvm::dwarf::MacinfoString(unsigned Encoding) { switch (Encoding) { // Macinfo Type Encodings case DW_MACINFO_define: return "MACINFO_define"; @@ -551,7 +548,7 @@ /// CallFrameString - Return the string for the specified call frame instruction /// encodings. -const char *CallFrameString(unsigned Encoding) { +const char *llvm::dwarf::CallFrameString(unsigned Encoding) { switch (Encoding) { case DW_CFA_advance_loc: return "CFA_advance_loc"; case DW_CFA_offset: return "CFA_offset"; @@ -584,7 +581,3 @@ llvm_unreachable("Unknown Dwarf Call Frame Instruction Encodings"); return ""; } - -} // End of namespace dwarf. - -} // End of namespace llvm. From sabre at nondot.org Tue Dec 29 01:44:16 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 07:44:16 -0000 Subject: [llvm-commits] [llvm] r92252 - in /llvm/trunk: include/llvm/Instruction.h include/llvm/Metadata.h lib/VMCore/Instruction.cpp lib/VMCore/Metadata.cpp Message-ID: <200912290744.nBT7iHiv030310@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 01:44:16 2009 New Revision: 92252 URL: http://llvm.org/viewvc/llvm-project?rev=92252&view=rev Log: remove some unneeded Metadata interfaces. Modified: llvm/trunk/include/llvm/Instruction.h llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Instruction.cpp llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Instruction.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Instruction.h?rev=92252&r1=92251&r2=92252&view=diff ============================================================================== --- llvm/trunk/include/llvm/Instruction.h (original) +++ llvm/trunk/include/llvm/Instruction.h Tue Dec 29 01:44:16 2009 @@ -160,6 +160,7 @@ MDNode *getMetadataImpl(unsigned KindID) const; MDNode *getMetadataImpl(const char *Kind) const; void getAllMetadataImpl(SmallVectorImpl > &)const; + void removeAllMetadata(); public: //===--------------------------------------------------------------------===// // Predicates and helper methods. Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92252&r1=92251&r2=92252&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Tue Dec 29 01:44:16 2009 @@ -231,14 +231,6 @@ /// getMDKindNames - Populate client supplied SmallVector with the name for /// each custom metadata ID. ID #0 is not used, so it is filled in as empty. void getMDKindNames(SmallVectorImpl &) const; - - /// ValueIsDeleted - This handler is used to update metadata store - /// when a value is deleted. - void ValueIsDeleted(Instruction *Inst); - - /// ValueIsCloned - This handler is used to update metadata store - /// when In1 is cloned to create In2. - void ValueIsCloned(const Instruction *In1, Instruction *In2); }; } // end llvm namespace Modified: llvm/trunk/lib/VMCore/Instruction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Instruction.cpp?rev=92252&r1=92251&r2=92252&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Instruction.cpp (original) +++ llvm/trunk/lib/VMCore/Instruction.cpp Tue Dec 29 01:44:16 2009 @@ -11,12 +11,10 @@ // //===----------------------------------------------------------------------===// -#include "LLVMContextImpl.h" +#include "llvm/Instruction.h" #include "llvm/Type.h" #include "llvm/Instructions.h" -#include "llvm/Function.h" #include "llvm/Constants.h" -#include "llvm/GlobalVariable.h" #include "llvm/Module.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/LeakDetector.h" @@ -52,7 +50,7 @@ Instruction::~Instruction() { assert(Parent == 0 && "Instruction still linked in the program!"); if (hasMetadata()) - getContext().pImpl->TheMetadata.ValueIsDeleted(this); + removeAllMetadata(); } @@ -462,7 +460,14 @@ Instruction *Instruction::clone() const { Instruction *New = clone_impl(); New->SubclassOptionalData = SubclassOptionalData; - if (hasMetadata()) - getContext().pImpl->TheMetadata.ValueIsCloned(this, New); + if (!hasMetadata()) + return New; + + // Otherwise, enumerate and copy over metadata from the old instruction to the + // new one. + SmallVector, 4> TheMDs; + getAllMetadata(TheMDs); + for (unsigned i = 0, e = TheMDs.size(); i != e; ++i) + New->setMetadata(TheMDs[i].first, TheMDs[i].second); return New; } Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92252&r1=92251&r2=92252&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Tue Dec 29 01:44:16 2009 @@ -273,26 +273,12 @@ void setMetadata(Instruction *Inst, unsigned Kind, MDNode *Node); - /// removeAllMetadata - Remove all metadata attached with an instruction. + /// removeAllMetadata - Remove all metadata attached to an instruction. void removeAllMetadata(Instruction *Inst); - - /// copyMD - If metadata is attached with Instruction In1 then attach /// the same metadata to In2. void copyMD(Instruction *In1, Instruction *In2); - - - /// ValueIsDeleted - This handler is used to update metadata store - /// when a value is deleted. - void ValueIsDeleted(const Value *) {} - void ValueIsDeleted(Instruction *Inst) { - removeAllMetadata(Inst); - } - - /// ValueIsCloned - This handler is used to update metadata store - /// when In1 is cloned to create In2. - void ValueIsCloned(const Instruction *In1, Instruction *In2); }; } @@ -413,20 +399,6 @@ In2->setMetadata(I->first, I->second); } -/// ValueIsCloned - This handler is used to update metadata store -/// when In1 is cloned to create In2. -void MetadataContextImpl::ValueIsCloned(const Instruction *In1, - Instruction *In2) { - // Find Metadata handles for In1. - MDStoreTy::iterator I = MetadataStore.find(In1); - assert(I != MetadataStore.end() && "Invalid custom metadata info!"); - - // FIXME: Give all metadata handlers a chance to adjust. - MDMapTy &In1Info = I->second; - for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I) - In2->setMetadata(I->first, I->second); -} - //===----------------------------------------------------------------------===// // MetadataContext implementation. // @@ -466,18 +438,6 @@ pImpl->getMDKindNames(N); } -/// ValueIsDeleted - This handler is used to update metadata store -/// when a value is deleted. -void MetadataContext::ValueIsDeleted(Instruction *Inst) { - pImpl->ValueIsDeleted(Inst); -} - -/// ValueIsCloned - This handler is used to update metadata store -/// when In1 is cloned to create In2. -void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) { - pImpl->ValueIsCloned(In1, In2); -} - //===----------------------------------------------------------------------===// // Instruction Metadata method implementations. // @@ -509,3 +469,9 @@ getContext().getMetadata().pImpl->getAllMetadata(this, Result); } +/// removeAllMetadata - Remove all metadata from this instruction. +void Instruction::removeAllMetadata() { + assert(hasMetadata() && "Caller should check"); + getContext().getMetadata().pImpl->removeAllMetadata(this); +} + From sabre at nondot.org Tue Dec 29 01:50:09 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 07:50:09 -0000 Subject: [llvm-commits] [llvm] r92254 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp Message-ID: <200912290750.nBT7oAU9030500@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 01:50:09 2009 New Revision: 92254 URL: http://llvm.org/viewvc/llvm-project?rev=92254&view=rev Log: the only call to this function (from clang) has been removed, zap it. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92254&r1=92253&r2=92254&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Tue Dec 29 01:50:09 2009 @@ -224,10 +224,6 @@ /// isValidName - Return true if Name is a valid custom metadata handler name. static bool isValidName(StringRef Name); - /// copyMD - If metadata is attached with Instruction In1 then attach - /// the same metadata to In2. - void copyMD(Instruction *In1, Instruction *In2); - /// getMDKindNames - Populate client supplied SmallVector with the name for /// each custom metadata ID. ID #0 is not used, so it is filled in as empty. void getMDKindNames(SmallVectorImpl &) const; Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92254&r1=92253&r2=92254&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Tue Dec 29 01:50:09 2009 @@ -275,10 +275,6 @@ /// removeAllMetadata - Remove all metadata attached to an instruction. void removeAllMetadata(Instruction *Inst); - - /// copyMD - If metadata is attached with Instruction In1 then attach - /// the same metadata to In2. - void copyMD(Instruction *In1, Instruction *In2); }; } @@ -387,18 +383,6 @@ } -/// copyMD - If metadata is attached with Instruction In1 then attach -/// the same metadata to In2. -void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) { - assert(In1 && In2 && "Invalid instruction!"); - MDMapTy &In1Info = MetadataStore[In1]; - if (In1Info.empty()) - return; - - for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I) - In2->setMetadata(I->first, I->second); -} - //===----------------------------------------------------------------------===// // MetadataContext implementation. // @@ -426,12 +410,6 @@ return pImpl->getMDKindID(Name); } -/// copyMD - If metadata is attached with Instruction In1 then attach -/// the same metadata to In2. -void MetadataContext::copyMD(Instruction *In1, Instruction *In2) { - pImpl->copyMD(In1, In2); -} - /// getHandlerNames - Populate client supplied smallvector using custome /// metadata name and ID. void MetadataContext::getMDKindNames(SmallVectorImpl &N) const { From sabre at nondot.org Tue Dec 29 01:56:15 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 07:56:15 -0000 Subject: [llvm-commits] [llvm] r92255 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp Message-ID: <200912290756.nBT7uF0Z030721@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 01:56:15 2009 New Revision: 92255 URL: http://llvm.org/viewvc/llvm-project?rev=92255&view=rev Log: privatize another interface. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92255&r1=92254&r2=92255&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Tue Dec 29 01:56:15 2009 @@ -221,9 +221,6 @@ /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. unsigned getMDKindID(StringRef Name) const; - /// isValidName - Return true if Name is a valid custom metadata handler name. - static bool isValidName(StringRef Name); - /// getMDKindNames - Populate client supplied SmallVector with the name for /// each custom metadata ID. ID #0 is not used, so it is filled in as empty. void getMDKindNames(SmallVectorImpl &) const; Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92255&r1=92254&r2=92255&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Tue Dec 29 01:56:15 2009 @@ -389,8 +389,9 @@ MetadataContext::MetadataContext() : pImpl(new MetadataContextImpl()) { } MetadataContext::~MetadataContext() { delete pImpl; } +#ifndef NDEBUG /// isValidName - Return true if Name is a valid custom metadata handler name. -bool MetadataContext::isValidName(StringRef MDName) { +static bool isValidName(StringRef MDName) { if (MDName.empty()) return false; @@ -404,9 +405,11 @@ } return true; } +#endif /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. unsigned MetadataContext::getMDKindID(StringRef Name) const { + assert(isValidName(Name) && "Invalid MDNode name"); return pImpl->getMDKindID(Name); } From sabre at nondot.org Tue Dec 29 02:03:58 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 08:03:58 -0000 Subject: [llvm-commits] [llvm] r92256 - /llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Message-ID: <200912290803.nBT83w7H030968@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 02:03:58 2009 New Revision: 92256 URL: http://llvm.org/viewvc/llvm-project?rev=92256&view=rev Log: remove useless argument. Modified: llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Modified: llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp?rev=92256&r1=92255&r2=92256&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp (original) +++ llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Tue Dec 29 02:03:58 2009 @@ -347,8 +347,7 @@ Ops.size(), TD); } -static MDNode *UpdateInlinedAtInfo(MDNode *InsnMD, MDNode *TheCallMD, - LLVMContext &Context) { +static MDNode *UpdateInlinedAtInfo(MDNode *InsnMD, MDNode *TheCallMD) { DILocation ILoc(InsnMD); if (ILoc.isNull()) return InsnMD; @@ -358,14 +357,14 @@ DILocation OrigLocation = ILoc.getOrigLocation(); MDNode *NewLoc = TheCallMD; if (!OrigLocation.isNull()) - NewLoc = UpdateInlinedAtInfo(OrigLocation.getNode(), TheCallMD, Context); + NewLoc = UpdateInlinedAtInfo(OrigLocation.getNode(), TheCallMD); SmallVector MDVs; MDVs.push_back(InsnMD->getElement(0)); // Line MDVs.push_back(InsnMD->getElement(1)); // Col MDVs.push_back(InsnMD->getElement(2)); // Scope MDVs.push_back(NewLoc); - return MDNode::get(Context, MDVs.data(), MDVs.size()); + return MDNode::get(InsnMD->getContext(), MDVs.data(), MDVs.size()); } /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto, @@ -421,8 +420,8 @@ // BasicBlock::iterator I = NewBB->begin(); - LLVMContext &Context = OldFunc->getContext(); - unsigned DbgKind = Context.getMetadata().getMDKindID("dbg"); + // FIXME: Only use of context. + unsigned DbgKind = OldFunc->getContext().getMetadata().getMDKindID("dbg"); MDNode *TheCallMD = NULL; SmallVector MDVs; if (TheCall && TheCall->hasMetadata()) @@ -437,7 +436,7 @@ if (I->hasMetadata()) { if (TheCallMD) { if (MDNode *IMD = I->getMetadata(DbgKind)) { - MDNode *NewMD = UpdateInlinedAtInfo(IMD, TheCallMD, Context); + MDNode *NewMD = UpdateInlinedAtInfo(IMD, TheCallMD); I->setMetadata(DbgKind, NewMD); } } else { @@ -461,7 +460,7 @@ if (I->hasMetadata()) { if (TheCallMD) { if (MDNode *IMD = I->getMetadata(DbgKind)) { - MDNode *NewMD = UpdateInlinedAtInfo(IMD, TheCallMD, Context); + MDNode *NewMD = UpdateInlinedAtInfo(IMD, TheCallMD); I->setMetadata(DbgKind, NewMD); } } else { From sabre at nondot.org Tue Dec 29 02:06:57 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 08:06:57 -0000 Subject: [llvm-commits] [llvm] r92258 - /llvm/trunk/include/llvm/Module.h Message-ID: <200912290806.nBT86vKX031077@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 02:06:56 2009 New Revision: 92258 URL: http://llvm.org/viewvc/llvm-project?rev=92258&view=rev Log: just cleanup. Modified: llvm/trunk/include/llvm/Module.h Modified: llvm/trunk/include/llvm/Module.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Module.h?rev=92258&r1=92257&r2=92258&view=diff ============================================================================== --- llvm/trunk/include/llvm/Module.h (original) +++ llvm/trunk/include/llvm/Module.h Tue Dec 29 02:06:56 2009 @@ -24,7 +24,6 @@ namespace llvm { -class GlobalValueRefMap; // Used by ConstantVals.cpp class FunctionType; class LLVMContext; @@ -132,7 +131,7 @@ /// @name Member Variables /// @{ private: - LLVMContext& Context; ///< The LLVMContext from which types and + LLVMContext &Context; ///< The LLVMContext from which types and ///< constants are allocated. GlobalListType GlobalList; ///< The Global Variables in the module FunctionListType FunctionList; ///< The Functions in the module @@ -161,7 +160,7 @@ /// @} /// @name Module Level Accessors /// @{ -public: + /// Get the module identifier which is, essentially, the name of the module. /// @returns the module identifier as a string const std::string &getModuleIdentifier() const { return ModuleID; } @@ -190,11 +189,11 @@ /// Get any module-scope inline assembly blocks. /// @returns a string containing the module-scope inline assembly blocks. const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; } + /// @} /// @name Module Level Mutators /// @{ -public: - + /// Set the module identifier. void setModuleIdentifier(StringRef ID) { ModuleID = ID; } @@ -226,7 +225,7 @@ /// @} /// @name Function Accessors /// @{ -public: + /// getOrInsertFunction - Look up the specified function in the module symbol /// table. Four possibilities: /// 1. If it does not exist, add a prototype for the function and return it. @@ -267,7 +266,7 @@ /// @} /// @name Global Variable Accessors /// @{ -public: + /// getGlobalVariable - Look up the specified global variable in the module /// symbol table. If it does not exist, return null. If AllowInternal is set /// to true, this function will return types that have InternalLinkage. By @@ -294,7 +293,7 @@ /// @} /// @name Global Alias Accessors /// @{ -public: + /// getNamedAlias - Return the first global alias in the module with the /// specified name, of arbitrary type. This method returns null if a global /// with the specified name is not found. @@ -303,7 +302,7 @@ /// @} /// @name Named Metadata Accessors /// @{ -public: + /// getNamedMetadata - Return the first NamedMDNode in the module with the /// specified name. This method returns null if a NamedMDNode with the /// specified name is not found. @@ -317,7 +316,7 @@ /// @} /// @name Type Accessors /// @{ -public: + /// addTypeName - Insert an entry in the symbol table mapping Str to Type. If /// there is already an entry for this name, true is returned and the symbol /// table is not modified. @@ -334,7 +333,7 @@ /// @} /// @name Direct access to the globals list, functions list, and symbol table /// @{ -public: + /// Get the Module's list of global variables (constant). const GlobalListType &getGlobalList() const { return GlobalList; } /// Get the Module's list of global variables. @@ -375,7 +374,7 @@ /// @} /// @name Global Variable Iteration /// @{ -public: + /// Get an iterator to the first global variable global_iterator global_begin() { return GlobalList.begin(); } /// Get a constant iterator to the first global variable @@ -390,7 +389,7 @@ /// @} /// @name Function Iteration /// @{ -public: + /// Get an iterator to the first function. iterator begin() { return FunctionList.begin(); } /// Get a constant iterator to the first function. @@ -407,7 +406,7 @@ /// @} /// @name Dependent Library Iteration /// @{ -public: + /// @brief Get a constant iterator to beginning of dependent library list. inline lib_iterator lib_begin() const { return LibraryList.begin(); } /// @brief Get a constant iterator to end of dependent library list. @@ -424,7 +423,7 @@ /// @} /// @name Alias Iteration /// @{ -public: + /// Get an iterator to the first alias. alias_iterator alias_begin() { return AliasList.begin(); } /// Get a constant iterator to the first alias. @@ -442,31 +441,31 @@ /// @} /// @name Named Metadata Iteration /// @{ -public: + /// Get an iterator to the first named metadata. - named_metadata_iterator named_metadata_begin() - { return NamedMDList.begin(); } + named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); } /// Get a constant iterator to the first named metadata. - const_named_metadata_iterator named_metadata_begin() const - { return NamedMDList.begin(); } + const_named_metadata_iterator named_metadata_begin() const { + return NamedMDList.begin(); + } + /// Get an iterator to the last named metadata. - named_metadata_iterator named_metadata_end () - { return NamedMDList.end(); } + named_metadata_iterator named_metadata_end() { return NamedMDList.end(); } /// Get a constant iterator to the last named metadata. - const_named_metadata_iterator named_metadata_end () const - { return NamedMDList.end(); } + const_named_metadata_iterator named_metadata_end() const { + return NamedMDList.end(); + } + /// Determine how many NamedMDNodes are in the Module's list of named metadata. - size_t named_metadata_size () const - { return NamedMDList.size(); } + size_t named_metadata_size() const { return NamedMDList.size(); } /// Determine if the list of named metadata is empty. - bool named_metadata_empty() const - { return NamedMDList.empty(); } + bool named_metadata_empty() const { return NamedMDList.empty(); } /// @} /// @name Utility functions for printing and dumping Module objects /// @{ -public: + /// Print the module to an output stream with AssemblyAnnotationWriter. void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const; From sabre at nondot.org Tue Dec 29 03:01:38 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 09:01:38 -0000 Subject: [llvm-commits] [llvm] r92259 - in /llvm/trunk: include/llvm/ lib/Analysis/ lib/AsmParser/ lib/Bitcode/Reader/ lib/Bitcode/Writer/ lib/CodeGen/SelectionDAG/ lib/Transforms/IPO/ lib/Transforms/Utils/ lib/VMCore/ Message-ID: <200912290901.nBT91ego011864@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 03:01:33 2009 New Revision: 92259 URL: http://llvm.org/viewvc/llvm-project?rev=92259&view=rev Log: Final step in the metadata API restructuring: move the getMDKindID/getMDKindNames methods to LLVMContext (and add convenience methods to Module), eliminating MetadataContext. Move the state that it maintains out to LLVMContext. Modified: llvm/trunk/include/llvm/Instruction.h llvm/trunk/include/llvm/LLVMContext.h llvm/trunk/include/llvm/Metadata.h llvm/trunk/include/llvm/Module.h llvm/trunk/include/llvm/Value.h llvm/trunk/lib/Analysis/DebugInfo.cpp llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp llvm/trunk/lib/Bitcode/Reader/BitcodeReader.h llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp llvm/trunk/lib/VMCore/AsmWriter.cpp llvm/trunk/lib/VMCore/IRBuilder.cpp llvm/trunk/lib/VMCore/LLVMContext.cpp llvm/trunk/lib/VMCore/LLVMContextImpl.h llvm/trunk/lib/VMCore/Metadata.cpp llvm/trunk/lib/VMCore/Module.cpp Modified: llvm/trunk/include/llvm/Instruction.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Instruction.h?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/include/llvm/Instruction.h (original) +++ llvm/trunk/include/llvm/Instruction.h Tue Dec 29 03:01:33 2009 @@ -22,7 +22,6 @@ class LLVMContext; class MDNode; -class MetadataContextImpl; template class SymbolTableListTraits; @@ -316,7 +315,6 @@ return Value::getSubclassDataFromValue(); } - friend class MetadataContextImpl; void setHasMetadata(bool V) { setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) | (V ? HasMetadataBit : 0)); Modified: llvm/trunk/include/llvm/LLVMContext.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/LLVMContext.h?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/include/llvm/LLVMContext.h (original) +++ llvm/trunk/include/llvm/LLVMContext.h Tue Dec 29 03:01:33 2009 @@ -18,7 +18,8 @@ namespace llvm { class LLVMContextImpl; -class MetadataContext; +class StringRef; +template class SmallVectorImpl; /// This is an important class for using LLVM in a threaded context. It /// (opaquely) owns and manages the core "global" data of LLVM's core @@ -31,14 +32,23 @@ void operator=(LLVMContext&); public: - LLVMContextImpl* const pImpl; - MetadataContext &getMetadata(); + LLVMContextImpl *const pImpl; LLVMContext(); ~LLVMContext(); + + /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. + /// This ID is uniqued across modules in the current LLVMContext. + unsigned getMDKindID(StringRef Name) const; + + /// getMDKindNames - Populate client supplied SmallVector with the name for + /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, + /// so it is filled in as an empty string. + void getMDKindNames(SmallVectorImpl &Result) const; }; -/// FOR BACKWARDS COMPATIBILITY - Returns a global context. -extern LLVMContext& getGlobalContext(); +/// getGlobalContext - Returns a global context. This is for LLVM clients that +/// only care about operating on a single thread. +extern LLVMContext &getGlobalContext(); } Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Tue Dec 29 03:01:33 2009 @@ -25,7 +25,6 @@ class Instruction; class LLVMContext; class Module; -class MetadataContextImpl; template class SmallVectorImpl; //===----------------------------------------------------------------------===// @@ -204,28 +203,6 @@ } }; -//===----------------------------------------------------------------------===// -/// MetadataContext - MetadataContext handles uniquing and assignment of IDs for -/// custom metadata types. -/// -class MetadataContext { - MetadataContext(MetadataContext&); // DO NOT IMPLEMENT - void operator=(MetadataContext&); // DO NOT IMPLEMENT - - MetadataContextImpl *const pImpl; - friend class Instruction; -public: - MetadataContext(); - ~MetadataContext(); - - /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. - unsigned getMDKindID(StringRef Name) const; - - /// getMDKindNames - Populate client supplied SmallVector with the name for - /// each custom metadata ID. ID #0 is not used, so it is filled in as empty. - void getMDKindNames(SmallVectorImpl &) const; -}; - } // end llvm namespace #endif Modified: llvm/trunk/include/llvm/Module.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Module.h?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/include/llvm/Module.h (original) +++ llvm/trunk/include/llvm/Module.h Tue Dec 29 03:01:33 2009 @@ -184,7 +184,7 @@ /// Get the global data context. /// @returns LLVMContext - a container for LLVM's global information - LLVMContext& getContext() const { return Context; } + LLVMContext &getContext() const { return Context; } /// Get any module-scope inline assembly blocks. /// @returns a string containing the module-scope inline assembly blocks. @@ -222,6 +222,15 @@ /// if a global with the specified name is not found. GlobalValue *getNamedValue(StringRef Name) const; + /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. + /// This ID is uniqued across modules in the current LLVMContext. + unsigned getMDKindID(StringRef Name) const; + + /// getMDKindNames - Populate client supplied SmallVector with the name for + /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, + /// so it is filled in as an empty string. + void getMDKindNames(SmallVectorImpl &Result) const; + /// @} /// @name Function Accessors /// @{ Modified: llvm/trunk/include/llvm/Value.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Value.h?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/include/llvm/Value.h (original) +++ llvm/trunk/include/llvm/Value.h Tue Dec 29 03:01:33 2009 @@ -41,7 +41,6 @@ class AssemblyAnnotationWriter; class ValueHandleBase; class LLVMContext; -class MetadataContextImpl; class Twine; //===----------------------------------------------------------------------===// Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Tue Dec 29 03:01:33 2009 @@ -18,7 +18,6 @@ #include "llvm/Intrinsics.h" #include "llvm/IntrinsicInst.h" #include "llvm/Instructions.h" -#include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/ADT/SmallPtrSet.h" @@ -1117,7 +1116,7 @@ /// processModule - Process entire module and collect debug info. void DebugInfoFinder::processModule(Module &M) { - unsigned MDDbgKind = M.getContext().getMetadata().getMDKindID("dbg"); + unsigned MDDbgKind = M.getMDKindID("dbg"); for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI) Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 03:01:33 2009 @@ -18,8 +18,6 @@ #include "llvm/DerivedTypes.h" #include "llvm/InlineAsm.h" #include "llvm/Instructions.h" -#include "llvm/LLVMContext.h" -#include "llvm/Metadata.h" #include "llvm/Module.h" #include "llvm/Operator.h" #include "llvm/ValueSymbolTable.h" @@ -1122,8 +1120,7 @@ MetadataBase *Node; if (ParseMDNode(Node)) return true; - MetadataContext &TheMetadata = M->getContext().getMetadata(); - unsigned MDK = TheMetadata.getMDKindID(Name.c_str()); + unsigned MDK = M->getMDKindID(Name.c_str()); MDsOnInst.push_back(std::make_pair(MDK, cast(Node))); return false; } Modified: llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp (original) +++ llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp Tue Dec 29 03:01:33 2009 @@ -17,7 +17,6 @@ #include "llvm/DerivedTypes.h" #include "llvm/InlineAsm.h" #include "llvm/IntrinsicInst.h" -#include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Operator.h" #include "llvm/AutoUpgrade.h" @@ -840,7 +839,7 @@ for (unsigned i = 1; i != RecordLength; ++i) Name[i-1] = Record[i]; - unsigned NewKind = Context.getMetadata().getMDKindID(Name.str()); + unsigned NewKind = TheModule->getMDKindID(Name.str()); assert(Kind == NewKind && "FIXME: Unable to handle custom metadata mismatch!");(void)NewKind; break; Modified: llvm/trunk/lib/Bitcode/Reader/BitcodeReader.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Reader/BitcodeReader.h?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Reader/BitcodeReader.h (original) +++ llvm/trunk/lib/Bitcode/Reader/BitcodeReader.h Tue Dec 29 03:01:33 2009 @@ -170,7 +170,7 @@ DenseMap > BlockAddrFwdRefs; public: - explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext& C) + explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C) : Context(C), Buffer(buffer), ErrorString(0), ValueList(C), MDValueList(C) { HasReversedFunctionsWithBodies = false; } Modified: llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp Tue Dec 29 03:01:33 2009 @@ -19,8 +19,6 @@ #include "llvm/DerivedTypes.h" #include "llvm/InlineAsm.h" #include "llvm/Instructions.h" -#include "llvm/LLVMContext.h" -#include "llvm/Metadata.h" #include "llvm/Module.h" #include "llvm/Operator.h" #include "llvm/TypeSymbolTable.h" @@ -595,9 +593,8 @@ // Write metadata kinds // METADATA_KIND - [n x [id, name]] - MetadataContext &TheMetadata = M->getContext().getMetadata(); SmallVector Names; - TheMetadata.getMDKindNames(Names); + M->getMDKindNames(Names); assert(Names[0] == "" && "MDKind #0 is invalid"); if (Names.size() == 1) return; Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp Tue Dec 29 03:01:33 2009 @@ -395,8 +395,7 @@ BasicBlock::iterator End, bool &HadTailCall) { SDB->setCurrentBasicBlock(BB); - MetadataContext &TheMetadata =LLVMBB->getParent()->getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); + unsigned MDDbgKind = LLVMBB->getContext().getMDKindID("dbg"); // Lower all of the non-terminator instructions. If a call is emitted // as a tail call, cease emitting nodes for this block. @@ -676,8 +675,7 @@ #endif ); - MetadataContext &TheMetadata = Fn.getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); + unsigned MDDbgKind = Fn.getContext().getMDKindID("dbg"); // Iterate over all basic blocks in the function. for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { Modified: llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp (original) +++ llvm/trunk/lib/Transforms/IPO/StripSymbols.cpp Tue Dec 29 03:01:33 2009 @@ -24,7 +24,6 @@ #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" -#include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Analysis/DebugInfo.h" @@ -220,9 +219,8 @@ Changed = true; NMD->eraseFromParent(); } - MetadataContext &TheMetadata = M.getContext().getMetadata(); - unsigned MDDbgKind = TheMetadata.getMDKindID("dbg"); - + + unsigned MDDbgKind = M.getMDKindID("dbg"); for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI) for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI) Modified: llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp (original) +++ llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Tue Dec 29 03:01:33 2009 @@ -420,8 +420,7 @@ // BasicBlock::iterator I = NewBB->begin(); - // FIXME: Only use of context. - unsigned DbgKind = OldFunc->getContext().getMetadata().getMDKindID("dbg"); + unsigned DbgKind = OldFunc->getContext().getMDKindID("dbg"); MDNode *TheCallMD = NULL; SmallVector MDVs; if (TheCall && TheCall->hasMetadata()) Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Tue Dec 29 03:01:33 2009 @@ -22,7 +22,6 @@ #include "llvm/DerivedTypes.h" #include "llvm/InlineAsm.h" #include "llvm/IntrinsicInst.h" -#include "llvm/LLVMContext.h" #include "llvm/Operator.h" #include "llvm/Module.h" #include "llvm/ValueSymbolTable.h" @@ -1338,7 +1337,7 @@ AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M); // FIXME: Provide MDPrinter if (M) - M->getContext().getMetadata().getMDKindNames(MDNames); + M->getMDKindNames(MDNames); } void write(const Module *M) { printModule(M); } Modified: llvm/trunk/lib/VMCore/IRBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/IRBuilder.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/IRBuilder.cpp (original) +++ llvm/trunk/lib/VMCore/IRBuilder.cpp Tue Dec 29 03:01:33 2009 @@ -15,7 +15,6 @@ #include "llvm/Support/IRBuilder.h" #include "llvm/GlobalVariable.h" #include "llvm/Function.h" -#include "llvm/Metadata.h" #include "llvm/LLVMContext.h" using namespace llvm; @@ -37,7 +36,7 @@ /// information. void IRBuilderBase::SetCurrentDebugLocation(MDNode *L) { if (DbgMDKind == 0) - DbgMDKind = Context.getMetadata().getMDKindID("dbg"); + DbgMDKind = Context.getMDKindID("dbg"); CurDbgLocation = L; } Modified: llvm/trunk/lib/VMCore/LLVMContext.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/LLVMContext.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/LLVMContext.cpp (original) +++ llvm/trunk/lib/VMCore/LLVMContext.cpp Tue Dec 29 03:01:33 2009 @@ -17,9 +17,7 @@ #include "llvm/Constants.h" #include "llvm/Instruction.h" #include "llvm/Support/ManagedStatic.h" -#include "llvm/Support/ValueHandle.h" #include "LLVMContextImpl.h" - using namespace llvm; static ManagedStatic GlobalContext; @@ -44,6 +42,3 @@ OperandList[i+1] = IdxList[i]; } -MetadataContext &LLVMContext::getMetadata() { - return pImpl->TheMetadata; -} Modified: llvm/trunk/lib/VMCore/LLVMContextImpl.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/LLVMContextImpl.h?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/LLVMContextImpl.h (original) +++ llvm/trunk/lib/VMCore/LLVMContextImpl.h Tue Dec 29 03:01:33 2009 @@ -23,6 +23,7 @@ #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Assembly/Writer.h" +#include "llvm/Support/ValueHandle.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/DenseMap.h" @@ -171,7 +172,17 @@ typedef DenseMap ValueHandlesTy; ValueHandlesTy ValueHandles; - MetadataContext TheMetadata; + /// CustomMDKindNames - Map to hold the metadata string to ID mapping. + StringMap CustomMDKindNames; + + typedef std::pair > MDPairTy; + typedef SmallVector MDMapTy; + + /// MetadataStore - Collection of per-instruction metadata used in this + /// context. + DenseMap MetadataStore; + + LLVMContextImpl(LLVMContext &C) : TheTrueVal(0), TheFalseVal(0), VoidTy(C, Type::VoidTyID), LabelTy(C, Type::LabelTyID), @@ -187,8 +198,7 @@ Int32Ty(C, 32), Int64Ty(C, 64) { } - ~LLVMContextImpl() - { + ~LLVMContextImpl() { ExprConstants.freeConstants(); ArrayConstants.freeConstants(); StructConstants.freeConstants(); Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Tue Dec 29 03:01:33 2009 @@ -243,131 +243,103 @@ //===----------------------------------------------------------------------===// -// MetadataContextImpl implementation. +// MetadataContext implementation. // -namespace llvm { -class MetadataContextImpl { -public: - typedef std::pair > MDPairTy; - typedef SmallVector MDMapTy; - typedef DenseMap MDStoreTy; - friend class BitcodeReader; -private: - - /// MetadataStore - Collection of metadata used in this context. - MDStoreTy MetadataStore; - - /// MDHandlerNames - Map to hold metadata handler names. - StringMap MDHandlerNames; - -public: - // Name <-> ID mapping methods. - unsigned getMDKindID(StringRef Name); - void getMDKindNames(SmallVectorImpl &) const; - - - // Instruction metadata methods. - MDNode *getMetadata(const Instruction *Inst, unsigned Kind); - void getAllMetadata(const Instruction *Inst, - SmallVectorImpl > &MDs)const; - - void setMetadata(Instruction *Inst, unsigned Kind, MDNode *Node); - - /// removeAllMetadata - Remove all metadata attached to an instruction. - void removeAllMetadata(Instruction *Inst); -}; + +#ifndef NDEBUG +/// isValidName - Return true if Name is a valid custom metadata handler name. +static bool isValidName(StringRef MDName) { + if (MDName.empty()) + return false; + + if (!isalpha(MDName[0])) + return false; + + for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E; + ++I) { + if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.') + return false; + } + return true; } +#endif /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. -unsigned MetadataContextImpl::getMDKindID(StringRef Name) { - unsigned &Entry = MDHandlerNames[Name]; - +unsigned LLVMContext::getMDKindID(StringRef Name) const { + assert(isValidName(Name) && "Invalid MDNode name"); + + unsigned &Entry = pImpl->CustomMDKindNames[Name]; + // If this is new, assign it its ID. - if (Entry == 0) Entry = MDHandlerNames.size(); + if (Entry == 0) Entry = pImpl->CustomMDKindNames.size(); return Entry; } /// getHandlerNames - Populate client supplied smallvector using custome /// metadata name and ID. -void MetadataContextImpl:: -getMDKindNames(SmallVectorImpl &Names) const { - Names.resize(MDHandlerNames.size()+1); +void LLVMContext::getMDKindNames(SmallVectorImpl &Names) const { + Names.resize(pImpl->CustomMDKindNames.size()+1); Names[0] = ""; - for (StringMap::const_iterator I = MDHandlerNames.begin(), - E = MDHandlerNames.end(); I != E; ++I) + for (StringMap::const_iterator I = pImpl->CustomMDKindNames.begin(), + E = pImpl->CustomMDKindNames.end(); I != E; ++I) // MD Handlers are numbered from 1. Names[I->second] = I->first(); } +//===----------------------------------------------------------------------===// +// Instruction Metadata method implementations. +// -/// getMetadata - Get the metadata of given kind attached to an Instruction. -/// If the metadata is not found then return 0. -MDNode *MetadataContextImpl:: -getMetadata(const Instruction *Inst, unsigned MDKind) { - MDMapTy &Info = MetadataStore[Inst]; - assert(Inst->hasMetadata() && !Info.empty() && "Shouldn't have called this"); - - for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I) - if (I->first == MDKind) - return I->second; - return 0; +void Instruction::setMetadata(const char *Kind, MDNode *Node) { + if (Node == 0 && !hasMetadata()) return; + setMetadata(getContext().getMDKindID(Kind), Node); } -/// getAllMetadata - Get all of the metadata attached to an Instruction. -void MetadataContextImpl:: -getAllMetadata(const Instruction *Inst, - SmallVectorImpl > &Result) const { - assert(Inst->hasMetadata() && MetadataStore.find(Inst) != MetadataStore.end() - && "Shouldn't have called this"); - const MDMapTy &Info = MetadataStore.find(Inst)->second; - assert(!Info.empty() && "Shouldn't have called this"); - - Result.clear(); - Result.append(Info.begin(), Info.end()); - - // Sort the resulting array so it is stable. - if (Result.size() > 1) - array_pod_sort(Result.begin(), Result.end()); +MDNode *Instruction::getMetadataImpl(const char *Kind) const { + return getMetadataImpl(getContext().getMDKindID(Kind)); } - -void MetadataContextImpl::setMetadata(Instruction *Inst, unsigned Kind, - MDNode *Node) { +/// setMetadata - Set the metadata of of the specified kind to the specified +/// node. This updates/replaces metadata if already present, or removes it if +/// Node is null. +void Instruction::setMetadata(unsigned KindID, MDNode *Node) { + if (Node == 0 && !hasMetadata()) return; + // Handle the case when we're adding/updating metadata on an instruction. if (Node) { - MDMapTy &Info = MetadataStore[Inst]; - assert(!Info.empty() == Inst->hasMetadata() && "HasMetadata bit is wonked"); + LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this]; + assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked"); if (Info.empty()) { - Inst->setHasMetadata(true); + setHasMetadata(true); } else { // Handle replacement of an existing value. for (unsigned i = 0, e = Info.size(); i != e; ++i) - if (Info[i].first == Kind) { + if (Info[i].first == KindID) { Info[i].second = Node; return; } } // No replacement, just add it to the list. - Info.push_back(std::make_pair(Kind, Node)); + Info.push_back(std::make_pair(KindID, Node)); return; } // Otherwise, we're removing metadata from an instruction. - assert(Inst->hasMetadata() && MetadataStore.count(Inst) && + assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) && "HasMetadata bit out of date!"); - MDMapTy &Info = MetadataStore[Inst]; - + LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this]; + // Common case is removing the only entry. - if (Info.size() == 1 && Info[0].first == Kind) { - MetadataStore.erase(Inst); - Inst->setHasMetadata(false); + if (Info.size() == 1 && Info[0].first == KindID) { + getContext().pImpl->MetadataStore.erase(this); + setHasMetadata(false); return; } // Handle replacement of an existing value. for (unsigned i = 0, e = Info.size(); i != e; ++i) - if (Info[i].first == Kind) { + if (Info[i].first == KindID) { Info[i] = Info.back(); Info.pop_back(); assert(!Info.empty() && "Removing last entry should be handled above"); @@ -376,83 +348,37 @@ // Otherwise, removing an entry that doesn't exist on the instruction. } -/// removeAllMetadata - Remove all metadata attached with an instruction. -void MetadataContextImpl::removeAllMetadata(Instruction *Inst) { - MetadataStore.erase(Inst); - Inst->setHasMetadata(false); -} - - -//===----------------------------------------------------------------------===// -// MetadataContext implementation. -// -MetadataContext::MetadataContext() : pImpl(new MetadataContextImpl()) { } -MetadataContext::~MetadataContext() { delete pImpl; } - -#ifndef NDEBUG -/// isValidName - Return true if Name is a valid custom metadata handler name. -static bool isValidName(StringRef MDName) { - if (MDName.empty()) - return false; - - if (!isalpha(MDName[0])) - return false; - - for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E; - ++I) { - if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.') - return false; - } - return true; -} -#endif - -/// getMDKindID - Return a unique non-zero ID for the specified metadata kind. -unsigned MetadataContext::getMDKindID(StringRef Name) const { - assert(isValidName(Name) && "Invalid MDNode name"); - return pImpl->getMDKindID(Name); -} - -/// getHandlerNames - Populate client supplied smallvector using custome -/// metadata name and ID. -void MetadataContext::getMDKindNames(SmallVectorImpl &N) const { - pImpl->getMDKindNames(N); -} - -//===----------------------------------------------------------------------===// -// Instruction Metadata method implementations. -// - -void Instruction::setMetadata(const char *Kind, MDNode *Node) { - if (Node == 0 && !hasMetadata()) return; - setMetadata(getContext().getMetadata().getMDKindID(Kind), Node); -} - -MDNode *Instruction::getMetadataImpl(const char *Kind) const { - return getMetadataImpl(getContext().getMetadata().getMDKindID(Kind)); -} - -/// setMetadata - Set the metadata of of the specified kind to the specified -/// node. This updates/replaces metadata if already present, or removes it if -/// Node is null. -void Instruction::setMetadata(unsigned KindID, MDNode *Node) { - if (Node == 0 && !hasMetadata()) return; - - getContext().getMetadata().pImpl->setMetadata(this, KindID, Node); -} - MDNode *Instruction::getMetadataImpl(unsigned KindID) const { - return getContext().getMetadata().pImpl->getMetadata(this, KindID); + LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this]; + assert(hasMetadata() && !Info.empty() && "Shouldn't have called this"); + + for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end(); + I != E; ++I) + if (I->first == KindID) + return I->second; + return 0; } void Instruction::getAllMetadataImpl(SmallVectorImpl > &Result)const { - getContext().getMetadata().pImpl->getAllMetadata(this, Result); + assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) && + "Shouldn't have called this"); + const LLVMContextImpl::MDMapTy &Info = + getContext().pImpl->MetadataStore.find(this)->second; + assert(!Info.empty() && "Shouldn't have called this"); + + Result.clear(); + Result.append(Info.begin(), Info.end()); + + // Sort the resulting array so it is stable. + if (Result.size() > 1) + array_pod_sort(Result.begin(), Result.end()); } /// removeAllMetadata - Remove all metadata from this instruction. void Instruction::removeAllMetadata() { assert(hasMetadata() && "Caller should check"); - getContext().getMetadata().pImpl->removeAllMetadata(this); + getContext().pImpl->MetadataStore.erase(this); + setHasMetadata(false); } Modified: llvm/trunk/lib/VMCore/Module.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Module.cpp?rev=92259&r1=92258&r2=92259&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Module.cpp (original) +++ llvm/trunk/lib/VMCore/Module.cpp Tue Dec 29 03:01:33 2009 @@ -118,6 +118,20 @@ return cast_or_null(getValueSymbolTable().lookup(Name)); } +/// getMDKindID - Return a unique non-zero ID for the specified metadata kind. +/// This ID is uniqued across modules in the current LLVMContext. +unsigned Module::getMDKindID(StringRef Name) const { + return Context.getMDKindID(Name); +} + +/// getMDKindNames - Populate client supplied SmallVector with the name for +/// custom metadata IDs registered in this LLVMContext. ID #0 is not used, +/// so it is filled in as an empty string. +void Module::getMDKindNames(SmallVectorImpl &Result) const { + return Context.getMDKindNames(Result); +} + + //===----------------------------------------------------------------------===// // Methods for easy access to the functions in the module. // From sabre at nondot.org Tue Dec 29 03:12:30 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 09:12:30 -0000 Subject: [llvm-commits] [llvm] r92260 - /llvm/trunk/lib/Transforms/Utils/Local.cpp Message-ID: <200912290912.nBT9CUKW015360@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 03:12:29 2009 New Revision: 92260 URL: http://llvm.org/viewvc/llvm-project?rev=92260&view=rev Log: prune #includes. Modified: llvm/trunk/lib/Transforms/Utils/Local.cpp Modified: llvm/trunk/lib/Transforms/Utils/Local.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/Local.cpp?rev=92260&r1=92259&r2=92260&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Utils/Local.cpp (original) +++ llvm/trunk/lib/Transforms/Utils/Local.cpp Tue Dec 29 03:12:29 2009 @@ -20,10 +20,9 @@ #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/IntrinsicInst.h" -#include "llvm/LLVMContext.h" +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Analysis/ConstantFolding.h" -#include "llvm/Analysis/DebugInfo.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/ProfileInfo.h" #include "llvm/Target/TargetData.h" @@ -31,6 +30,7 @@ #include "llvm/Support/Debug.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Support/MathExtras.h" +#include "llvm/Support/ValueHandle.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; From sabre at nondot.org Tue Dec 29 03:15:46 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 09:15:46 -0000 Subject: [llvm-commits] [llvm] r92261 - in /llvm/trunk: include/llvm/Analysis/DebugInfo.h lib/Analysis/DebugInfo.cpp Message-ID: <200912290915.nBT9FkuD015457@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 03:15:46 2009 New Revision: 92261 URL: http://llvm.org/viewvc/llvm-project?rev=92261&view=rev Log: one pass of cleanup over DebugInfo.h. Much more is still needed. Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h llvm/trunk/lib/Analysis/DebugInfo.cpp Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Analysis/DebugInfo.h?rev=92261&r1=92260&r2=92261&view=diff ============================================================================== --- llvm/trunk/include/llvm/Analysis/DebugInfo.h (original) +++ llvm/trunk/include/llvm/Analysis/DebugInfo.h Tue Dec 29 03:15:46 2009 @@ -17,14 +17,10 @@ #ifndef LLVM_ANALYSIS_DEBUGINFO_H #define LLVM_ANALYSIS_DEBUGINFO_H -#include "llvm/Metadata.h" -#include "llvm/Target/TargetMachine.h" -#include "llvm/ADT/StringMap.h" -#include "llvm/ADT/DenseMap.h" +#include "llvm/Metadata.h" // FIXME: Should not need this. #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/SmallPtrSet.h" -#include "llvm/Support/Dwarf.h" -#include "llvm/Support/ValueHandle.h" +#include "llvm/Support/Dwarf.h" // FIXME: Should not need this. namespace llvm { class BasicBlock; @@ -42,13 +38,13 @@ class DebugLoc; struct DebugLocTracker; class Instruction; - class LLVMContext; - /// DIDescriptor - A thin wraper around MDNode to access encoded debug info. This should not - /// be stored in a container, because underly MDNode may change in certain situations. + /// DIDescriptor - A thin wraper around MDNode to access encoded debug info. + /// This should not be stored in a container, because underly MDNode may + /// change in certain situations. class DIDescriptor { protected: - MDNode *DbgNode; + MDNode *DbgNode; /// DIDescriptor constructor. If the specified node is non-null, check /// to make sure that the tag in the descriptor matches 'RequiredTag'. If @@ -86,7 +82,7 @@ } /// ValidDebugInfo - Return true if N represents valid debug info value. - static bool ValidDebugInfo(MDNode *N, CodeGenOpt::Level OptLevel); + static bool ValidDebugInfo(MDNode *N, unsigned OptLevel); /// dump - print descriptor. void dump() const; @@ -483,7 +479,7 @@ StringRef getName() const { return getStringField(2); } StringRef getDirectory() const { return getContext().getDirectory(); } StringRef getFilename() const { return getContext().getFilename(); } - DICompileUnit getCompileUnit() const { return getFieldAs(3); } + DICompileUnit getCompileUnit() const { return getFieldAs(3);} unsigned getLineNumber() const { return getUnsignedField(4); } }; @@ -688,34 +684,29 @@ /// Find the debug info descriptor corresponding to this global variable. Value *findDbgGlobalDeclare(GlobalVariable *V); -bool getLocationInfo(const Value *V, std::string &DisplayName, - std::string &Type, unsigned &LineNo, std::string &File, - std::string &Dir); + bool getLocationInfo(const Value *V, std::string &DisplayName, + std::string &Type, unsigned &LineNo, std::string &File, + std::string &Dir); /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, - CodeGenOpt::Level OptLev); + bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, unsigned OptLev); /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI, - CodeGenOpt::Level OptLev); + bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI, unsigned OptLev); /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI, - CodeGenOpt::Level OptLev); + bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI, unsigned OptLev); /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI, - CodeGenOpt::Level OptLev); + bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI, unsigned OptLev); /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI, - CodeGenOpt::Level OptLev); + bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI, unsigned OptLev); /// ExtractDebugLocation - Extract debug location information /// from llvm.dbg.stoppoint intrinsic. Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=92261&r1=92260&r2=92261&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Tue Dec 29 03:15:46 2009 @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// #include "llvm/Analysis/DebugInfo.h" +#include "llvm/Target/TargetMachine.h" // FIXME: LAYERING VIOLATION! #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Intrinsics.h" @@ -34,7 +35,7 @@ /// ValidDebugInfo - Return true if V represents valid debug info value. /// FIXME : Add DIDescriptor.isValid() -bool DIDescriptor::ValidDebugInfo(MDNode *N, CodeGenOpt::Level OptLevel) { +bool DIDescriptor::ValidDebugInfo(MDNode *N, unsigned OptLevel) { if (!N) return false; @@ -1353,7 +1354,7 @@ bool getLocationInfo(const Value *V, std::string &DisplayName, std::string &Type, unsigned &LineNo, std::string &File, - std::string &Dir) { + std::string &Dir) { DICompileUnit Unit; DIType TypeD; @@ -1395,37 +1396,32 @@ /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, - CodeGenOpt::Level OptLev) { + bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, unsigned OptLev) { return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev); } /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI, - CodeGenOpt::Level OptLev) { + bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI, unsigned OptLev) { return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev); } /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI, - CodeGenOpt::Level OptLev) { + bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI, unsigned OptLev) { return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev); } /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI, - CodeGenOpt::Level OptLev) { + bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI, unsigned OptLev) { return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev); } /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI, - CodeGenOpt::Level OptLev) { + bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI, unsigned OptLev) { return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev); } From sabre at nondot.org Tue Dec 29 03:22:47 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 09:22:47 -0000 Subject: [llvm-commits] [llvm] r92262 - /llvm/trunk/lib/Analysis/DebugInfo.cpp Message-ID: <200912290922.nBT9MlZx015719@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 03:22:47 2009 New Revision: 92262 URL: http://llvm.org/viewvc/llvm-project?rev=92262&view=rev Log: major cleanups, much of this file was incorrectly indented. Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=92262&r1=92261&r2=92262&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Tue Dec 29 03:22:47 2009 @@ -46,8 +46,7 @@ if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6) return false; - unsigned Tag = DI.getTag(); - switch (Tag) { + switch (DI.getTag()) { case DW_TAG_variable: assert(DIVariable(N).Verify() && "Invalid DebugInfo value"); break; @@ -128,18 +127,14 @@ /// isBasicType - Return true if the specified tag is legal for /// DIBasicType. bool DIDescriptor::isBasicType() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - return Tag == dwarf::DW_TAG_base_type; + assert(!isNull() && "Invalid descriptor!"); + return getTag() == dwarf::DW_TAG_base_type; } /// isDerivedType - Return true if the specified tag is legal for DIDerivedType. bool DIDescriptor::isDerivedType() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - switch (Tag) { + assert(!isNull() && "Invalid descriptor!"); + switch (getTag()) { case dwarf::DW_TAG_typedef: case dwarf::DW_TAG_pointer_type: case dwarf::DW_TAG_reference_type: @@ -158,10 +153,8 @@ /// isCompositeType - Return true if the specified tag is legal for /// DICompositeType. bool DIDescriptor::isCompositeType() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - switch (Tag) { + assert(!isNull() && "Invalid descriptor!"); + switch (getTag()) { case dwarf::DW_TAG_array_type: case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_union_type: @@ -177,10 +170,8 @@ /// isVariable - Return true if the specified tag is legal for DIVariable. bool DIDescriptor::isVariable() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - switch (Tag) { + assert(!isNull() && "Invalid descriptor!"); + switch (getTag()) { case dwarf::DW_TAG_auto_variable: case dwarf::DW_TAG_arg_variable: case dwarf::DW_TAG_return_variable: @@ -198,19 +189,15 @@ /// isSubprogram - Return true if the specified tag is legal for /// DISubprogram. bool DIDescriptor::isSubprogram() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - return Tag == dwarf::DW_TAG_subprogram; + assert(!isNull() && "Invalid descriptor!"); + return getTag() == dwarf::DW_TAG_subprogram; } /// isGlobalVariable - Return true if the specified tag is legal for /// DIGlobalVariable. bool DIDescriptor::isGlobalVariable() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - return Tag == dwarf::DW_TAG_variable; + assert(!isNull() && "Invalid descriptor!"); + return getTag() == dwarf::DW_TAG_variable; } /// isGlobal - Return true if the specified tag is legal for DIGlobal. @@ -221,59 +208,47 @@ /// isScope - Return true if the specified tag is one of the scope /// related tag. bool DIDescriptor::isScope() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - switch (Tag) { - case dwarf::DW_TAG_compile_unit: - case dwarf::DW_TAG_lexical_block: - case dwarf::DW_TAG_subprogram: - case dwarf::DW_TAG_namespace: - return true; - default: - break; + assert(!isNull() && "Invalid descriptor!"); + switch (getTag()) { + case dwarf::DW_TAG_compile_unit: + case dwarf::DW_TAG_lexical_block: + case dwarf::DW_TAG_subprogram: + case dwarf::DW_TAG_namespace: + return true; + default: + break; } return false; } /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit. bool DIDescriptor::isCompileUnit() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - return Tag == dwarf::DW_TAG_compile_unit; + assert(!isNull() && "Invalid descriptor!"); + return getTag() == dwarf::DW_TAG_compile_unit; } /// isNameSpace - Return true if the specified tag is DW_TAG_namespace. bool DIDescriptor::isNameSpace() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - return Tag == dwarf::DW_TAG_namespace; + assert(!isNull() && "Invalid descriptor!"); + return getTag() == dwarf::DW_TAG_namespace; } /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block. bool DIDescriptor::isLexicalBlock() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - return Tag == dwarf::DW_TAG_lexical_block; + assert(!isNull() && "Invalid descriptor!"); + return getTag() == dwarf::DW_TAG_lexical_block; } /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type. bool DIDescriptor::isSubrange() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - return Tag == dwarf::DW_TAG_subrange_type; + assert(!isNull() && "Invalid descriptor!"); + return getTag() == dwarf::DW_TAG_subrange_type; } /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator. bool DIDescriptor::isEnumerator() const { - assert (!isNull() && "Invalid descriptor!"); - unsigned Tag = getTag(); - - return Tag == dwarf::DW_TAG_enumerator; + assert(!isNull() && "Invalid descriptor!"); + return getTag() == dwarf::DW_TAG_enumerator; } //===----------------------------------------------------------------------===// @@ -288,7 +263,7 @@ } unsigned DIArray::getNumElements() const { - assert (DbgNode && "Invalid DIArray"); + assert(DbgNode && "Invalid DIArray"); return DbgNode->getNumElements(); } @@ -299,7 +274,7 @@ if (isNull()) return; - assert (!D.isNull() && "Can not replace with null"); + assert(!D.isNull() && "Can not replace with null"); // Since we use a TrackingVH for the node, its easy for clients to manufacture // legitimate situations where they want to replaceAllUsesWith() on something @@ -432,7 +407,7 @@ /// describes - Return true if this subprogram provides debugging /// information for the function F. bool DISubprogram::describes(const Function *F) { - assert (F && "Invalid function"); + assert(F && "Invalid function"); StringRef Name = getLinkageName(); if (Name.empty()) Name = getName(); @@ -444,28 +419,26 @@ StringRef DIScope::getFilename() const { if (isLexicalBlock()) return DILexicalBlock(DbgNode).getFilename(); - else if (isSubprogram()) + if (isSubprogram()) return DISubprogram(DbgNode).getFilename(); - else if (isCompileUnit()) + if (isCompileUnit()) return DICompileUnit(DbgNode).getFilename(); - else if (isNameSpace()) + if (isNameSpace()) return DINameSpace(DbgNode).getFilename(); - else - assert (0 && "Invalid DIScope!"); + assert(0 && "Invalid DIScope!"); return StringRef(); } StringRef DIScope::getDirectory() const { if (isLexicalBlock()) return DILexicalBlock(DbgNode).getDirectory(); - else if (isSubprogram()) + if (isSubprogram()) return DISubprogram(DbgNode).getDirectory(); - else if (isCompileUnit()) + if (isCompileUnit()) return DICompileUnit(DbgNode).getDirectory(); - else if (isNameSpace()) + if (isNameSpace()) return DINameSpace(DbgNode).getDirectory(); - else - assert (0 && "Invalid DIScope!"); + assert(0 && "Invalid DIScope!"); return StringRef(); } @@ -1264,270 +1237,267 @@ return true; } -namespace llvm { - /// findStopPoint - Find the stoppoint coressponding to this instruction, that - /// is the stoppoint that dominates this instruction. - const DbgStopPointInst *findStopPoint(const Instruction *Inst) { - if (const DbgStopPointInst *DSI = dyn_cast(Inst)) - return DSI; - - const BasicBlock *BB = Inst->getParent(); - BasicBlock::const_iterator I = Inst, B; - while (BB) { - B = BB->begin(); - - // A BB consisting only of a terminator can't have a stoppoint. - while (I != B) { - --I; - if (const DbgStopPointInst *DSI = dyn_cast(I)) - return DSI; - } - - // This BB didn't have a stoppoint: if there is only one predecessor, look - // for a stoppoint there. We could use getIDom(), but that would require - // dominator info. - BB = I->getParent()->getUniquePredecessor(); - if (BB) - I = BB->getTerminator(); - } - - return 0; - } - - /// findBBStopPoint - Find the stoppoint corresponding to first real - /// (non-debug intrinsic) instruction in this Basic Block, and return the - /// stoppoint for it. - const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) { - for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) +/// findStopPoint - Find the stoppoint coressponding to this instruction, that +/// is the stoppoint that dominates this instruction. +const DbgStopPointInst *llvm::findStopPoint(const Instruction *Inst) { + if (const DbgStopPointInst *DSI = dyn_cast(Inst)) + return DSI; + + const BasicBlock *BB = Inst->getParent(); + BasicBlock::const_iterator I = Inst, B; + while (BB) { + B = BB->begin(); + + // A BB consisting only of a terminator can't have a stoppoint. + while (I != B) { + --I; if (const DbgStopPointInst *DSI = dyn_cast(I)) return DSI; + } - // Fallback to looking for stoppoint of unique predecessor. Useful if this - // BB contains no stoppoints, but unique predecessor does. - BB = BB->getUniquePredecessor(); + // This BB didn't have a stoppoint: if there is only one predecessor, look + // for a stoppoint there. We could use getIDom(), but that would require + // dominator info. + BB = I->getParent()->getUniquePredecessor(); if (BB) - return findStopPoint(BB->getTerminator()); - - return 0; + I = BB->getTerminator(); } - Value *findDbgGlobalDeclare(GlobalVariable *V) { - const Module *M = V->getParent(); - NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"); - if (!NMD) - return 0; - - for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { - DIGlobalVariable DIG(cast_or_null(NMD->getElement(i))); - if (DIG.isNull()) - continue; - if (DIG.getGlobal() == V) - return DIG.getNode(); - } - return 0; - } - - /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any. - /// It looks through pointer casts too. - const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) { - if (stripCasts) { - V = V->stripPointerCasts(); - - // Look for the bitcast. - for (Value::use_const_iterator I = V->use_begin(), E =V->use_end(); - I != E; ++I) - if (isa(I)) { - const DbgDeclareInst *DDI = findDbgDeclare(*I, false); - if (DDI) return DDI; - } - return 0; - } - - // Find llvm.dbg.declare among uses of the instruction. - for (Value::use_const_iterator I = V->use_begin(), E =V->use_end(); - I != E; ++I) - if (const DbgDeclareInst *DDI = dyn_cast(I)) - return DDI; + return 0; +} - return 0; - } +/// findBBStopPoint - Find the stoppoint corresponding to first real +/// (non-debug intrinsic) instruction in this Basic Block, and return the +/// stoppoint for it. +const DbgStopPointInst *llvm::findBBStopPoint(const BasicBlock *BB) { + for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) + if (const DbgStopPointInst *DSI = dyn_cast(I)) + return DSI; -bool getLocationInfo(const Value *V, std::string &DisplayName, - std::string &Type, unsigned &LineNo, std::string &File, - std::string &Dir) { - DICompileUnit Unit; - DIType TypeD; - - if (GlobalVariable *GV = dyn_cast(const_cast(V))) { - Value *DIGV = findDbgGlobalDeclare(GV); - if (!DIGV) return false; - DIGlobalVariable Var(cast(DIGV)); - - StringRef D = Var.getDisplayName(); - if (!D.empty()) - DisplayName = D; - LineNo = Var.getLineNumber(); - Unit = Var.getCompileUnit(); - TypeD = Var.getType(); - } else { - const DbgDeclareInst *DDI = findDbgDeclare(V); - if (!DDI) return false; - DIVariable Var(cast(DDI->getVariable())); - - StringRef D = Var.getName(); - if (!D.empty()) - DisplayName = D; - LineNo = Var.getLineNumber(); - Unit = Var.getCompileUnit(); - TypeD = Var.getType(); - } + // Fallback to looking for stoppoint of unique predecessor. Useful if this + // BB contains no stoppoints, but unique predecessor does. + BB = BB->getUniquePredecessor(); + if (BB) + return findStopPoint(BB->getTerminator()); - StringRef T = TypeD.getName(); - if (!T.empty()) - Type = T; - StringRef F = Unit.getFilename(); - if (!F.empty()) - File = F; - StringRef D = Unit.getDirectory(); - if (!D.empty()) - Dir = D; - return true; - } + return 0; +} - /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev); - } +Value *llvm::findDbgGlobalDeclare(GlobalVariable *V) { + const Module *M = V->getParent(); + NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"); + if (!NMD) + return 0; - /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev); + for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { + DIGlobalVariable DIG(cast_or_null(NMD->getElement(i))); + if (DIG.isNull()) + continue; + if (DIG.getGlobal() == V) + return DIG.getNode(); } + return 0; +} - /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev); - } +/// Finds the llvm.dbg.declare intrinsic corresponding to this value if any. +/// It looks through pointer casts too. +const DbgDeclareInst *llvm::findDbgDeclare(const Value *V, bool stripCasts) { + if (stripCasts) { + V = V->stripPointerCasts(); - /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev); + // Look for the bitcast. + for (Value::use_const_iterator I = V->use_begin(), E =V->use_end(); + I != E; ++I) + if (isa(I)) { + const DbgDeclareInst *DDI = findDbgDeclare(*I, false); + if (DDI) return DDI; + } + return 0; } + // Find llvm.dbg.declare among uses of the instruction. + for (Value::use_const_iterator I = V->use_begin(), E =V->use_end(); + I != E; ++I) + if (const DbgDeclareInst *DDI = dyn_cast(I)) + return DDI; - /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev); - } - - /// ExtractDebugLocation - Extract debug location information - /// from llvm.dbg.stoppoint intrinsic. - DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI, - DebugLocTracker &DebugLocInfo) { - DebugLoc DL; - Value *Context = SPI.getContext(); - - // If this location is already tracked then use it. - DebugLocTuple Tuple(cast(Context), NULL, SPI.getLine(), - SPI.getColumn()); - DenseMap::iterator II - = DebugLocInfo.DebugIdMap.find(Tuple); - if (II != DebugLocInfo.DebugIdMap.end()) - return DebugLoc::get(II->second); - - // Add a new location entry. - unsigned Id = DebugLocInfo.DebugLocations.size(); - DebugLocInfo.DebugLocations.push_back(Tuple); - DebugLocInfo.DebugIdMap[Tuple] = Id; + return 0; +} - return DebugLoc::get(Id); - } +bool llvm::getLocationInfo(const Value *V, std::string &DisplayName, + std::string &Type, unsigned &LineNo, + std::string &File, std::string &Dir) { + DICompileUnit Unit; + DIType TypeD; + + if (GlobalVariable *GV = dyn_cast(const_cast(V))) { + Value *DIGV = findDbgGlobalDeclare(GV); + if (!DIGV) return false; + DIGlobalVariable Var(cast(DIGV)); - /// ExtractDebugLocation - Extract debug location information - /// from DILocation. - DebugLoc ExtractDebugLocation(DILocation &Loc, - DebugLocTracker &DebugLocInfo) { - DebugLoc DL; - MDNode *Context = Loc.getScope().getNode(); - MDNode *InlinedLoc = NULL; - if (!Loc.getOrigLocation().isNull()) - InlinedLoc = Loc.getOrigLocation().getNode(); - // If this location is already tracked then use it. - DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(), - Loc.getColumnNumber()); - DenseMap::iterator II - = DebugLocInfo.DebugIdMap.find(Tuple); - if (II != DebugLocInfo.DebugIdMap.end()) - return DebugLoc::get(II->second); - - // Add a new location entry. - unsigned Id = DebugLocInfo.DebugLocations.size(); - DebugLocInfo.DebugLocations.push_back(Tuple); - DebugLocInfo.DebugIdMap[Tuple] = Id; + StringRef D = Var.getDisplayName(); + if (!D.empty()) + DisplayName = D; + LineNo = Var.getLineNumber(); + Unit = Var.getCompileUnit(); + TypeD = Var.getType(); + } else { + const DbgDeclareInst *DDI = findDbgDeclare(V); + if (!DDI) return false; + DIVariable Var(cast(DDI->getVariable())); - return DebugLoc::get(Id); + StringRef D = Var.getName(); + if (!D.empty()) + DisplayName = D; + LineNo = Var.getLineNumber(); + Unit = Var.getCompileUnit(); + TypeD = Var.getType(); } - /// ExtractDebugLocation - Extract debug location information - /// from llvm.dbg.func_start intrinsic. - DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI, - DebugLocTracker &DebugLocInfo) { - DebugLoc DL; - Value *SP = FSI.getSubprogram(); - - DISubprogram Subprogram(cast(SP)); - unsigned Line = Subprogram.getLineNumber(); - DICompileUnit CU(Subprogram.getCompileUnit()); - - // If this location is already tracked then use it. - DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0); - DenseMap::iterator II - = DebugLocInfo.DebugIdMap.find(Tuple); - if (II != DebugLocInfo.DebugIdMap.end()) - return DebugLoc::get(II->second); - - // Add a new location entry. - unsigned Id = DebugLocInfo.DebugLocations.size(); - DebugLocInfo.DebugLocations.push_back(Tuple); - DebugLocInfo.DebugIdMap[Tuple] = Id; - - return DebugLoc::get(Id); - } + StringRef T = TypeD.getName(); + if (!T.empty()) + Type = T; + StringRef F = Unit.getFilename(); + if (!F.empty()) + File = F; + StringRef D = Unit.getDirectory(); + if (!D.empty()) + Dir = D; + return true; +} - /// getDISubprogram - Find subprogram that is enclosing this scope. - DISubprogram getDISubprogram(MDNode *Scope) { - DIDescriptor D(Scope); - if (D.isNull()) - return DISubprogram(); - - if (D.isCompileUnit()) - return DISubprogram(); - - if (D.isSubprogram()) - return DISubprogram(Scope); - - if (D.isLexicalBlock()) - return getDISubprogram(DILexicalBlock(Scope).getContext().getNode()); - +/// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug +/// info intrinsic. +bool llvm::isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, unsigned OptLev) { + return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev); +} + +/// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug +/// info intrinsic. +bool llvm::isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI, unsigned OptLev) { + return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev); +} + +/// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug +/// info intrinsic. +bool llvm::isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI, unsigned OptLev) { + return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev); +} + +/// isValidDebugInfoIntrinsic - Return true if REI is a valid debug +/// info intrinsic. +bool llvm::isValidDebugInfoIntrinsic(DbgRegionEndInst &REI, unsigned OptLev) { + return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev); +} + +/// isValidDebugInfoIntrinsic - Return true if DI is a valid debug +/// info intrinsic. +bool llvm::isValidDebugInfoIntrinsic(DbgDeclareInst &DI, unsigned OptLev) { + return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev); +} + +/// ExtractDebugLocation - Extract debug location information +/// from llvm.dbg.stoppoint intrinsic. +DebugLoc llvm::ExtractDebugLocation(DbgStopPointInst &SPI, + DebugLocTracker &DebugLocInfo) { + DebugLoc DL; + Value *Context = SPI.getContext(); + + // If this location is already tracked then use it. + DebugLocTuple Tuple(cast(Context), NULL, SPI.getLine(), + SPI.getColumn()); + DenseMap::iterator II + = DebugLocInfo.DebugIdMap.find(Tuple); + if (II != DebugLocInfo.DebugIdMap.end()) + return DebugLoc::get(II->second); + + // Add a new location entry. + unsigned Id = DebugLocInfo.DebugLocations.size(); + DebugLocInfo.DebugLocations.push_back(Tuple); + DebugLocInfo.DebugIdMap[Tuple] = Id; + + return DebugLoc::get(Id); +} + +/// ExtractDebugLocation - Extract debug location information +/// from DILocation. +DebugLoc llvm::ExtractDebugLocation(DILocation &Loc, + DebugLocTracker &DebugLocInfo) { + DebugLoc DL; + MDNode *Context = Loc.getScope().getNode(); + MDNode *InlinedLoc = NULL; + if (!Loc.getOrigLocation().isNull()) + InlinedLoc = Loc.getOrigLocation().getNode(); + // If this location is already tracked then use it. + DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(), + Loc.getColumnNumber()); + DenseMap::iterator II + = DebugLocInfo.DebugIdMap.find(Tuple); + if (II != DebugLocInfo.DebugIdMap.end()) + return DebugLoc::get(II->second); + + // Add a new location entry. + unsigned Id = DebugLocInfo.DebugLocations.size(); + DebugLocInfo.DebugLocations.push_back(Tuple); + DebugLocInfo.DebugIdMap[Tuple] = Id; + + return DebugLoc::get(Id); +} + +/// ExtractDebugLocation - Extract debug location information +/// from llvm.dbg.func_start intrinsic. +DebugLoc llvm::ExtractDebugLocation(DbgFuncStartInst &FSI, + DebugLocTracker &DebugLocInfo) { + DebugLoc DL; + Value *SP = FSI.getSubprogram(); + + DISubprogram Subprogram(cast(SP)); + unsigned Line = Subprogram.getLineNumber(); + DICompileUnit CU(Subprogram.getCompileUnit()); + + // If this location is already tracked then use it. + DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0); + DenseMap::iterator II + = DebugLocInfo.DebugIdMap.find(Tuple); + if (II != DebugLocInfo.DebugIdMap.end()) + return DebugLoc::get(II->second); + + // Add a new location entry. + unsigned Id = DebugLocInfo.DebugLocations.size(); + DebugLocInfo.DebugLocations.push_back(Tuple); + DebugLocInfo.DebugIdMap[Tuple] = Id; + + return DebugLoc::get(Id); +} + +/// getDISubprogram - Find subprogram that is enclosing this scope. +DISubprogram llvm::getDISubprogram(MDNode *Scope) { + DIDescriptor D(Scope); + if (D.isNull()) return DISubprogram(); - } + + if (D.isCompileUnit()) + return DISubprogram(); + + if (D.isSubprogram()) + return DISubprogram(Scope); + + if (D.isLexicalBlock()) + return getDISubprogram(DILexicalBlock(Scope).getContext().getNode()); + + return DISubprogram(); +} - /// getDICompositeType - Find underlying composite type. - DICompositeType getDICompositeType(DIType T) { - if (T.isNull()) - return DICompositeType(); - - if (T.isCompositeType()) - return DICompositeType(T.getNode()); - - if (T.isDerivedType()) - return getDICompositeType(DIDerivedType(T.getNode()).getTypeDerivedFrom()); - +/// getDICompositeType - Find underlying composite type. +DICompositeType llvm::getDICompositeType(DIType T) { + if (T.isNull()) return DICompositeType(); - } + + if (T.isCompositeType()) + return DICompositeType(T.getNode()); + + if (T.isDerivedType()) + return getDICompositeType(DIDerivedType(T.getNode()).getTypeDerivedFrom()); + + return DICompositeType(); } From sabre at nondot.org Tue Dec 29 03:32:20 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 09:32:20 -0000 Subject: [llvm-commits] [llvm] r92263 - in /llvm/trunk: include/llvm/Analysis/DebugInfo.h lib/Analysis/DebugInfo.cpp lib/CodeGen/SelectionDAG/FastISel.cpp lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Message-ID: <200912290932.nBT9WKQD016008@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 03:32:19 2009 New Revision: 92263 URL: http://llvm.org/viewvc/llvm-project?rev=92263&view=rev Log: remove a bunch of unneeded functions. Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h llvm/trunk/lib/Analysis/DebugInfo.cpp llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Analysis/DebugInfo.h?rev=92263&r1=92262&r2=92263&view=diff ============================================================================== --- llvm/trunk/include/llvm/Analysis/DebugInfo.h (original) +++ llvm/trunk/include/llvm/Analysis/DebugInfo.h Tue Dec 29 03:32:19 2009 @@ -688,26 +688,6 @@ std::string &Type, unsigned &LineNo, std::string &File, std::string &Dir); - /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, unsigned OptLev); - - /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI, unsigned OptLev); - - /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI, unsigned OptLev); - - /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI, unsigned OptLev); - - /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug - /// info intrinsic. - bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI, unsigned OptLev); - /// ExtractDebugLocation - Extract debug location information /// from llvm.dbg.stoppoint intrinsic. DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI, @@ -730,7 +710,6 @@ DICompositeType getDICompositeType(DIType T); class DebugInfoFinder { - public: /// processModule - Process entire module and collect debug info /// anchors. Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=92263&r1=92262&r2=92263&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Tue Dec 29 03:32:19 2009 @@ -1366,36 +1366,6 @@ return true; } -/// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug -/// info intrinsic. -bool llvm::isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev); -} - -/// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug -/// info intrinsic. -bool llvm::isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev); -} - -/// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug -/// info intrinsic. -bool llvm::isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev); -} - -/// isValidDebugInfoIntrinsic - Return true if REI is a valid debug -/// info intrinsic. -bool llvm::isValidDebugInfoIntrinsic(DbgRegionEndInst &REI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev); -} - -/// isValidDebugInfoIntrinsic - Return true if DI is a valid debug -/// info intrinsic. -bool llvm::isValidDebugInfoIntrinsic(DbgDeclareInst &DI, unsigned OptLev) { - return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev); -} - /// ExtractDebugLocation - Extract debug location information /// from llvm.dbg.stoppoint intrinsic. DebugLoc llvm::ExtractDebugLocation(DbgStopPointInst &SPI, Modified: llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp?rev=92263&r1=92262&r2=92263&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp Tue Dec 29 03:32:19 2009 @@ -333,7 +333,7 @@ return true; case Intrinsic::dbg_declare: { DbgDeclareInst *DI = cast(I); - if (!isValidDebugInfoIntrinsic(*DI, CodeGenOpt::None) || !DW + if (!DIDescriptor::ValidDebugInfo(DI->getVariable(), CodeGenOpt::None)||!DW || !DW->ShouldEmitDwarfDebug()) return true; Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp?rev=92263&r1=92262&r2=92263&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Tue Dec 29 03:32:19 2009 @@ -4361,7 +4361,7 @@ if (!DW) return 0; DbgDeclareInst &DI = cast(I); - if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None)) + if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None)) return 0; MDNode *Variable = DI.getVariable(); From benny.kra at googlemail.com Tue Dec 29 05:04:53 2009 From: benny.kra at googlemail.com (Benjamin Kramer) Date: Tue, 29 Dec 2009 11:04:53 -0000 Subject: [llvm-commits] [llvm] r92264 - /llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Message-ID: <200912291104.nBTB4rgl019443@zion.cs.uiuc.edu> Author: d0k Date: Tue Dec 29 05:04:52 2009 New Revision: 92264 URL: http://llvm.org/viewvc/llvm-project?rev=92264&view=rev Log: Use an array instead of a SmallVector. Modified: llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Modified: llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp?rev=92264&r1=92263&r2=92264&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp (original) +++ llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Tue Dec 29 05:04:52 2009 @@ -359,12 +359,13 @@ if (!OrigLocation.isNull()) NewLoc = UpdateInlinedAtInfo(OrigLocation.getNode(), TheCallMD); - SmallVector MDVs; - MDVs.push_back(InsnMD->getElement(0)); // Line - MDVs.push_back(InsnMD->getElement(1)); // Col - MDVs.push_back(InsnMD->getElement(2)); // Scope - MDVs.push_back(NewLoc); - return MDNode::get(InsnMD->getContext(), MDVs.data(), MDVs.size()); + Value *MDVs[] = { + InsnMD->getElement(0), // Line + InsnMD->getElement(1), // Col + InsnMD->getElement(2), // Scope + NewLoc + }; + return MDNode::get(InsnMD->getContext(), MDVs, 4); } /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto, @@ -422,7 +423,6 @@ unsigned DbgKind = OldFunc->getContext().getMDKindID("dbg"); MDNode *TheCallMD = NULL; - SmallVector MDVs; if (TheCall && TheCall->hasMetadata()) TheCallMD = TheCall->getMetadata(DbgKind); From benny.kra at googlemail.com Tue Dec 29 10:57:27 2009 From: benny.kra at googlemail.com (Benjamin Kramer) Date: Tue, 29 Dec 2009 16:57:27 -0000 Subject: [llvm-commits] [llvm] r92265 - /llvm/trunk/lib/Target/X86/X86ISelLowering.cpp Message-ID: <200912291657.nBTGvRLm032095@zion.cs.uiuc.edu> Author: d0k Date: Tue Dec 29 10:57:26 2009 New Revision: 92265 URL: http://llvm.org/viewvc/llvm-project?rev=92265&view=rev Log: Replace a few more SmallVectors with arrays. Modified: llvm/trunk/lib/Target/X86/X86ISelLowering.cpp Modified: llvm/trunk/lib/Target/X86/X86ISelLowering.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/X86/X86ISelLowering.cpp?rev=92265&r1=92264&r2=92265&view=diff ============================================================================== --- llvm/trunk/lib/Target/X86/X86ISelLowering.cpp (original) +++ llvm/trunk/lib/Target/X86/X86ISelLowering.cpp Tue Dec 29 10:57:26 2009 @@ -5128,12 +5128,9 @@ Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag); else Tys = DAG.getVTList(Op.getValueType(), MVT::Other); - SmallVector Ops; - Ops.push_back(Chain); - Ops.push_back(StackSlot); - Ops.push_back(DAG.getValueType(SrcVT)); + SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl, - Tys, &Ops[0], Ops.size()); + Tys, Ops, array_lengthof(Ops)); if (useSSE) { Chain = Result.getValue(1); @@ -5146,13 +5143,10 @@ int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false); SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); Tys = DAG.getVTList(MVT::Other); - SmallVector Ops; - Ops.push_back(Chain); - Ops.push_back(Result); - Ops.push_back(StackSlot); - Ops.push_back(DAG.getValueType(Op.getValueType())); - Ops.push_back(InFlag); - Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size()); + SDValue Ops[] = { + Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag + }; + Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops)); Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot, PseudoSourceValue::getFixedStack(SSFI), 0); } @@ -5947,14 +5941,10 @@ } SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag); - SmallVector Ops; // X86ISD::CMOV means set the result (which is operand 1) to the RHS if // condition is true. - Ops.push_back(Op.getOperand(2)); - Ops.push_back(Op.getOperand(1)); - Ops.push_back(CC); - Ops.push_back(Cond); - return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size()); + SDValue Ops[] = { Op.getOperand(2), Op.getOperand(1), CC, Cond }; + return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops)); } // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or @@ -6265,11 +6255,8 @@ InFlag = Chain.getValue(1); SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag); - SmallVector Ops; - Ops.push_back(Chain); - Ops.push_back(DAG.getValueType(AVT)); - Ops.push_back(InFlag); - Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size()); + SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag }; + Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops)); if (TwoRepStos) { InFlag = Chain.getValue(1); @@ -6282,11 +6269,8 @@ Left, InFlag); InFlag = Chain.getValue(1); Tys = DAG.getVTList(MVT::Other, MVT::Flag); - Ops.clear(); - Ops.push_back(Chain); - Ops.push_back(DAG.getValueType(MVT::i8)); - Ops.push_back(InFlag); - Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size()); + SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag }; + Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops)); } else if (BytesLeft) { // Handle the last 1 - 7 bytes. unsigned Offset = SizeVal - BytesLeft; @@ -6350,11 +6334,9 @@ InFlag = Chain.getValue(1); SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag); - SmallVector Ops; - Ops.push_back(Chain); - Ops.push_back(DAG.getValueType(AVT)); - Ops.push_back(InFlag); - SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size()); + SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag }; + SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops, + array_lengthof(Ops)); SmallVector Results; Results.push_back(RepMovs); @@ -6978,12 +6960,13 @@ Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); // If src is zero (i.e. bsr sets ZF), returns NumBits. - SmallVector Ops; - Ops.push_back(Op); - Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT)); - Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8)); - Ops.push_back(Op.getValue(1)); - Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4); + SDValue Ops[] = { + Op, + DAG.getConstant(NumBits+NumBits-1, OpVT), + DAG.getConstant(X86::COND_E, MVT::i8), + Op.getValue(1) + }; + Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); // Finally xor with NumBits-1. Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); @@ -7010,12 +6993,13 @@ Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); // If src is zero (i.e. bsf sets ZF), returns NumBits. - SmallVector Ops; - Ops.push_back(Op); - Ops.push_back(DAG.getConstant(NumBits, OpVT)); - Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8)); - Ops.push_back(Op.getValue(1)); - Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4); + SDValue Ops[] = { + Op, + DAG.getConstant(NumBits, OpVT), + DAG.getConstant(X86::COND_E, MVT::i8), + Op.getValue(1) + }; + Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); if (VT == MVT::i8) Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); From sabre at nondot.org Tue Dec 29 15:09:58 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 21:09:58 -0000 Subject: [llvm-commits] [llvm] r92267 - /llvm/trunk/lib/Support/Dwarf.cpp Message-ID: <200912292109.nBTL9wMT008482@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 15:09:57 2009 New Revision: 92267 URL: http://llvm.org/viewvc/llvm-project?rev=92267&view=rev Log: fix indentation, fit in 80 cols. Modified: llvm/trunk/lib/Support/Dwarf.cpp Modified: llvm/trunk/lib/Support/Dwarf.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Support/Dwarf.cpp?rev=92267&r1=92266&r2=92267&view=diff ============================================================================== --- llvm/trunk/lib/Support/Dwarf.cpp (original) +++ llvm/trunk/lib/Support/Dwarf.cpp Tue Dec 29 15:09:57 2009 @@ -21,65 +21,65 @@ /// const char *llvm::dwarf::TagString(unsigned Tag) { switch (Tag) { - case DW_TAG_array_type: return "DW_TAG_array_type"; - case DW_TAG_class_type: return "DW_TAG_class_type"; - case DW_TAG_entry_point: return "DW_TAG_entry_point"; - case DW_TAG_enumeration_type: return "DW_TAG_enumeration_type"; - case DW_TAG_formal_parameter: return "DW_TAG_formal_parameter"; - case DW_TAG_imported_declaration: return "DW_TAG_imported_declaration"; - case DW_TAG_label: return "DW_TAG_label"; - case DW_TAG_lexical_block: return "DW_TAG_lexical_block"; - case DW_TAG_member: return "DW_TAG_member"; - case DW_TAG_pointer_type: return "DW_TAG_pointer_type"; - case DW_TAG_reference_type: return "DW_TAG_reference_type"; - case DW_TAG_compile_unit: return "DW_TAG_compile_unit"; - case DW_TAG_string_type: return "DW_TAG_string_type"; - case DW_TAG_structure_type: return "DW_TAG_structure_type"; - case DW_TAG_subroutine_type: return "DW_TAG_subroutine_type"; - case DW_TAG_typedef: return "DW_TAG_typedef"; - case DW_TAG_union_type: return "DW_TAG_union_type"; - case DW_TAG_unspecified_parameters: return "DW_TAG_unspecified_parameters"; - case DW_TAG_variant: return "DW_TAG_variant"; - case DW_TAG_common_block: return "DW_TAG_common_block"; - case DW_TAG_common_inclusion: return "DW_TAG_common_inclusion"; - case DW_TAG_inheritance: return "DW_TAG_inheritance"; - case DW_TAG_inlined_subroutine: return "DW_TAG_inlined_subroutine"; - case DW_TAG_module: return "DW_TAG_module"; - case DW_TAG_ptr_to_member_type: return "DW_TAG_ptr_to_member_type"; - case DW_TAG_set_type: return "DW_TAG_set_type"; - case DW_TAG_subrange_type: return "DW_TAG_subrange_type"; - case DW_TAG_with_stmt: return "DW_TAG_with_stmt"; - case DW_TAG_access_declaration: return "DW_TAG_access_declaration"; - case DW_TAG_base_type: return "DW_TAG_base_type"; - case DW_TAG_catch_block: return "DW_TAG_catch_block"; - case DW_TAG_const_type: return "DW_TAG_const_type"; - case DW_TAG_constant: return "DW_TAG_constant"; - case DW_TAG_enumerator: return "DW_TAG_enumerator"; - case DW_TAG_file_type: return "DW_TAG_file_type"; - case DW_TAG_friend: return "DW_TAG_friend"; - case DW_TAG_namelist: return "DW_TAG_namelist"; - case DW_TAG_namelist_item: return "DW_TAG_namelist_item"; - case DW_TAG_packed_type: return "DW_TAG_packed_type"; - case DW_TAG_subprogram: return "DW_TAG_subprogram"; - case DW_TAG_template_type_parameter: return "DW_TAG_template_type_parameter"; - case DW_TAG_template_value_parameter: return "DW_TAG_template_value_parameter"; - case DW_TAG_thrown_type: return "DW_TAG_thrown_type"; - case DW_TAG_try_block: return "DW_TAG_try_block"; - case DW_TAG_variant_part: return "DW_TAG_variant_part"; - case DW_TAG_variable: return "DW_TAG_variable"; - case DW_TAG_volatile_type: return "DW_TAG_volatile_type"; - case DW_TAG_dwarf_procedure: return "DW_TAG_dwarf_procedure"; - case DW_TAG_restrict_type: return "DW_TAG_restrict_type"; - case DW_TAG_interface_type: return "DW_TAG_interface_type"; - case DW_TAG_namespace: return "DW_TAG_namespace"; - case DW_TAG_imported_module: return "DW_TAG_imported_module"; - case DW_TAG_unspecified_type: return "DW_TAG_unspecified_type"; - case DW_TAG_partial_unit: return "DW_TAG_partial_unit"; - case DW_TAG_imported_unit: return "DW_TAG_imported_unit"; - case DW_TAG_condition: return "DW_TAG_condition"; - case DW_TAG_shared_type: return "DW_TAG_shared_type"; - case DW_TAG_lo_user: return "DW_TAG_lo_user"; - case DW_TAG_hi_user: return "DW_TAG_hi_user"; + case DW_TAG_array_type: return "DW_TAG_array_type"; + case DW_TAG_class_type: return "DW_TAG_class_type"; + case DW_TAG_entry_point: return "DW_TAG_entry_point"; + case DW_TAG_enumeration_type: return "DW_TAG_enumeration_type"; + case DW_TAG_formal_parameter: return "DW_TAG_formal_parameter"; + case DW_TAG_imported_declaration: return "DW_TAG_imported_declaration"; + case DW_TAG_label: return "DW_TAG_label"; + case DW_TAG_lexical_block: return "DW_TAG_lexical_block"; + case DW_TAG_member: return "DW_TAG_member"; + case DW_TAG_pointer_type: return "DW_TAG_pointer_type"; + case DW_TAG_reference_type: return "DW_TAG_reference_type"; + case DW_TAG_compile_unit: return "DW_TAG_compile_unit"; + case DW_TAG_string_type: return "DW_TAG_string_type"; + case DW_TAG_structure_type: return "DW_TAG_structure_type"; + case DW_TAG_subroutine_type: return "DW_TAG_subroutine_type"; + case DW_TAG_typedef: return "DW_TAG_typedef"; + case DW_TAG_union_type: return "DW_TAG_union_type"; + case DW_TAG_unspecified_parameters: return "DW_TAG_unspecified_parameters"; + case DW_TAG_variant: return "DW_TAG_variant"; + case DW_TAG_common_block: return "DW_TAG_common_block"; + case DW_TAG_common_inclusion: return "DW_TAG_common_inclusion"; + case DW_TAG_inheritance: return "DW_TAG_inheritance"; + case DW_TAG_inlined_subroutine: return "DW_TAG_inlined_subroutine"; + case DW_TAG_module: return "DW_TAG_module"; + case DW_TAG_ptr_to_member_type: return "DW_TAG_ptr_to_member_type"; + case DW_TAG_set_type: return "DW_TAG_set_type"; + case DW_TAG_subrange_type: return "DW_TAG_subrange_type"; + case DW_TAG_with_stmt: return "DW_TAG_with_stmt"; + case DW_TAG_access_declaration: return "DW_TAG_access_declaration"; + case DW_TAG_base_type: return "DW_TAG_base_type"; + case DW_TAG_catch_block: return "DW_TAG_catch_block"; + case DW_TAG_const_type: return "DW_TAG_const_type"; + case DW_TAG_constant: return "DW_TAG_constant"; + case DW_TAG_enumerator: return "DW_TAG_enumerator"; + case DW_TAG_file_type: return "DW_TAG_file_type"; + case DW_TAG_friend: return "DW_TAG_friend"; + case DW_TAG_namelist: return "DW_TAG_namelist"; + case DW_TAG_namelist_item: return "DW_TAG_namelist_item"; + case DW_TAG_packed_type: return "DW_TAG_packed_type"; + case DW_TAG_subprogram: return "DW_TAG_subprogram"; + case DW_TAG_template_type_parameter: return "DW_TAG_template_type_parameter"; + case DW_TAG_template_value_parameter:return "DW_TAG_template_value_parameter"; + case DW_TAG_thrown_type: return "DW_TAG_thrown_type"; + case DW_TAG_try_block: return "DW_TAG_try_block"; + case DW_TAG_variant_part: return "DW_TAG_variant_part"; + case DW_TAG_variable: return "DW_TAG_variable"; + case DW_TAG_volatile_type: return "DW_TAG_volatile_type"; + case DW_TAG_dwarf_procedure: return "DW_TAG_dwarf_procedure"; + case DW_TAG_restrict_type: return "DW_TAG_restrict_type"; + case DW_TAG_interface_type: return "DW_TAG_interface_type"; + case DW_TAG_namespace: return "DW_TAG_namespace"; + case DW_TAG_imported_module: return "DW_TAG_imported_module"; + case DW_TAG_unspecified_type: return "DW_TAG_unspecified_type"; + case DW_TAG_partial_unit: return "DW_TAG_partial_unit"; + case DW_TAG_imported_unit: return "DW_TAG_imported_unit"; + case DW_TAG_condition: return "DW_TAG_condition"; + case DW_TAG_shared_type: return "DW_TAG_shared_type"; + case DW_TAG_lo_user: return "DW_TAG_lo_user"; + case DW_TAG_hi_user: return "DW_TAG_hi_user"; } llvm_unreachable("Unknown Dwarf Tag"); return ""; @@ -100,108 +100,108 @@ /// const char *llvm::dwarf::AttributeString(unsigned Attribute) { switch (Attribute) { - case DW_AT_sibling: return "DW_AT_sibling"; - case DW_AT_location: return "DW_AT_location"; - case DW_AT_name: return "DW_AT_name"; - case DW_AT_ordering: return "DW_AT_ordering"; - case DW_AT_byte_size: return "DW_AT_byte_size"; - case DW_AT_bit_offset: return "DW_AT_bit_offset"; - case DW_AT_bit_size: return "DW_AT_bit_size"; - case DW_AT_stmt_list: return "DW_AT_stmt_list"; - case DW_AT_low_pc: return "DW_AT_low_pc"; - case DW_AT_high_pc: return "DW_AT_high_pc"; - case DW_AT_language: return "DW_AT_language"; - case DW_AT_discr: return "DW_AT_discr"; - case DW_AT_discr_value: return "DW_AT_discr_value"; - case DW_AT_visibility: return "DW_AT_visibility"; - case DW_AT_import: return "DW_AT_import"; - case DW_AT_string_length: return "DW_AT_string_length"; - case DW_AT_common_reference: return "DW_AT_common_reference"; - case DW_AT_comp_dir: return "DW_AT_comp_dir"; - case DW_AT_const_value: return "DW_AT_const_value"; - case DW_AT_containing_type: return "DW_AT_containing_type"; - case DW_AT_default_value: return "DW_AT_default_value"; - case DW_AT_inline: return "DW_AT_inline"; - case DW_AT_is_optional: return "DW_AT_is_optional"; - case DW_AT_lower_bound: return "DW_AT_lower_bound"; - case DW_AT_producer: return "DW_AT_producer"; - case DW_AT_prototyped: return "DW_AT_prototyped"; - case DW_AT_return_addr: return "DW_AT_return_addr"; - case DW_AT_start_scope: return "DW_AT_start_scope"; - case DW_AT_bit_stride: return "DW_AT_bit_stride"; - case DW_AT_upper_bound: return "DW_AT_upper_bound"; - case DW_AT_abstract_origin: return "DW_AT_abstract_origin"; - case DW_AT_accessibility: return "DW_AT_accessibility"; - case DW_AT_address_class: return "DW_AT_address_class"; - case DW_AT_artificial: return "DW_AT_artificial"; - case DW_AT_base_types: return "DW_AT_base_types"; - case DW_AT_calling_convention: return "DW_AT_calling_convention"; - case DW_AT_count: return "DW_AT_count"; - case DW_AT_data_member_location: return "DW_AT_data_member_location"; - case DW_AT_decl_column: return "DW_AT_decl_column"; - case DW_AT_decl_file: return "DW_AT_decl_file"; - case DW_AT_decl_line: return "DW_AT_decl_line"; - case DW_AT_declaration: return "DW_AT_declaration"; - case DW_AT_discr_list: return "DW_AT_discr_list"; - case DW_AT_encoding: return "DW_AT_encoding"; - case DW_AT_external: return "DW_AT_external"; - case DW_AT_frame_base: return "DW_AT_frame_base"; - case DW_AT_friend: return "DW_AT_friend"; - case DW_AT_identifier_case: return "DW_AT_identifier_case"; - case DW_AT_macro_info: return "DW_AT_macro_info"; - case DW_AT_namelist_item: return "DW_AT_namelist_item"; - case DW_AT_priority: return "DW_AT_priority"; - case DW_AT_segment: return "DW_AT_segment"; - case DW_AT_specification: return "DW_AT_specification"; - case DW_AT_static_link: return "DW_AT_static_link"; - case DW_AT_type: return "DW_AT_type"; - case DW_AT_use_location: return "DW_AT_use_location"; - case DW_AT_variable_parameter: return "DW_AT_variable_parameter"; - case DW_AT_virtuality: return "DW_AT_virtuality"; - case DW_AT_vtable_elem_location: return "DW_AT_vtable_elem_location"; - case DW_AT_allocated: return "DW_AT_allocated"; - case DW_AT_associated: return "DW_AT_associated"; - case DW_AT_data_location: return "DW_AT_data_location"; - case DW_AT_byte_stride: return "DW_AT_byte_stride"; - case DW_AT_entry_pc: return "DW_AT_entry_pc"; - case DW_AT_use_UTF8: return "DW_AT_use_UTF8"; - case DW_AT_extension: return "DW_AT_extension"; - case DW_AT_ranges: return "DW_AT_ranges"; - case DW_AT_trampoline: return "DW_AT_trampoline"; - case DW_AT_call_column: return "DW_AT_call_column"; - case DW_AT_call_file: return "DW_AT_call_file"; - case DW_AT_call_line: return "DW_AT_call_line"; - case DW_AT_description: return "DW_AT_description"; - case DW_AT_binary_scale: return "DW_AT_binary_scale"; - case DW_AT_decimal_scale: return "DW_AT_decimal_scale"; - case DW_AT_small: return "DW_AT_small"; - case DW_AT_decimal_sign: return "DW_AT_decimal_sign"; - case DW_AT_digit_count: return "DW_AT_digit_count"; - case DW_AT_picture_string: return "DW_AT_picture_string"; - case DW_AT_mutable: return "DW_AT_mutable"; - case DW_AT_threads_scaled: return "DW_AT_threads_scaled"; - case DW_AT_explicit: return "DW_AT_explicit"; - case DW_AT_object_pointer: return "DW_AT_object_pointer"; - case DW_AT_endianity: return "DW_AT_endianity"; - case DW_AT_elemental: return "DW_AT_elemental"; - case DW_AT_pure: return "DW_AT_pure"; - case DW_AT_recursive: return "DW_AT_recursive"; - case DW_AT_MIPS_linkage_name: return "DW_AT_MIPS_linkage_name"; - case DW_AT_sf_names: return "DW_AT_sf_names"; - case DW_AT_src_info: return "DW_AT_src_info"; - case DW_AT_mac_info: return "DW_AT_mac_info"; - case DW_AT_src_coords: return "DW_AT_src_coords"; - case DW_AT_body_begin: return "DW_AT_body_begin"; - case DW_AT_body_end: return "DW_AT_body_end"; - case DW_AT_GNU_vector: return "DW_AT_GNU_vector"; - case DW_AT_lo_user: return "DW_AT_lo_user"; - case DW_AT_hi_user: return "DW_AT_hi_user"; - case DW_AT_APPLE_optimized: return "DW_AT_APPLE_optimized"; - case DW_AT_APPLE_flags: return "DW_AT_APPLE_flags"; - case DW_AT_APPLE_isa: return "DW_AT_APPLE_isa"; - case DW_AT_APPLE_block: return "DW_AT_APPLE_block"; - case DW_AT_APPLE_major_runtime_vers: return "DW_AT_APPLE_major_runtime_vers"; - case DW_AT_APPLE_runtime_class: return "DW_AT_APPLE_runtime_class"; + case DW_AT_sibling: return "DW_AT_sibling"; + case DW_AT_location: return "DW_AT_location"; + case DW_AT_name: return "DW_AT_name"; + case DW_AT_ordering: return "DW_AT_ordering"; + case DW_AT_byte_size: return "DW_AT_byte_size"; + case DW_AT_bit_offset: return "DW_AT_bit_offset"; + case DW_AT_bit_size: return "DW_AT_bit_size"; + case DW_AT_stmt_list: return "DW_AT_stmt_list"; + case DW_AT_low_pc: return "DW_AT_low_pc"; + case DW_AT_high_pc: return "DW_AT_high_pc"; + case DW_AT_language: return "DW_AT_language"; + case DW_AT_discr: return "DW_AT_discr"; + case DW_AT_discr_value: return "DW_AT_discr_value"; + case DW_AT_visibility: return "DW_AT_visibility"; + case DW_AT_import: return "DW_AT_import"; + case DW_AT_string_length: return "DW_AT_string_length"; + case DW_AT_common_reference: return "DW_AT_common_reference"; + case DW_AT_comp_dir: return "DW_AT_comp_dir"; + case DW_AT_const_value: return "DW_AT_const_value"; + case DW_AT_containing_type: return "DW_AT_containing_type"; + case DW_AT_default_value: return "DW_AT_default_value"; + case DW_AT_inline: return "DW_AT_inline"; + case DW_AT_is_optional: return "DW_AT_is_optional"; + case DW_AT_lower_bound: return "DW_AT_lower_bound"; + case DW_AT_producer: return "DW_AT_producer"; + case DW_AT_prototyped: return "DW_AT_prototyped"; + case DW_AT_return_addr: return "DW_AT_return_addr"; + case DW_AT_start_scope: return "DW_AT_start_scope"; + case DW_AT_bit_stride: return "DW_AT_bit_stride"; + case DW_AT_upper_bound: return "DW_AT_upper_bound"; + case DW_AT_abstract_origin: return "DW_AT_abstract_origin"; + case DW_AT_accessibility: return "DW_AT_accessibility"; + case DW_AT_address_class: return "DW_AT_address_class"; + case DW_AT_artificial: return "DW_AT_artificial"; + case DW_AT_base_types: return "DW_AT_base_types"; + case DW_AT_calling_convention: return "DW_AT_calling_convention"; + case DW_AT_count: return "DW_AT_count"; + case DW_AT_data_member_location: return "DW_AT_data_member_location"; + case DW_AT_decl_column: return "DW_AT_decl_column"; + case DW_AT_decl_file: return "DW_AT_decl_file"; + case DW_AT_decl_line: return "DW_AT_decl_line"; + case DW_AT_declaration: return "DW_AT_declaration"; + case DW_AT_discr_list: return "DW_AT_discr_list"; + case DW_AT_encoding: return "DW_AT_encoding"; + case DW_AT_external: return "DW_AT_external"; + case DW_AT_frame_base: return "DW_AT_frame_base"; + case DW_AT_friend: return "DW_AT_friend"; + case DW_AT_identifier_case: return "DW_AT_identifier_case"; + case DW_AT_macro_info: return "DW_AT_macro_info"; + case DW_AT_namelist_item: return "DW_AT_namelist_item"; + case DW_AT_priority: return "DW_AT_priority"; + case DW_AT_segment: return "DW_AT_segment"; + case DW_AT_specification: return "DW_AT_specification"; + case DW_AT_static_link: return "DW_AT_static_link"; + case DW_AT_type: return "DW_AT_type"; + case DW_AT_use_location: return "DW_AT_use_location"; + case DW_AT_variable_parameter: return "DW_AT_variable_parameter"; + case DW_AT_virtuality: return "DW_AT_virtuality"; + case DW_AT_vtable_elem_location: return "DW_AT_vtable_elem_location"; + case DW_AT_allocated: return "DW_AT_allocated"; + case DW_AT_associated: return "DW_AT_associated"; + case DW_AT_data_location: return "DW_AT_data_location"; + case DW_AT_byte_stride: return "DW_AT_byte_stride"; + case DW_AT_entry_pc: return "DW_AT_entry_pc"; + case DW_AT_use_UTF8: return "DW_AT_use_UTF8"; + case DW_AT_extension: return "DW_AT_extension"; + case DW_AT_ranges: return "DW_AT_ranges"; + case DW_AT_trampoline: return "DW_AT_trampoline"; + case DW_AT_call_column: return "DW_AT_call_column"; + case DW_AT_call_file: return "DW_AT_call_file"; + case DW_AT_call_line: return "DW_AT_call_line"; + case DW_AT_description: return "DW_AT_description"; + case DW_AT_binary_scale: return "DW_AT_binary_scale"; + case DW_AT_decimal_scale: return "DW_AT_decimal_scale"; + case DW_AT_small: return "DW_AT_small"; + case DW_AT_decimal_sign: return "DW_AT_decimal_sign"; + case DW_AT_digit_count: return "DW_AT_digit_count"; + case DW_AT_picture_string: return "DW_AT_picture_string"; + case DW_AT_mutable: return "DW_AT_mutable"; + case DW_AT_threads_scaled: return "DW_AT_threads_scaled"; + case DW_AT_explicit: return "DW_AT_explicit"; + case DW_AT_object_pointer: return "DW_AT_object_pointer"; + case DW_AT_endianity: return "DW_AT_endianity"; + case DW_AT_elemental: return "DW_AT_elemental"; + case DW_AT_pure: return "DW_AT_pure"; + case DW_AT_recursive: return "DW_AT_recursive"; + case DW_AT_MIPS_linkage_name: return "DW_AT_MIPS_linkage_name"; + case DW_AT_sf_names: return "DW_AT_sf_names"; + case DW_AT_src_info: return "DW_AT_src_info"; + case DW_AT_mac_info: return "DW_AT_mac_info"; + case DW_AT_src_coords: return "DW_AT_src_coords"; + case DW_AT_body_begin: return "DW_AT_body_begin"; + case DW_AT_body_end: return "DW_AT_body_end"; + case DW_AT_GNU_vector: return "DW_AT_GNU_vector"; + case DW_AT_lo_user: return "DW_AT_lo_user"; + case DW_AT_hi_user: return "DW_AT_hi_user"; + case DW_AT_APPLE_optimized: return "DW_AT_APPLE_optimized"; + case DW_AT_APPLE_flags: return "DW_AT_APPLE_flags"; + case DW_AT_APPLE_isa: return "DW_AT_APPLE_isa"; + case DW_AT_APPLE_block: return "DW_AT_APPLE_block"; + case DW_AT_APPLE_major_runtime_vers: return "DW_AT_APPLE_major_runtime_vers"; + case DW_AT_APPLE_runtime_class: return "DW_AT_APPLE_runtime_class"; } llvm_unreachable("Unknown Dwarf Attribute"); return ""; @@ -211,27 +211,27 @@ /// const char *llvm::dwarf::FormEncodingString(unsigned Encoding) { switch (Encoding) { - case DW_FORM_addr: return "FORM_addr"; - case DW_FORM_block2: return "FORM_block2"; - case DW_FORM_block4: return "FORM_block4"; - case DW_FORM_data2: return "FORM_data2"; - case DW_FORM_data4: return "FORM_data4"; - case DW_FORM_data8: return "FORM_data8"; - case DW_FORM_string: return "FORM_string"; - case DW_FORM_block: return "FORM_block"; - case DW_FORM_block1: return "FORM_block1"; - case DW_FORM_data1: return "FORM_data1"; - case DW_FORM_flag: return "FORM_flag"; - case DW_FORM_sdata: return "FORM_sdata"; - case DW_FORM_strp: return "FORM_strp"; - case DW_FORM_udata: return "FORM_udata"; - case DW_FORM_ref_addr: return "FORM_ref_addr"; - case DW_FORM_ref1: return "FORM_ref1"; - case DW_FORM_ref2: return "FORM_ref2"; - case DW_FORM_ref4: return "FORM_ref4"; - case DW_FORM_ref8: return "FORM_ref8"; - case DW_FORM_ref_udata: return "FORM_ref_udata"; - case DW_FORM_indirect: return "FORM_indirect"; + case DW_FORM_addr: return "FORM_addr"; + case DW_FORM_block2: return "FORM_block2"; + case DW_FORM_block4: return "FORM_block4"; + case DW_FORM_data2: return "FORM_data2"; + case DW_FORM_data4: return "FORM_data4"; + case DW_FORM_data8: return "FORM_data8"; + case DW_FORM_string: return "FORM_string"; + case DW_FORM_block: return "FORM_block"; + case DW_FORM_block1: return "FORM_block1"; + case DW_FORM_data1: return "FORM_data1"; + case DW_FORM_flag: return "FORM_flag"; + case DW_FORM_sdata: return "FORM_sdata"; + case DW_FORM_strp: return "FORM_strp"; + case DW_FORM_udata: return "FORM_udata"; + case DW_FORM_ref_addr: return "FORM_ref_addr"; + case DW_FORM_ref1: return "FORM_ref1"; + case DW_FORM_ref2: return "FORM_ref2"; + case DW_FORM_ref4: return "FORM_ref4"; + case DW_FORM_ref8: return "FORM_ref8"; + case DW_FORM_ref_udata: return "FORM_ref_udata"; + case DW_FORM_indirect: return "FORM_indirect"; } llvm_unreachable("Unknown Dwarf Form Encoding"); return ""; @@ -241,72 +241,72 @@ /// encoding. const char *llvm::dwarf::OperationEncodingString(unsigned Encoding) { switch (Encoding) { - case DW_OP_addr: return "OP_addr"; - case DW_OP_deref: return "OP_deref"; - case DW_OP_const1u: return "OP_const1u"; - case DW_OP_const1s: return "OP_const1s"; - case DW_OP_const2u: return "OP_const2u"; - case DW_OP_const2s: return "OP_const2s"; - case DW_OP_const4u: return "OP_const4u"; - case DW_OP_const4s: return "OP_const4s"; - case DW_OP_const8u: return "OP_const8u"; - case DW_OP_const8s: return "OP_const8s"; - case DW_OP_constu: return "OP_constu"; - case DW_OP_consts: return "OP_consts"; - case DW_OP_dup: return "OP_dup"; - case DW_OP_drop: return "OP_drop"; - case DW_OP_over: return "OP_over"; - case DW_OP_pick: return "OP_pick"; - case DW_OP_swap: return "OP_swap"; - case DW_OP_rot: return "OP_rot"; - case DW_OP_xderef: return "OP_xderef"; - case DW_OP_abs: return "OP_abs"; - case DW_OP_and: return "OP_and"; - case DW_OP_div: return "OP_div"; - case DW_OP_minus: return "OP_minus"; - case DW_OP_mod: return "OP_mod"; - case DW_OP_mul: return "OP_mul"; - case DW_OP_neg: return "OP_neg"; - case DW_OP_not: return "OP_not"; - case DW_OP_or: return "OP_or"; - case DW_OP_plus: return "OP_plus"; - case DW_OP_plus_uconst: return "OP_plus_uconst"; - case DW_OP_shl: return "OP_shl"; - case DW_OP_shr: return "OP_shr"; - case DW_OP_shra: return "OP_shra"; - case DW_OP_xor: return "OP_xor"; - case DW_OP_skip: return "OP_skip"; - case DW_OP_bra: return "OP_bra"; - case DW_OP_eq: return "OP_eq"; - case DW_OP_ge: return "OP_ge"; - case DW_OP_gt: return "OP_gt"; - case DW_OP_le: return "OP_le"; - case DW_OP_lt: return "OP_lt"; - case DW_OP_ne: return "OP_ne"; - case DW_OP_lit0: return "OP_lit0"; - case DW_OP_lit1: return "OP_lit1"; - case DW_OP_lit31: return "OP_lit31"; - case DW_OP_reg0: return "OP_reg0"; - case DW_OP_reg1: return "OP_reg1"; - case DW_OP_reg31: return "OP_reg31"; - case DW_OP_breg0: return "OP_breg0"; - case DW_OP_breg1: return "OP_breg1"; - case DW_OP_breg31: return "OP_breg31"; - case DW_OP_regx: return "OP_regx"; - case DW_OP_fbreg: return "OP_fbreg"; - case DW_OP_bregx: return "OP_bregx"; - case DW_OP_piece: return "OP_piece"; - case DW_OP_deref_size: return "OP_deref_size"; - case DW_OP_xderef_size: return "OP_xderef_size"; - case DW_OP_nop: return "OP_nop"; - case DW_OP_push_object_address: return "OP_push_object_address"; - case DW_OP_call2: return "OP_call2"; - case DW_OP_call4: return "OP_call4"; - case DW_OP_call_ref: return "OP_call_ref"; - case DW_OP_form_tls_address: return "OP_form_tls_address"; - case DW_OP_call_frame_cfa: return "OP_call_frame_cfa"; - case DW_OP_lo_user: return "OP_lo_user"; - case DW_OP_hi_user: return "OP_hi_user"; + case DW_OP_addr: return "OP_addr"; + case DW_OP_deref: return "OP_deref"; + case DW_OP_const1u: return "OP_const1u"; + case DW_OP_const1s: return "OP_const1s"; + case DW_OP_const2u: return "OP_const2u"; + case DW_OP_const2s: return "OP_const2s"; + case DW_OP_const4u: return "OP_const4u"; + case DW_OP_const4s: return "OP_const4s"; + case DW_OP_const8u: return "OP_const8u"; + case DW_OP_const8s: return "OP_const8s"; + case DW_OP_constu: return "OP_constu"; + case DW_OP_consts: return "OP_consts"; + case DW_OP_dup: return "OP_dup"; + case DW_OP_drop: return "OP_drop"; + case DW_OP_over: return "OP_over"; + case DW_OP_pick: return "OP_pick"; + case DW_OP_swap: return "OP_swap"; + case DW_OP_rot: return "OP_rot"; + case DW_OP_xderef: return "OP_xderef"; + case DW_OP_abs: return "OP_abs"; + case DW_OP_and: return "OP_and"; + case DW_OP_div: return "OP_div"; + case DW_OP_minus: return "OP_minus"; + case DW_OP_mod: return "OP_mod"; + case DW_OP_mul: return "OP_mul"; + case DW_OP_neg: return "OP_neg"; + case DW_OP_not: return "OP_not"; + case DW_OP_or: return "OP_or"; + case DW_OP_plus: return "OP_plus"; + case DW_OP_plus_uconst: return "OP_plus_uconst"; + case DW_OP_shl: return "OP_shl"; + case DW_OP_shr: return "OP_shr"; + case DW_OP_shra: return "OP_shra"; + case DW_OP_xor: return "OP_xor"; + case DW_OP_skip: return "OP_skip"; + case DW_OP_bra: return "OP_bra"; + case DW_OP_eq: return "OP_eq"; + case DW_OP_ge: return "OP_ge"; + case DW_OP_gt: return "OP_gt"; + case DW_OP_le: return "OP_le"; + case DW_OP_lt: return "OP_lt"; + case DW_OP_ne: return "OP_ne"; + case DW_OP_lit0: return "OP_lit0"; + case DW_OP_lit1: return "OP_lit1"; + case DW_OP_lit31: return "OP_lit31"; + case DW_OP_reg0: return "OP_reg0"; + case DW_OP_reg1: return "OP_reg1"; + case DW_OP_reg31: return "OP_reg31"; + case DW_OP_breg0: return "OP_breg0"; + case DW_OP_breg1: return "OP_breg1"; + case DW_OP_breg31: return "OP_breg31"; + case DW_OP_regx: return "OP_regx"; + case DW_OP_fbreg: return "OP_fbreg"; + case DW_OP_bregx: return "OP_bregx"; + case DW_OP_piece: return "OP_piece"; + case DW_OP_deref_size: return "OP_deref_size"; + case DW_OP_xderef_size: return "OP_xderef_size"; + case DW_OP_nop: return "OP_nop"; + case DW_OP_push_object_address: return "OP_push_object_address"; + case DW_OP_call2: return "OP_call2"; + case DW_OP_call4: return "OP_call4"; + case DW_OP_call_ref: return "OP_call_ref"; + case DW_OP_form_tls_address: return "OP_form_tls_address"; + case DW_OP_call_frame_cfa: return "OP_call_frame_cfa"; + case DW_OP_lo_user: return "OP_lo_user"; + case DW_OP_hi_user: return "OP_hi_user"; } llvm_unreachable("Unknown Dwarf Operation Encoding"); return ""; @@ -316,23 +316,23 @@ /// encoding. const char *llvm::dwarf::AttributeEncodingString(unsigned Encoding) { switch (Encoding) { - case DW_ATE_address: return "ATE_address"; - case DW_ATE_boolean: return "ATE_boolean"; - case DW_ATE_complex_float: return "ATE_complex_float"; - case DW_ATE_float: return "ATE_float"; - case DW_ATE_signed: return "ATE_signed"; - case DW_ATE_signed_char: return "ATE_signed_char"; - case DW_ATE_unsigned: return "ATE_unsigned"; - case DW_ATE_unsigned_char: return "ATE_unsigned_char"; - case DW_ATE_imaginary_float: return "ATE_imaginary_float"; - case DW_ATE_packed_decimal: return "ATE_packed_decimal"; - case DW_ATE_numeric_string: return "ATE_numeric_string"; - case DW_ATE_edited: return "ATE_edited"; - case DW_ATE_signed_fixed: return "ATE_signed_fixed"; - case DW_ATE_unsigned_fixed: return "ATE_unsigned_fixed"; - case DW_ATE_decimal_float: return "ATE_decimal_float"; - case DW_ATE_lo_user: return "ATE_lo_user"; - case DW_ATE_hi_user: return "ATE_hi_user"; + case DW_ATE_address: return "ATE_address"; + case DW_ATE_boolean: return "ATE_boolean"; + case DW_ATE_complex_float: return "ATE_complex_float"; + case DW_ATE_float: return "ATE_float"; + case DW_ATE_signed: return "ATE_signed"; + case DW_ATE_signed_char: return "ATE_signed_char"; + case DW_ATE_unsigned: return "ATE_unsigned"; + case DW_ATE_unsigned_char: return "ATE_unsigned_char"; + case DW_ATE_imaginary_float: return "ATE_imaginary_float"; + case DW_ATE_packed_decimal: return "ATE_packed_decimal"; + case DW_ATE_numeric_string: return "ATE_numeric_string"; + case DW_ATE_edited: return "ATE_edited"; + case DW_ATE_signed_fixed: return "ATE_signed_fixed"; + case DW_ATE_unsigned_fixed: return "ATE_unsigned_fixed"; + case DW_ATE_decimal_float: return "ATE_decimal_float"; + case DW_ATE_lo_user: return "ATE_lo_user"; + case DW_ATE_hi_user: return "ATE_hi_user"; } llvm_unreachable("Unknown Dwarf Attribute Encoding"); return ""; @@ -342,11 +342,11 @@ /// attribute. const char *llvm::dwarf::DecimalSignString(unsigned Sign) { switch (Sign) { - case DW_DS_unsigned: return "DS_unsigned"; - case DW_DS_leading_overpunch: return "DS_leading_overpunch"; - case DW_DS_trailing_overpunch: return "DS_trailing_overpunch"; - case DW_DS_leading_separate: return "DS_leading_separate"; - case DW_DS_trailing_separate: return "DS_trailing_separate"; + case DW_DS_unsigned: return "DS_unsigned"; + case DW_DS_leading_overpunch: return "DS_leading_overpunch"; + case DW_DS_trailing_overpunch: return "DS_trailing_overpunch"; + case DW_DS_leading_separate: return "DS_leading_separate"; + case DW_DS_trailing_separate: return "DS_trailing_separate"; } llvm_unreachable("Unknown Dwarf Decimal Sign Attribute"); return ""; @@ -356,11 +356,11 @@ /// const char *llvm::dwarf::EndianityString(unsigned Endian) { switch (Endian) { - case DW_END_default: return "END_default"; - case DW_END_big: return "END_big"; - case DW_END_little: return "END_little"; - case DW_END_lo_user: return "END_lo_user"; - case DW_END_hi_user: return "END_hi_user"; + case DW_END_default: return "END_default"; + case DW_END_big: return "END_big"; + case DW_END_little: return "END_little"; + case DW_END_lo_user: return "END_lo_user"; + case DW_END_hi_user: return "END_hi_user"; } llvm_unreachable("Unknown Dwarf Endianity"); return ""; @@ -370,10 +370,10 @@ /// const char *llvm::dwarf::AccessibilityString(unsigned Access) { switch (Access) { - // Accessibility codes - case DW_ACCESS_public: return "ACCESS_public"; - case DW_ACCESS_protected: return "ACCESS_protected"; - case DW_ACCESS_private: return "ACCESS_private"; + // Accessibility codes + case DW_ACCESS_public: return "ACCESS_public"; + case DW_ACCESS_protected: return "ACCESS_protected"; + case DW_ACCESS_private: return "ACCESS_private"; } llvm_unreachable("Unknown Dwarf Accessibility"); return ""; @@ -383,9 +383,9 @@ /// const char *llvm::dwarf::VisibilityString(unsigned Visibility) { switch (Visibility) { - case DW_VIS_local: return "VIS_local"; - case DW_VIS_exported: return "VIS_exported"; - case DW_VIS_qualified: return "VIS_qualified"; + case DW_VIS_local: return "VIS_local"; + case DW_VIS_exported: return "VIS_exported"; + case DW_VIS_qualified: return "VIS_qualified"; } llvm_unreachable("Unknown Dwarf Visibility"); return ""; @@ -395,9 +395,9 @@ /// const char *llvm::dwarf::VirtualityString(unsigned Virtuality) { switch (Virtuality) { - case DW_VIRTUALITY_none: return "VIRTUALITY_none"; - case DW_VIRTUALITY_virtual: return "VIRTUALITY_virtual"; - case DW_VIRTUALITY_pure_virtual: return "VIRTUALITY_pure_virtual"; + case DW_VIRTUALITY_none: return "VIRTUALITY_none"; + case DW_VIRTUALITY_virtual: return "VIRTUALITY_virtual"; + case DW_VIRTUALITY_pure_virtual: return "VIRTUALITY_pure_virtual"; } llvm_unreachable("Unknown Dwarf Virtuality"); return ""; @@ -407,27 +407,27 @@ /// const char *llvm::dwarf::LanguageString(unsigned Language) { switch (Language) { - case DW_LANG_C89: return "LANG_C89"; - case DW_LANG_C: return "LANG_C"; - case DW_LANG_Ada83: return "LANG_Ada83"; - case DW_LANG_C_plus_plus: return "LANG_C_plus_plus"; - case DW_LANG_Cobol74: return "LANG_Cobol74"; - case DW_LANG_Cobol85: return "LANG_Cobol85"; - case DW_LANG_Fortran77: return "LANG_Fortran77"; - case DW_LANG_Fortran90: return "LANG_Fortran90"; - case DW_LANG_Pascal83: return "LANG_Pascal83"; - case DW_LANG_Modula2: return "LANG_Modula2"; - case DW_LANG_Java: return "LANG_Java"; - case DW_LANG_C99: return "LANG_C99"; - case DW_LANG_Ada95: return "LANG_Ada95"; - case DW_LANG_Fortran95: return "LANG_Fortran95"; - case DW_LANG_PLI: return "LANG_PLI"; - case DW_LANG_ObjC: return "LANG_ObjC"; - case DW_LANG_ObjC_plus_plus: return "LANG_ObjC_plus_plus"; - case DW_LANG_UPC: return "LANG_UPC"; - case DW_LANG_D: return "LANG_D"; - case DW_LANG_lo_user: return "LANG_lo_user"; - case DW_LANG_hi_user: return "LANG_hi_user"; + case DW_LANG_C89: return "LANG_C89"; + case DW_LANG_C: return "LANG_C"; + case DW_LANG_Ada83: return "LANG_Ada83"; + case DW_LANG_C_plus_plus: return "LANG_C_plus_plus"; + case DW_LANG_Cobol74: return "LANG_Cobol74"; + case DW_LANG_Cobol85: return "LANG_Cobol85"; + case DW_LANG_Fortran77: return "LANG_Fortran77"; + case DW_LANG_Fortran90: return "LANG_Fortran90"; + case DW_LANG_Pascal83: return "LANG_Pascal83"; + case DW_LANG_Modula2: return "LANG_Modula2"; + case DW_LANG_Java: return "LANG_Java"; + case DW_LANG_C99: return "LANG_C99"; + case DW_LANG_Ada95: return "LANG_Ada95"; + case DW_LANG_Fortran95: return "LANG_Fortran95"; + case DW_LANG_PLI: return "LANG_PLI"; + case DW_LANG_ObjC: return "LANG_ObjC"; + case DW_LANG_ObjC_plus_plus: return "LANG_ObjC_plus_plus"; + case DW_LANG_UPC: return "LANG_UPC"; + case DW_LANG_D: return "LANG_D"; + case DW_LANG_lo_user: return "LANG_lo_user"; + case DW_LANG_hi_user: return "LANG_hi_user"; } llvm_unreachable("Unknown Dwarf Language"); return ""; @@ -436,11 +436,11 @@ /// CaseString - Return the string for the specified identifier case. /// const char *llvm::dwarf::CaseString(unsigned Case) { - switch (Case) { - case DW_ID_case_sensitive: return "ID_case_sensitive"; - case DW_ID_up_case: return "ID_up_case"; - case DW_ID_down_case: return "ID_down_case"; - case DW_ID_case_insensitive: return "ID_case_insensitive"; + switch (Case) { + case DW_ID_case_sensitive: return "ID_case_sensitive"; + case DW_ID_up_case: return "ID_up_case"; + case DW_ID_down_case: return "ID_down_case"; + case DW_ID_case_insensitive: return "ID_case_insensitive"; } llvm_unreachable("Unknown Dwarf Identifier Case"); return ""; @@ -450,11 +450,11 @@ /// const char *llvm::dwarf::ConventionString(unsigned Convention) { switch (Convention) { - case DW_CC_normal: return "CC_normal"; - case DW_CC_program: return "CC_program"; - case DW_CC_nocall: return "CC_nocall"; - case DW_CC_lo_user: return "CC_lo_user"; - case DW_CC_hi_user: return "CC_hi_user"; + case DW_CC_normal: return "CC_normal"; + case DW_CC_program: return "CC_program"; + case DW_CC_nocall: return "CC_nocall"; + case DW_CC_lo_user: return "CC_lo_user"; + case DW_CC_hi_user: return "CC_hi_user"; } llvm_unreachable("Unknown Dwarf Calling Convention"); return ""; @@ -463,11 +463,11 @@ /// InlineCodeString - Return the string for the specified inline code. /// const char *llvm::dwarf::InlineCodeString(unsigned Code) { - switch (Code) { - case DW_INL_not_inlined: return "INL_not_inlined"; - case DW_INL_inlined: return "INL_inlined"; - case DW_INL_declared_not_inlined: return "INL_declared_not_inlined"; - case DW_INL_declared_inlined: return "INL_declared_inlined"; + switch (Code) { + case DW_INL_not_inlined: return "INL_not_inlined"; + case DW_INL_inlined: return "INL_inlined"; + case DW_INL_declared_not_inlined: return "INL_declared_not_inlined"; + case DW_INL_declared_inlined: return "INL_declared_inlined"; } llvm_unreachable("Unknown Dwarf Inline Code"); return ""; @@ -476,9 +476,9 @@ /// ArrayOrderString - Return the string for the specified array order. /// const char *llvm::dwarf::ArrayOrderString(unsigned Order) { - switch (Order) { - case DW_ORD_row_major: return "ORD_row_major"; - case DW_ORD_col_major: return "ORD_col_major"; + switch (Order) { + case DW_ORD_row_major: return "ORD_row_major"; + case DW_ORD_col_major: return "ORD_col_major"; } llvm_unreachable("Unknown Dwarf Array Order"); return ""; @@ -487,9 +487,9 @@ /// DiscriminantString - Return the string for the specified discriminant /// descriptor. const char *llvm::dwarf::DiscriminantString(unsigned Discriminant) { - switch (Discriminant) { - case DW_DSC_label: return "DSC_label"; - case DW_DSC_range: return "DSC_range"; + switch (Discriminant) { + case DW_DSC_label: return "DSC_label"; + case DW_DSC_range: return "DSC_range"; } llvm_unreachable("Unknown Dwarf Discriminant Descriptor"); return ""; @@ -498,19 +498,19 @@ /// LNStandardString - Return the string for the specified line number standard. /// const char *llvm::dwarf::LNStandardString(unsigned Standard) { - switch (Standard) { - case DW_LNS_copy: return "LNS_copy"; - case DW_LNS_advance_pc: return "LNS_advance_pc"; - case DW_LNS_advance_line: return "LNS_advance_line"; - case DW_LNS_set_file: return "LNS_set_file"; - case DW_LNS_set_column: return "LNS_set_column"; - case DW_LNS_negate_stmt: return "LNS_negate_stmt"; - case DW_LNS_set_basic_block: return "LNS_set_basic_block"; - case DW_LNS_const_add_pc: return "LNS_const_add_pc"; - case DW_LNS_fixed_advance_pc: return "LNS_fixed_advance_pc"; - case DW_LNS_set_prologue_end: return "LNS_set_prologue_end"; - case DW_LNS_set_epilogue_begin: return "LNS_set_epilogue_begin"; - case DW_LNS_set_isa: return "LNS_set_isa"; + switch (Standard) { + case DW_LNS_copy: return "LNS_copy"; + case DW_LNS_advance_pc: return "LNS_advance_pc"; + case DW_LNS_advance_line: return "LNS_advance_line"; + case DW_LNS_set_file: return "LNS_set_file"; + case DW_LNS_set_column: return "LNS_set_column"; + case DW_LNS_negate_stmt: return "LNS_negate_stmt"; + case DW_LNS_set_basic_block: return "LNS_set_basic_block"; + case DW_LNS_const_add_pc: return "LNS_const_add_pc"; + case DW_LNS_fixed_advance_pc: return "LNS_fixed_advance_pc"; + case DW_LNS_set_prologue_end: return "LNS_set_prologue_end"; + case DW_LNS_set_epilogue_begin: return "LNS_set_epilogue_begin"; + case DW_LNS_set_isa: return "LNS_set_isa"; } llvm_unreachable("Unknown Dwarf Line Number Standard"); return ""; @@ -519,13 +519,13 @@ /// LNExtendedString - Return the string for the specified line number extended /// opcode encodings. const char *llvm::dwarf::LNExtendedString(unsigned Encoding) { - switch (Encoding) { - // Line Number Extended Opcode Encodings - case DW_LNE_end_sequence: return "LNE_end_sequence"; - case DW_LNE_set_address: return "LNE_set_address"; - case DW_LNE_define_file: return "LNE_define_file"; - case DW_LNE_lo_user: return "LNE_lo_user"; - case DW_LNE_hi_user: return "LNE_hi_user"; + switch (Encoding) { + // Line Number Extended Opcode Encodings + case DW_LNE_end_sequence: return "LNE_end_sequence"; + case DW_LNE_set_address: return "LNE_set_address"; + case DW_LNE_define_file: return "LNE_define_file"; + case DW_LNE_lo_user: return "LNE_lo_user"; + case DW_LNE_hi_user: return "LNE_hi_user"; } llvm_unreachable("Unknown Dwarf Line Number Extended Opcode Encoding"); return ""; @@ -534,13 +534,13 @@ /// MacinfoString - Return the string for the specified macinfo type encodings. /// const char *llvm::dwarf::MacinfoString(unsigned Encoding) { - switch (Encoding) { - // Macinfo Type Encodings - case DW_MACINFO_define: return "MACINFO_define"; - case DW_MACINFO_undef: return "MACINFO_undef"; - case DW_MACINFO_start_file: return "MACINFO_start_file"; - case DW_MACINFO_end_file: return "MACINFO_end_file"; - case DW_MACINFO_vendor_ext: return "MACINFO_vendor_ext"; + switch (Encoding) { + // Macinfo Type Encodings + case DW_MACINFO_define: return "MACINFO_define"; + case DW_MACINFO_undef: return "MACINFO_undef"; + case DW_MACINFO_start_file: return "MACINFO_start_file"; + case DW_MACINFO_end_file: return "MACINFO_end_file"; + case DW_MACINFO_vendor_ext: return "MACINFO_vendor_ext"; } llvm_unreachable("Unknown Dwarf Macinfo Type Encodings"); return ""; @@ -549,34 +549,34 @@ /// CallFrameString - Return the string for the specified call frame instruction /// encodings. const char *llvm::dwarf::CallFrameString(unsigned Encoding) { - switch (Encoding) { - case DW_CFA_advance_loc: return "CFA_advance_loc"; - case DW_CFA_offset: return "CFA_offset"; - case DW_CFA_restore: return "CFA_restore"; - case DW_CFA_set_loc: return "CFA_set_loc"; - case DW_CFA_advance_loc1: return "CFA_advance_loc1"; - case DW_CFA_advance_loc2: return "CFA_advance_loc2"; - case DW_CFA_advance_loc4: return "CFA_advance_loc4"; - case DW_CFA_offset_extended: return "CFA_offset_extended"; - case DW_CFA_restore_extended: return "CFA_restore_extended"; - case DW_CFA_undefined: return "CFA_undefined"; - case DW_CFA_same_value: return "CFA_same_value"; - case DW_CFA_register: return "CFA_register"; - case DW_CFA_remember_state: return "CFA_remember_state"; - case DW_CFA_restore_state: return "CFA_restore_state"; - case DW_CFA_def_cfa: return "CFA_def_cfa"; - case DW_CFA_def_cfa_register: return "CFA_def_cfa_register"; - case DW_CFA_def_cfa_offset: return "CFA_def_cfa_offset"; - case DW_CFA_def_cfa_expression: return "CFA_def_cfa_expression"; - case DW_CFA_expression: return "CFA_expression"; - case DW_CFA_offset_extended_sf: return "CFA_offset_extended_sf"; - case DW_CFA_def_cfa_sf: return "CFA_def_cfa_sf"; - case DW_CFA_def_cfa_offset_sf: return "CFA_def_cfa_offset_sf"; - case DW_CFA_val_offset: return "CFA_val_offset"; - case DW_CFA_val_offset_sf: return "CFA_val_offset_sf"; - case DW_CFA_val_expression: return "CFA_val_expression"; - case DW_CFA_lo_user: return "CFA_lo_user"; - case DW_CFA_hi_user: return "CFA_hi_user"; + switch (Encoding) { + case DW_CFA_advance_loc: return "CFA_advance_loc"; + case DW_CFA_offset: return "CFA_offset"; + case DW_CFA_restore: return "CFA_restore"; + case DW_CFA_set_loc: return "CFA_set_loc"; + case DW_CFA_advance_loc1: return "CFA_advance_loc1"; + case DW_CFA_advance_loc2: return "CFA_advance_loc2"; + case DW_CFA_advance_loc4: return "CFA_advance_loc4"; + case DW_CFA_offset_extended: return "CFA_offset_extended"; + case DW_CFA_restore_extended: return "CFA_restore_extended"; + case DW_CFA_undefined: return "CFA_undefined"; + case DW_CFA_same_value: return "CFA_same_value"; + case DW_CFA_register: return "CFA_register"; + case DW_CFA_remember_state: return "CFA_remember_state"; + case DW_CFA_restore_state: return "CFA_restore_state"; + case DW_CFA_def_cfa: return "CFA_def_cfa"; + case DW_CFA_def_cfa_register: return "CFA_def_cfa_register"; + case DW_CFA_def_cfa_offset: return "CFA_def_cfa_offset"; + case DW_CFA_def_cfa_expression: return "CFA_def_cfa_expression"; + case DW_CFA_expression: return "CFA_expression"; + case DW_CFA_offset_extended_sf: return "CFA_offset_extended_sf"; + case DW_CFA_def_cfa_sf: return "CFA_def_cfa_sf"; + case DW_CFA_def_cfa_offset_sf: return "CFA_def_cfa_offset_sf"; + case DW_CFA_val_offset: return "CFA_val_offset"; + case DW_CFA_val_offset_sf: return "CFA_val_offset_sf"; + case DW_CFA_val_expression: return "CFA_val_expression"; + case DW_CFA_lo_user: return "CFA_lo_user"; + case DW_CFA_hi_user: return "CFA_hi_user"; } llvm_unreachable("Unknown Dwarf Call Frame Instruction Encodings"); return ""; From sabre at nondot.org Tue Dec 29 15:17:34 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 21:17:34 -0000 Subject: [llvm-commits] [llvm] r92268 - in /llvm/trunk: lib/Support/Dwarf.cpp lib/VMCore/AsmWriter.cpp test/Assembler/metadata.ll Message-ID: <200912292117.nBTLHY8j008701@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 15:17:33 2009 New Revision: 92268 URL: http://llvm.org/viewvc/llvm-project?rev=92268&view=rev Log: Do not crash when .ll printing metadata that smells like debug info, but isn't. Added: llvm/trunk/test/Assembler/metadata.ll Modified: llvm/trunk/lib/Support/Dwarf.cpp llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/Support/Dwarf.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Support/Dwarf.cpp?rev=92268&r1=92267&r2=92268&view=diff ============================================================================== --- llvm/trunk/lib/Support/Dwarf.cpp (original) +++ llvm/trunk/lib/Support/Dwarf.cpp Tue Dec 29 15:17:33 2009 @@ -12,8 +12,6 @@ //===----------------------------------------------------------------------===// #include "llvm/Support/Dwarf.h" -#include "llvm/Support/ErrorHandling.h" -#include using namespace llvm; using namespace dwarf; @@ -81,19 +79,17 @@ case DW_TAG_lo_user: return "DW_TAG_lo_user"; case DW_TAG_hi_user: return "DW_TAG_hi_user"; } - llvm_unreachable("Unknown Dwarf Tag"); - return ""; + return 0; } /// ChildrenString - Return the string for the specified children flag. /// const char *llvm::dwarf::ChildrenString(unsigned Children) { switch (Children) { - case DW_CHILDREN_no: return "CHILDREN_no"; - case DW_CHILDREN_yes: return "CHILDREN_yes"; + case DW_CHILDREN_no: return "CHILDREN_no"; + case DW_CHILDREN_yes: return "CHILDREN_yes"; } - llvm_unreachable("Unknown Dwarf ChildrenFlag"); - return ""; + return 0; } /// AttributeString - Return the string for the specified attribute. @@ -203,8 +199,7 @@ case DW_AT_APPLE_major_runtime_vers: return "DW_AT_APPLE_major_runtime_vers"; case DW_AT_APPLE_runtime_class: return "DW_AT_APPLE_runtime_class"; } - llvm_unreachable("Unknown Dwarf Attribute"); - return ""; + return 0; } /// FormEncodingString - Return the string for the specified form encoding. @@ -233,8 +228,7 @@ case DW_FORM_ref_udata: return "FORM_ref_udata"; case DW_FORM_indirect: return "FORM_indirect"; } - llvm_unreachable("Unknown Dwarf Form Encoding"); - return ""; + return 0; } /// OperationEncodingString - Return the string for the specified operation @@ -308,8 +302,7 @@ case DW_OP_lo_user: return "OP_lo_user"; case DW_OP_hi_user: return "OP_hi_user"; } - llvm_unreachable("Unknown Dwarf Operation Encoding"); - return ""; + return 0; } /// AttributeEncodingString - Return the string for the specified attribute @@ -334,8 +327,7 @@ case DW_ATE_lo_user: return "ATE_lo_user"; case DW_ATE_hi_user: return "ATE_hi_user"; } - llvm_unreachable("Unknown Dwarf Attribute Encoding"); - return ""; + return 0; } /// DecimalSignString - Return the string for the specified decimal sign @@ -348,8 +340,7 @@ case DW_DS_leading_separate: return "DS_leading_separate"; case DW_DS_trailing_separate: return "DS_trailing_separate"; } - llvm_unreachable("Unknown Dwarf Decimal Sign Attribute"); - return ""; + return 0; } /// EndianityString - Return the string for the specified endianity. @@ -362,8 +353,7 @@ case DW_END_lo_user: return "END_lo_user"; case DW_END_hi_user: return "END_hi_user"; } - llvm_unreachable("Unknown Dwarf Endianity"); - return ""; + return 0; } /// AccessibilityString - Return the string for the specified accessibility. @@ -375,8 +365,7 @@ case DW_ACCESS_protected: return "ACCESS_protected"; case DW_ACCESS_private: return "ACCESS_private"; } - llvm_unreachable("Unknown Dwarf Accessibility"); - return ""; + return 0; } /// VisibilityString - Return the string for the specified visibility. @@ -387,8 +376,7 @@ case DW_VIS_exported: return "VIS_exported"; case DW_VIS_qualified: return "VIS_qualified"; } - llvm_unreachable("Unknown Dwarf Visibility"); - return ""; + return 0; } /// VirtualityString - Return the string for the specified virtuality. @@ -399,8 +387,7 @@ case DW_VIRTUALITY_virtual: return "VIRTUALITY_virtual"; case DW_VIRTUALITY_pure_virtual: return "VIRTUALITY_pure_virtual"; } - llvm_unreachable("Unknown Dwarf Virtuality"); - return ""; + return 0; } /// LanguageString - Return the string for the specified language. @@ -429,8 +416,7 @@ case DW_LANG_lo_user: return "LANG_lo_user"; case DW_LANG_hi_user: return "LANG_hi_user"; } - llvm_unreachable("Unknown Dwarf Language"); - return ""; + return 0; } /// CaseString - Return the string for the specified identifier case. @@ -442,8 +428,7 @@ case DW_ID_down_case: return "ID_down_case"; case DW_ID_case_insensitive: return "ID_case_insensitive"; } - llvm_unreachable("Unknown Dwarf Identifier Case"); - return ""; + return 0; } /// ConventionString - Return the string for the specified calling convention. @@ -456,8 +441,7 @@ case DW_CC_lo_user: return "CC_lo_user"; case DW_CC_hi_user: return "CC_hi_user"; } - llvm_unreachable("Unknown Dwarf Calling Convention"); - return ""; + return 0; } /// InlineCodeString - Return the string for the specified inline code. @@ -469,8 +453,7 @@ case DW_INL_declared_not_inlined: return "INL_declared_not_inlined"; case DW_INL_declared_inlined: return "INL_declared_inlined"; } - llvm_unreachable("Unknown Dwarf Inline Code"); - return ""; + return 0; } /// ArrayOrderString - Return the string for the specified array order. @@ -480,8 +463,7 @@ case DW_ORD_row_major: return "ORD_row_major"; case DW_ORD_col_major: return "ORD_col_major"; } - llvm_unreachable("Unknown Dwarf Array Order"); - return ""; + return 0; } /// DiscriminantString - Return the string for the specified discriminant @@ -491,8 +473,7 @@ case DW_DSC_label: return "DSC_label"; case DW_DSC_range: return "DSC_range"; } - llvm_unreachable("Unknown Dwarf Discriminant Descriptor"); - return ""; + return 0; } /// LNStandardString - Return the string for the specified line number standard. @@ -512,8 +493,7 @@ case DW_LNS_set_epilogue_begin: return "LNS_set_epilogue_begin"; case DW_LNS_set_isa: return "LNS_set_isa"; } - llvm_unreachable("Unknown Dwarf Line Number Standard"); - return ""; + return 0; } /// LNExtendedString - Return the string for the specified line number extended @@ -527,8 +507,7 @@ case DW_LNE_lo_user: return "LNE_lo_user"; case DW_LNE_hi_user: return "LNE_hi_user"; } - llvm_unreachable("Unknown Dwarf Line Number Extended Opcode Encoding"); - return ""; + return 0; } /// MacinfoString - Return the string for the specified macinfo type encodings. @@ -542,8 +521,7 @@ case DW_MACINFO_end_file: return "MACINFO_end_file"; case DW_MACINFO_vendor_ext: return "MACINFO_vendor_ext"; } - llvm_unreachable("Unknown Dwarf Macinfo Type Encodings"); - return ""; + return 0; } /// CallFrameString - Return the string for the specified call frame instruction @@ -578,6 +556,5 @@ case DW_CFA_lo_user: return "CFA_lo_user"; case DW_CFA_hi_user: return "CFA_hi_user"; } - llvm_unreachable("Unknown Dwarf Call Frame Instruction Encodings"); - return ""; + return 0; } Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92268&r1=92267&r2=92268&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Tue Dec 29 15:17:33 2009 @@ -892,8 +892,8 @@ Out << "; [ DW_TAG_vector_type ]"; else if (Tag == dwarf::DW_TAG_user_base) Out << "; [ DW_TAG_user_base ]"; - else - Out << "; [ " << dwarf::TagString(Tag) << " ]"; + else if (const char *TagName = dwarf::TagString(Tag)) + Out << "; [ " << TagName << " ]"; } static void WriteMDNodes(formatted_raw_ostream &Out, TypePrinting &TypePrinter, @@ -1519,7 +1519,6 @@ static void PrintVisibility(GlobalValue::VisibilityTypes Vis, formatted_raw_ostream &Out) { switch (Vis) { - default: llvm_unreachable("Invalid visibility style!"); case GlobalValue::DefaultVisibility: break; case GlobalValue::HiddenVisibility: Out << "hidden "; break; case GlobalValue::ProtectedVisibility: Out << "protected "; break; Added: llvm/trunk/test/Assembler/metadata.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Assembler/metadata.ll?rev=92268&view=auto ============================================================================== --- llvm/trunk/test/Assembler/metadata.ll (added) +++ llvm/trunk/test/Assembler/metadata.ll Tue Dec 29 15:17:33 2009 @@ -0,0 +1,8 @@ +; RUN: llvm-as < %s | llvm-dis | llvm-as | llvm-dis | grep {ret void, !foo !0} +define void @test() { + ret void, !foo !0 +;, !bar !1 +} + +!0 = metadata !{i32 662302, i32 26, metadata !1, null} +!1 = metadata !{i32 4} From sabre at nondot.org Tue Dec 29 15:25:40 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 21:25:40 -0000 Subject: [llvm-commits] [llvm] r92270 - in /llvm/trunk: lib/AsmParser/LLParser.cpp test/Assembler/metadata.ll Message-ID: <200912292125.nBTLPeTf008948@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 15:25:40 2009 New Revision: 92270 URL: http://llvm.org/viewvc/llvm-project?rev=92270&view=rev Log: Each instruction is allowed to have *multiple* different metadata objects on them. Though the entire compiler supports this, the asmparser didn't. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/test/Assembler/metadata.ll Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92270&r1=92269&r2=92270&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 15:25:40 2009 @@ -1105,24 +1105,33 @@ /// ParseOptionalCustomMetadata /// ::= /* empty */ -/// ::= !dbg !42 +/// ::= !dbg !42 (',' !dbg !57)* bool LLParser::ParseOptionalCustomMetadata() { if (Lex.getKind() != lltok::NamedOrCustomMD) return false; - std::string Name = Lex.getStrVal(); - Lex.Lex(); + while (1) { + std::string Name = Lex.getStrVal(); + Lex.Lex(); - if (Lex.getKind() != lltok::Metadata) - return TokError("Expected '!' here"); - Lex.Lex(); + if (Lex.getKind() != lltok::Metadata) + return TokError("expected '!' here"); + Lex.Lex(); - MetadataBase *Node; - if (ParseMDNode(Node)) return true; + MetadataBase *Node; + if (ParseMDNode(Node)) return true; - unsigned MDK = M->getMDKindID(Name.c_str()); - MDsOnInst.push_back(std::make_pair(MDK, cast(Node))); - return false; + unsigned MDK = M->getMDKindID(Name.c_str()); + MDsOnInst.push_back(std::make_pair(MDK, cast(Node))); + + // If this is the end of the list, we're done. + if (!EatIfPresent(lltok::comma)) + return false; + + // The next value must be a custom metadata id. + if (Lex.getKind() != lltok::NamedOrCustomMD) + return TokError("expected more custom metadata ids"); + } } /// ParseOptionalAlignment @@ -3008,9 +3017,9 @@ //===----------------------------------------------------------------------===// /// ParseRet - Parse a return instruction. -/// ::= 'ret' void (',' !dbg, !1) -/// ::= 'ret' TypeAndValue (',' !dbg, !1) -/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1) +/// ::= 'ret' void (',' !dbg, !1)* +/// ::= 'ret' TypeAndValue (',' !dbg, !1)* +/// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)* /// [[obsolete: LLVM 3.0]] bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS) { @@ -3031,8 +3040,8 @@ if (ParseOptionalCustomMetadata()) return true; } else { // The normal case is one return value. - // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use - // of 'ret {i32,i32} {i32 1, i32 2}' + // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring + // use of 'ret {i32,i32} {i32 1, i32 2}' SmallVector RVs; RVs.push_back(RV); Modified: llvm/trunk/test/Assembler/metadata.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Assembler/metadata.ll?rev=92270&r1=92269&r2=92270&view=diff ============================================================================== --- llvm/trunk/test/Assembler/metadata.ll (original) +++ llvm/trunk/test/Assembler/metadata.ll Tue Dec 29 15:25:40 2009 @@ -1,7 +1,8 @@ -; RUN: llvm-as < %s | llvm-dis | llvm-as | llvm-dis | grep {ret void, !foo !0} +; RUN: llvm-as < %s | llvm-dis | llvm-as | llvm-dis | grep {ret void, !bar !1, !foo !0} define void @test() { - ret void, !foo !0 -;, !bar !1 + add i32 2, 1, !bar !0 + add i32 1, 2, !foo !1 + ret void, !foo !0, !bar !1 } !0 = metadata !{i32 662302, i32 26, metadata !1, null} From sabre at nondot.org Tue Dec 29 15:43:59 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 21:43:59 -0000 Subject: [llvm-commits] [llvm] r92272 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912292143.nBTLhxLv009615@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 15:43:58 2009 New Revision: 92272 URL: http://llvm.org/viewvc/llvm-project?rev=92272&view=rev Log: switch to TrackingVH instead of WeakVH, since these can never be RAUW'd and go to null. This also gets us some sorely lacking type safety. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92272&r1=92271&r2=92272&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 15:43:58 2009 @@ -472,29 +472,30 @@ // MDNode: // ::= '!' MDNodeNumber +// FIXME: Take an MDNode*&. bool LLParser::ParseMDNode(MetadataBase *&Node) { // !{ ..., !42, ... } unsigned MID = 0; - if (ParseUInt32(MID)) return true; + if (ParseUInt32(MID)) return true; // Check existing MDNode. - std::map::iterator I = MetadataCache.find(MID); + std::map >::iterator I = MetadataCache.find(MID); if (I != MetadataCache.end()) { - Node = cast(I->second); + Node = I->second; return false; } // Check known forward references. - std::map >::iterator + std::map, LocTy> >::iterator FI = ForwardRefMDNodes.find(MID); if (FI != ForwardRefMDNodes.end()) { - Node = cast(FI->second.first); + Node = FI->second.first; return false; } // Create MDNode forward reference - SmallVector Elts; std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID); + SmallVector Elts; Elts.push_back(MDString::get(Context, FwdRefName)); MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size()); ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); @@ -544,7 +545,7 @@ unsigned MetadataID = 0; if (ParseUInt32(MetadataID)) return true; - if (MetadataCache.find(MetadataID) != MetadataCache.end()) + if (MetadataCache.count(MetadataID)) return TokError("Metadata id is already used"); if (ParseToken(lltok::equal, "expected '=' here")) return true; @@ -568,11 +569,10 @@ MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size()); MetadataCache[MetadataID] = Init; - std::map >::iterator + std::map, LocTy> >::iterator FI = ForwardRefMDNodes.find(MetadataID); if (FI != ForwardRefMDNodes.end()) { - MDNode *FwdNode = cast(FI->second.first); - FwdNode->replaceAllUsesWith(Init); + FI->second.first->replaceAllUsesWith(Init); ForwardRefMDNodes.erase(FI); } Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92272&r1=92271&r2=92272&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 15:43:58 2009 @@ -17,8 +17,8 @@ #include "LLLexer.h" #include "llvm/Module.h" #include "llvm/Type.h" -#include #include "llvm/Support/ValueHandle.h" +#include namespace llvm { class Module; @@ -80,8 +80,8 @@ std::map > ForwardRefTypeIDs; std::vector NumberedTypes; /// MetadataCache - This map keeps track of parsed metadata constants. - std::map MetadataCache; - std::map > ForwardRefMDNodes; + std::map > MetadataCache; + std::map, LocTy> > ForwardRefMDNodes; SmallVector, 2> MDsOnInst; struct UpRefRecord { /// Loc - This is the location of the upref. From sabre at nondot.org Tue Dec 29 15:53:56 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 21:53:56 -0000 Subject: [llvm-commits] [llvm] r92273 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912292153.nBTLruUf009983@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 15:53:55 2009 New Revision: 92273 URL: http://llvm.org/viewvc/llvm-project?rev=92273&view=rev Log: change ParseMDString and ParseMDNode to take arguments of the right type. This exposed a raft of other problems, which I'll deal with in subsequent patches. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92273&r1=92272&r2=92273&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 15:53:55 2009 @@ -463,17 +463,16 @@ // MDString: // ::= '!' STRINGCONSTANT -bool LLParser::ParseMDString(MetadataBase *&MDS) { +bool LLParser::ParseMDString(MDString *&Result) { std::string Str; if (ParseStringConstant(Str)) return true; - MDS = MDString::get(Context, Str); + Result = MDString::get(Context, Str); return false; } // MDNode: // ::= '!' MDNodeNumber -// FIXME: Take an MDNode*&. -bool LLParser::ParseMDNode(MetadataBase *&Node) { +bool LLParser::ParseMDNode(MDNode *&Result) { // !{ ..., !42, ... } unsigned MID = 0; if (ParseUInt32(MID)) return true; @@ -481,7 +480,7 @@ // Check existing MDNode. std::map >::iterator I = MetadataCache.find(MID); if (I != MetadataCache.end()) { - Node = I->second; + Result = I->second; return false; } @@ -489,7 +488,7 @@ std::map, LocTy> >::iterator FI = ForwardRefMDNodes.find(MID); if (FI != ForwardRefMDNodes.end()) { - Node = FI->second.first; + Result = FI->second.first; return false; } @@ -499,7 +498,7 @@ Elts.push_back(MDString::get(Context, FwdRefName)); MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size()); ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); - Node = FwdNode; + Result = FwdNode; return false; } @@ -522,10 +521,13 @@ Lex.Lex(); SmallVector Elts; do { + // FIXME: Eat if present. if (Lex.getKind() != lltok::Metadata) return TokError("Expected '!' here"); Lex.Lex(); - MetadataBase *N = 0; + + // FIXME: Will crash on mdstrings etc. + MDNode *N = 0; if (ParseMDNode(N)) return true; Elts.push_back(N); } while (EatIfPresent(lltok::comma)); @@ -562,6 +564,7 @@ if (Lex.getKind() != lltok::lbrace) return TokError("Expected '{' here"); + // FIXME: This doesn't make sense here. SmallVector Elts; if (ParseMDNodeVector(Elts) || ParseToken(lltok::rbrace, "expected end of metadata node")) @@ -599,14 +602,16 @@ return false; } + // FIXME: This can't possibly work at all. r90497 + // Standalone metadata reference // !{ ..., !42, ... } - if (!ParseMDNode((MetadataBase *&)V)) + if (!ParseMDNode((MDNode *&)V)) return false; // MDString: // '!' STRINGCONSTANT - if (ParseMDString((MetadataBase *&)V)) return true; + if (ParseMDString((MDString *&)V)) return true; return false; } @@ -1118,11 +1123,11 @@ return TokError("expected '!' here"); Lex.Lex(); - MetadataBase *Node; + MDNode *Node; if (ParseMDNode(Node)) return true; unsigned MDK = M->getMDKindID(Name.c_str()); - MDsOnInst.push_back(std::make_pair(MDK, cast(Node))); + MDsOnInst.push_back(std::make_pair(MDK, Node)); // If this is the end of the list, we're done. if (!EatIfPresent(lltok::comma)) @@ -1937,6 +1942,8 @@ case lltok::Metadata: { // !{...} MDNode, !"foo" MDString ID.Kind = ValID::t_Metadata; Lex.Lex(); + + // FIXME: This doesn't belong here. if (Lex.getKind() == lltok::lbrace) { SmallVector Elts; if (ParseMDNodeVector(Elts) || @@ -1949,12 +1956,13 @@ // Standalone metadata reference // !{ ..., !42, ... } - if (!ParseMDNode(ID.MetadataVal)) + // FIXME: Split MetadataVal into one for MDNode and one for MDString. + if (!ParseMDNode((MDNode*&)ID.MetadataVal)) return false; // MDString: // ::= '!' STRINGCONSTANT - if (ParseMDString(ID.MetadataVal)) return true; + if (ParseMDString((MDString*&)ID.MetadataVal)) return true; ID.Kind = ValID::t_Metadata; return false; } @@ -3842,6 +3850,7 @@ Lex.Lex(); do { Value *V = 0; + // FIXME: REWRITE. if (Lex.getKind() == lltok::kw_null) { Lex.Lex(); V = 0; @@ -3850,11 +3859,11 @@ if (ParseType(Ty)) return true; if (Lex.getKind() == lltok::Metadata) { Lex.Lex(); - MetadataBase *Node = 0; + MDNode *Node = 0; if (!ParseMDNode(Node)) V = Node; else { - MetadataBase *MDS = 0; + MDString *MDS = 0; if (ParseMDString(MDS)) return true; V = MDS; } Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92273&r1=92272&r2=92273&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 15:53:55 2009 @@ -193,8 +193,8 @@ bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Visibility); bool ParseStandaloneMetadata(); bool ParseNamedMetadata(); - bool ParseMDString(MetadataBase *&S); - bool ParseMDNode(MetadataBase *&N); + bool ParseMDString(MDString *&Result); + bool ParseMDNode(MDNode *&Result); // Type Parsing. bool ParseType(PATypeHolder &Result, bool AllowVoid = false); From sabre at nondot.org Tue Dec 29 16:01:50 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 22:01:50 -0000 Subject: [llvm-commits] [llvm] r92275 - /llvm/trunk/lib/AsmParser/LLParser.cpp Message-ID: <200912292201.nBTM1ofB010439@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 16:01:50 2009 New Revision: 92275 URL: http://llvm.org/viewvc/llvm-project?rev=92275&view=rev Log: clean up some really strange code. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92275&r1=92274&r2=92275&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 16:01:50 2009 @@ -492,11 +492,12 @@ return false; } - // Create MDNode forward reference + // Create MDNode forward reference. + + // FIXME: This is not unique enough! std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID); - SmallVector Elts; - Elts.push_back(MDString::get(Context, FwdRefName)); - MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size()); + Value *V = MDString::get(Context, FwdRefName)); + MDNode *FwdNode = MDNode::get(Context, &V, 1); ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); Result = FwdNode; return false; @@ -521,12 +522,11 @@ Lex.Lex(); SmallVector Elts; do { - // FIXME: Eat if present. - if (Lex.getKind() != lltok::Metadata) - return TokError("Expected '!' here"); + if (ParseToken(lltok::Metadata, "Expected '!' here")) + return true; Lex.Lex(); - // FIXME: Will crash on mdstrings etc. + // FIXME: This rejects MDStrings. Are they legal in an named MDNode or not? MDNode *N = 0; if (ParseMDNode(N)) return true; Elts.push_back(N); From benny.kra at googlemail.com Tue Dec 29 16:17:06 2009 From: benny.kra at googlemail.com (Benjamin Kramer) Date: Tue, 29 Dec 2009 22:17:06 -0000 Subject: [llvm-commits] [llvm] r92277 - /llvm/trunk/lib/AsmParser/LLParser.cpp Message-ID: <200912292217.nBTMH61d010976@zion.cs.uiuc.edu> Author: d0k Date: Tue Dec 29 16:17:06 2009 New Revision: 92277 URL: http://llvm.org/viewvc/llvm-project?rev=92277&view=rev Log: remove a really wrong parenthesis. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92277&r1=92276&r2=92277&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 16:17:06 2009 @@ -496,7 +496,7 @@ // FIXME: This is not unique enough! std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID); - Value *V = MDString::get(Context, FwdRefName)); + Value *V = MDString::get(Context, FwdRefName); MDNode *FwdNode = MDNode::get(Context, &V, 1); ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); Result = FwdNode; From sabre at nondot.org Tue Dec 29 16:35:40 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 22:35:40 -0000 Subject: [llvm-commits] [llvm] r92279 - /llvm/trunk/lib/AsmParser/LLParser.cpp Message-ID: <200912292235.nBTMZeYp011660@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 16:35:39 2009 New Revision: 92279 URL: http://llvm.org/viewvc/llvm-project?rev=92279&view=rev Log: simplify some code and unbreak the build by not consuming an extra token. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92279&r1=92278&r2=92279&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 16:35:39 2009 @@ -503,28 +503,22 @@ return false; } -///ParseNamedMetadata: +/// ParseNamedMetadata: /// !foo = !{ !1, !2 } bool LLParser::ParseNamedMetadata() { assert(Lex.getKind() == lltok::NamedOrCustomMD); Lex.Lex(); std::string Name = Lex.getStrVal(); - if (ParseToken(lltok::equal, "expected '=' here")) + if (ParseToken(lltok::equal, "expected '=' here") || + ParseToken(lltok::Metadata, "Expected '!' here") || + ParseToken(lltok::lbrace, "Expected '{' here")) return true; - if (Lex.getKind() != lltok::Metadata) - return TokError("Expected '!' here"); - Lex.Lex(); - - if (Lex.getKind() != lltok::lbrace) - return TokError("Expected '{' here"); - Lex.Lex(); SmallVector Elts; do { if (ParseToken(lltok::Metadata, "Expected '!' here")) return true; - Lex.Lex(); // FIXME: This rejects MDStrings. Are they legal in an named MDNode or not? MDNode *N = 0; From sabre at nondot.org Tue Dec 29 16:40:21 2009 From: sabre at nondot.org (Chris Lattner) Date: Tue, 29 Dec 2009 22:40:21 -0000 Subject: [llvm-commits] [llvm] r92280 - /llvm/trunk/lib/AsmParser/LLParser.cpp Message-ID: <200912292240.nBTMeL1X011837@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 16:40:21 2009 New Revision: 92280 URL: http://llvm.org/viewvc/llvm-project?rev=92280&view=rev Log: factor code even more. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92280&r1=92279&r2=92280&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 16:40:21 2009 @@ -539,31 +539,23 @@ assert(Lex.getKind() == lltok::Metadata); Lex.Lex(); unsigned MetadataID = 0; - if (ParseUInt32(MetadataID)) - return true; - if (MetadataCache.count(MetadataID)) - return TokError("Metadata id is already used"); - if (ParseToken(lltok::equal, "expected '=' here")) - return true; LocTy TyLoc; PATypeHolder Ty(Type::getVoidTy(Context)); - if (ParseType(Ty, TyLoc)) - return true; - - if (Lex.getKind() != lltok::Metadata) - return TokError("Expected metadata here"); - - Lex.Lex(); - if (Lex.getKind() != lltok::lbrace) - return TokError("Expected '{' here"); - - // FIXME: This doesn't make sense here. SmallVector Elts; - if (ParseMDNodeVector(Elts) - || ParseToken(lltok::rbrace, "expected end of metadata node")) + // FIXME: This doesn't make sense here. Pull braced MD stuff parsing out! + if (ParseUInt32(MetadataID) || + ParseToken(lltok::equal, "expected '=' here") || + ParseType(Ty, TyLoc) || + ParseToken(lltok::Metadata, "Expected metadata here") || + ParseToken(lltok::lbrace, "Expected '{' here") || + ParseMDNodeVector(Elts) || + ParseToken(lltok::rbrace, "expected end of metadata node")) return true; + if (MetadataCache.count(MetadataID)) + return TokError("Metadata id is already used"); + MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size()); MetadataCache[MetadataID] = Init; std::map, LocTy> >::iterator @@ -585,14 +577,12 @@ V = 0; Lex.Lex(); - if (Lex.getKind() == lltok::lbrace) { - Lex.Lex(); + if (EatIfPresent(lltok::lbrace)) { if (ParseTypeAndValue(V, PFS) || ParseToken(lltok::rbrace, "expected end of metadata node")) return true; - Value *Vals[] = { V }; - V = MDNode::get(Context, Vals, 1); + V = MDNode::get(Context, &V, 1); return false; } @@ -1938,7 +1928,7 @@ Lex.Lex(); // FIXME: This doesn't belong here. - if (Lex.getKind() == lltok::lbrace) { + if (EatIfPresent(lltok::lbrace)) { SmallVector Elts; if (ParseMDNodeVector(Elts) || ParseToken(lltok::rbrace, "expected end of metadata node")) @@ -3840,8 +3830,6 @@ /// Element /// ::= 'null' | TypeAndValue bool LLParser::ParseMDNodeVector(SmallVectorImpl &Elts) { - assert(Lex.getKind() == lltok::lbrace); - Lex.Lex(); do { Value *V = 0; // FIXME: REWRITE. From gohman at apple.com Tue Dec 29 18:36:17 2009 From: gohman at apple.com (Dan Gohman) Date: Tue, 29 Dec 2009 16:36:17 -0800 Subject: [llvm-commits] [llvm] r91672 - in /llvm/trunk: lib/Target/X86/X86.td lib/Target/X86/X86InstrInfo.cpp lib/Target/X86/X86InstrInfo.td lib/Target/X86/X86InstrSSE.td lib/Target/X86/X86Subtarget.cpp lib/Target/X86/X86Subtarget.h test/CodeGen/X86/break-sse-dep.ll In-Reply-To: <99F7166D-548B-4DCC-AA22-FAD6616EC1D1@apple.com> References: <200912180740.nBI7eUQG026117@zion.cs.uiuc.edu> <1705660A-2565-4C04-943A-D8032B676037@apple.com> <7F1FB4E1-A63C-48CC-AB24-D1BDCC3BC1BF@apple.com> <0D89AF38-18FC-4407-9274-C843B83652D4@apple.com> <99F7166D-548B-4DCC-AA22-FAD6616EC1D1@apple.com> Message-ID: On Dec 21, 2009, at 11:13 AM, Chris Lattner wrote: > > On Dec 21, 2009, at 11:05 AM, Evan Cheng wrote: > >>> Unless there is a reason to have this, I'd prefer to not have it >>> clutter up the td files. I can't imagine a reasonable (non- >>> scalarizing) implementation of SSE that wouldn't have this issue. >> >> Really? It's a big surprise to Dan and I (and the engineer who >> noticed this) that unfolding the load actually breaks the register >> dependency. It's not documented anywhere in the public Intel manual. > > It was also surprising to me, but it makes perfect sense in > retrospect. If a scalar load zeros the top of the register, it > "obviously" has no dependence on the top bits coming in. No. The underlying problem is more subtle than that. The hardware phenomenon, and Evan's fix, only applies to *unary* operators, such as cvtss2sd, and not binary operators like addsd, mulss, etc. It really is surprising, and it really does make sense to have a subtarget flag here. > >>> For example, you didn't add this flag to any of the AMD chips. >> >> That's intentional. I don't have a AMD machine to try it on and I >> did not want to introduce a regression. > > I'm almost certain they have the same issue. It would be very suprising, actually. This should wait for someone with an AMD proccessor who can actually test this. > >> >> I don't really care that much whether it's a subtarget feature. If >> no one pipes up soon, I'll remove it. Please leave the flag in place. Dan > From gohman at apple.com Tue Dec 29 18:52:52 2009 From: gohman at apple.com (Dan Gohman) Date: Tue, 29 Dec 2009 16:52:52 -0800 Subject: [llvm-commits] [llvm] r85016 - /llvm/trunk/lib/Transforms/Scalar/LoopRotation.cpp In-Reply-To: <45E320E2-244A-4C08-982E-2CFE14B1AB14@apple.com> References: <200910242319.n9ONJrei025407@zion.cs.uiuc.edu> <6FE2703A-1167-451D-B151-E84B042B2378@apple.com> <7064681D-2A98-432F-A88E-53E851C2FFF4@apple.com> <45E320E2-244A-4C08-982E-2CFE14B1AB14@apple.com> Message-ID: <2D84CC2A-4048-437E-8F50-77D0C6845C29@apple.com> On Dec 20, 2009, at 11:38 PM, Chris Lattner wrote: > > On Oct 26, 2009, at 8:58 AM, Dan Gohman wrote: >>>> Author: djg >>>> Date: Sat Oct 24 18:19:52 2009 >>>> New Revision: 85016 >>>> >>>> URL: http://llvm.org/viewvc/llvm-project?rev=85016&view=rev >>>> Log: >>>> Rewrite LoopRotation's SSA updating code using SSAUpdater. >>> >>> Awesome, I didn't remember loop rotate had its own ssa update code. >>> >>> If, in your travels, you run into any cases where SSAUpdate is a >>> significant compile time issue, please give me a testcase. I have >>> many less-than-crazy ideas for speeding it up. >> >> One problem I'm seeing is redundant PHIs. Sphereflake for example >> now gets code like this: >> >> %p.013.i = phi %struct.node_t* [ %p.0.be.i, %bb5.backedge.i ], >> [ %78, %bb9.i ] ; <%struct.node_t*> [#uses=1] >> %p.012.i = phi %struct.node_t* [ %p.0.be.i, %bb5.backedge.i ], >> [ %78, %bb9.i ] ; <%struct.node_t*> [#uses=1] >> %p.011.i = phi %struct.node_t* [ %p.0.be.i, %bb5.backedge.i ], >> [ %78, %bb9.i ] ; <%struct.node_t*> [#uses=1] >> %p.010.i = phi %struct.node_t* [ %p.0.be.i, %bb5.backedge.i ], >> [ %78, %bb9.i ] ; <%struct.node_t*> [#uses=1] >> %p.09.i = phi %struct.node_t* [ %p.0.be.i, %bb5.backedge.i ], >> [ %78, %bb9.i ] ; <%struct.node_t*> [#uses=7] >> >> Indvars can't eliminate these because they aren't a function of the >> canonical induction variable. These PHIs stick around and end up >> being allocated registers, which is suboptimal. > > I finally found a good example that demonstrated this, PR5837, which > is now fixed. I recall that you added phi merging code to > simplifycfg or instcombine somewhere, do you think it makes sense to > remove this (potentially really expensive) optimization now? It's not really expensive; it's proportional to the size of the input in the worst case (ignoring worst case hash collisions). There's no other optimization that removes redundant phis like this. I guess if front-ends never emit phis and if all optimization passes which emit phis check existing phis (the ones I'm familiar with all do at this point), then this isn't needed. Otherwise it's still useful. Dan From clattner at apple.com Tue Dec 29 19:51:02 2009 From: clattner at apple.com (Chris Lattner) Date: Tue, 29 Dec 2009 17:51:02 -0800 Subject: [llvm-commits] [llvm] r91672 - in /llvm/trunk: lib/Target/X86/X86.td lib/Target/X86/X86InstrInfo.cpp lib/Target/X86/X86InstrInfo.td lib/Target/X86/X86InstrSSE.td lib/Target/X86/X86Subtarget.cpp lib/Target/X86/X86Subtarget.h test/CodeGen/X86/break-sse-dep.ll In-Reply-To: References: <200912180740.nBI7eUQG026117@zion.cs.uiuc.edu> <1705660A-2565-4C04-943A-D8032B676037@apple.com> <7F1FB4E1-A63C-48CC-AB24-D1BDCC3BC1BF@apple.com> <0D89AF38-18FC-4407-9274-C843B83652D4@apple.com> <99F7166D-548B-4DCC-AA22-FAD6616EC1D1@apple.com> Message-ID: <773B7D55-B2D0-406E-8AD7-8CA97F28FAEA@apple.com> On Dec 29, 2009, at 4:36 PM, Dan Gohman wrote: > > > On Dec 21, 2009, at 11:13 AM, Chris Lattner wrote: > >> >> On Dec 21, 2009, at 11:05 AM, Evan Cheng wrote: >> >>>> Unless there is a reason to have this, I'd prefer to not have it clutter up the td files. I can't imagine a reasonable (non-scalarizing) implementation of SSE that wouldn't have this issue. >>> >>> Really? It's a big surprise to Dan and I (and the engineer who noticed this) that unfolding the load actually breaks the register dependency. It's not documented anywhere in the public Intel manual. >> >> It was also surprising to me, but it makes perfect sense in retrospect. If a scalar load zeros the top of the register, it "obviously" has no dependence on the top bits coming in. > > No. The underlying problem is more subtle than that. The hardware phenomenon, and Evan's fix, only applies to *unary* operators, such as cvtss2sd, and not binary operators like addsd, mulss, etc. It really is surprising, and it really does make sense to have a subtarget flag here. > >> >>>> For example, you didn't add this flag to any of the AMD chips. >>> >>> That's intentional. I don't have a AMD machine to try it on and I did not want to introduce a regression. >> >> I'm almost certain they have the same issue. > > It would be very suprising, actually. This should wait for someone with an AMD proccessor who can actually test this. David already verified that AMD chips have exactly the same problem. -Chris From sabre at nondot.org Tue Dec 29 20:11:14 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 02:11:14 -0000 Subject: [llvm-commits] [llvm] r92287 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300211.nBU2BE2d018955@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 20:11:14 2009 New Revision: 92287 URL: http://llvm.org/viewvc/llvm-project?rev=92287&view=rev Log: split t_Metadata into t_MDNode and t_MDString, eliminating some unsafe casting. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92287&r1=92286&r2=92287&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 20:11:14 2009 @@ -1408,17 +1408,21 @@ if (ParseType(ArgTy, ArgLoc)) return true; + // Parse metadata operands to calls (for intrinsics). if (Lex.getKind() == lltok::Metadata) { if (ParseInlineMetadata(V, PFS)) return true; - } else { - if (ParseOptionalAttrs(ArgAttrs1, 0) || - ParseValue(ArgTy, V, PFS) || - // FIXME: Should not allow attributes after the argument, remove this - // in LLVM 3.0. - ParseOptionalAttrs(ArgAttrs2, 3)) - return true; + ArgList.push_back(ParamInfo(ArgLoc, V, Attribute::None)); + continue; } + + // Otherwise, handle normal operands. + if (ParseOptionalAttrs(ArgAttrs1, 0) || + ParseValue(ArgTy, V, PFS) || + // FIXME: Should not allow attributes after the argument, remove this + // in LLVM 3.0. + ParseOptionalAttrs(ArgAttrs2, 3)) + return true; ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2)); } @@ -1924,7 +1928,6 @@ ID.Kind = ValID::t_LocalName; break; case lltok::Metadata: { // !{...} MDNode, !"foo" MDString - ID.Kind = ValID::t_Metadata; Lex.Lex(); // FIXME: This doesn't belong here. @@ -1934,20 +1937,25 @@ ParseToken(lltok::rbrace, "expected end of metadata node")) return true; - ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size()); + ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size()); + ID.Kind = ValID::t_MDNode; return false; } // Standalone metadata reference // !{ ..., !42, ... } // FIXME: Split MetadataVal into one for MDNode and one for MDString. - if (!ParseMDNode((MDNode*&)ID.MetadataVal)) + if (!ParseMDNode(ID.MDNodeVal)) { + ID.Kind = ValID::t_MDNode; return false; + } + + // FIXME: This can't work. // MDString: // ::= '!' STRINGCONSTANT - if (ParseMDString((MDString*&)ID.MetadataVal)) return true; - ID.Kind = ValID::t_Metadata; + if (ParseMDString(ID.MDStringVal)) return true; + ID.Kind = ValID::t_MDString; return false; } case lltok::APSInt: @@ -2393,7 +2401,8 @@ switch (ID.Kind) { default: llvm_unreachable("Unknown ValID!"); - case ValID::t_Metadata: + case ValID::t_MDNode: + case ValID::t_MDString: return Error(ID.Loc, "invalid use of metadata"); case ValID::t_LocalID: case ValID::t_LocalName: @@ -2499,26 +2508,27 @@ bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V, PerFunctionState &PFS) { - if (ID.Kind == ValID::t_LocalID) - V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc); - else if (ID.Kind == ValID::t_LocalName) - V = PFS.GetVal(ID.StrVal, Ty, ID.Loc); - else if (ID.Kind == ValID::t_InlineAsm) { + switch (ID.Kind) { + case ValID::t_LocalID: V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc); break; + case ValID::t_LocalName: V = PFS.GetVal(ID.StrVal, Ty, ID.Loc); break; + case ValID::t_MDNode: V = ID.MDNodeVal; break; + case ValID::t_MDString: V = ID.MDStringVal; + case ValID::t_InlineAsm: { const PointerType *PTy = dyn_cast(Ty); const FunctionType *FTy = - PTy ? dyn_cast(PTy->getElementType()) : 0; + PTy ? dyn_cast(PTy->getElementType()) : 0; if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2)) return Error(ID.Loc, "invalid type for inline asm constraint string"); V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1); return false; - } else if (ID.Kind == ValID::t_Metadata) { - V = ID.MetadataVal; - } else { + } + default: { Constant *C; if (ConvertGlobalValIDToValue(Ty, ID, C)) return true; V = C; return false; } + } return V == 0; } Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92287&r1=92286&r2=92287&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 20:11:14 2009 @@ -46,7 +46,8 @@ t_EmptyArray, // No value: [] t_Constant, // Value in ConstantVal. t_InlineAsm, // Value in StrVal/StrVal2/UIntVal. - t_Metadata // Value in MetadataVal. + t_MDNode, // Value in MDNodeVal. + t_MDString // Value in MDStringVal. } Kind; LLLexer::LocTy Loc; @@ -55,7 +56,8 @@ APSInt APSIntVal; APFloat APFloatVal; Constant *ConstantVal; - MetadataBase *MetadataVal; + MDNode *MDNodeVal; + MDString *MDStringVal; ValID() : APFloatVal(0.0) {} bool operator<(const ValID &RHS) const { From sabre at nondot.org Tue Dec 29 20:20:07 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 02:20:07 -0000 Subject: [llvm-commits] [llvm] r92288 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300220.nBU2K7Sw019207@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 20:20:07 2009 New Revision: 92288 URL: http://llvm.org/viewvc/llvm-project?rev=92288&view=rev Log: remove the code added in r90497. It has several major issues and no tests. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92288&r1=92287&r2=92288&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 20:20:07 2009 @@ -568,37 +568,6 @@ return false; } -/// ParseInlineMetadata: -/// !{type %instr} -/// !{...} MDNode -/// !"foo" MDString -bool LLParser::ParseInlineMetadata(Value *&V, PerFunctionState &PFS) { - assert(Lex.getKind() == lltok::Metadata && "Only for Metadata"); - V = 0; - - Lex.Lex(); - if (EatIfPresent(lltok::lbrace)) { - if (ParseTypeAndValue(V, PFS) || - ParseToken(lltok::rbrace, "expected end of metadata node")) - return true; - - V = MDNode::get(Context, &V, 1); - return false; - } - - // FIXME: This can't possibly work at all. r90497 - - // Standalone metadata reference - // !{ ..., !42, ... } - if (!ParseMDNode((MDNode *&)V)) - return false; - - // MDString: - // '!' STRINGCONSTANT - if (ParseMDString((MDString *&)V)) return true; - return false; -} - /// ParseAlias: /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee /// Aliasee @@ -1408,14 +1377,6 @@ if (ParseType(ArgTy, ArgLoc)) return true; - // Parse metadata operands to calls (for intrinsics). - if (Lex.getKind() == lltok::Metadata) { - if (ParseInlineMetadata(V, PFS)) - return true; - ArgList.push_back(ParamInfo(ArgLoc, V, Attribute::None)); - continue; - } - // Otherwise, handle normal operands. if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS) || @@ -2515,8 +2476,8 @@ case ValID::t_MDString: V = ID.MDStringVal; case ValID::t_InlineAsm: { const PointerType *PTy = dyn_cast(Ty); - const FunctionType *FTy = - PTy ? dyn_cast(PTy->getElementType()) : 0; + const FunctionType *FTy = + PTy ? dyn_cast(PTy->getElementType()) : 0; if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2)) return Error(ID.Loc, "invalid type for inline asm constraint string"); V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1); Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92288&r1=92287&r2=92288&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 20:20:07 2009 @@ -283,8 +283,6 @@ return ParseTypeAndBasicBlock(BB, Loc, PFS); } - bool ParseInlineMetadata(Value *&V, PerFunctionState &PFS); - struct ParamInfo { LocTy Loc; Value *V; From clattner at apple.com Tue Dec 29 20:20:07 2009 From: clattner at apple.com (Chris Lattner) Date: Tue, 29 Dec 2009 18:20:07 -0800 Subject: [llvm-commits] [llvm] r90497 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h In-Reply-To: <200912032340.nB3Nex5D003399@zion.cs.uiuc.edu> References: <200912032340.nB3Nex5D003399@zion.cs.uiuc.edu> Message-ID: <694AA3AD-BF06-4294-9118-6CDBA42B7932@apple.com> On Dec 3, 2009, at 3:40 PM, Victor Hernandez wrote: > Author: hernande > Date: Thu Dec 3 17:40:58 2009 > New Revision: 90497 > > URL: http://llvm.org/viewvc/llvm-project?rev=90497&view=rev > Log: > Add ParseInlineMetadata() which can parses metadata that refers to an instruction. Extend ParseParameterList() to use this new function so that calls to llvm.dbg.declare can pass inline metadata Hi Victor, There are several problems with this: > +/// ParseInlineMetadata: > +/// !{type %instr} > +/// !{...} MDNode > +/// !"foo" MDString > +bool LLParser::ParseInlineMetadata(Value *&V, PerFunctionState &PFS) { > + assert(Lex.getKind() == lltok::Metadata && "Only for Metadata"); > + V = 0; This duplicates a lot of logic from other places. > + // Standalone metadata reference > + // !{ ..., !42, ... } > + if (!ParseMDNode((MetadataBase *&)V)) > + return false; This can't work. If the thing is not an mdnode, an error will be emitted. You can't continue after the error. There is no testcase for this patch and no extension to the langref documentation. I assume that this isn't used, because everything passes without it. I'm removing the code for the time being to make way for other cleanups. -Chris From sabre at nondot.org Tue Dec 29 22:13:37 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 04:13:37 -0000 Subject: [llvm-commits] [llvm] r92290 - in /llvm/trunk: lib/AsmParser/LLParser.cpp test/Assembler/metadata.ll Message-ID: <200912300413.nBU4DcCx023019@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 22:13:37 2009 New Revision: 92290 URL: http://llvm.org/viewvc/llvm-project?rev=92290&view=rev Log: fix parsing of mdstring values. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/test/Assembler/metadata.ll Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92290&r1=92289&r2=92290&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 22:13:37 2009 @@ -1888,7 +1888,7 @@ ID.StrVal = Lex.getStrVal(); ID.Kind = ValID::t_LocalName; break; - case lltok::Metadata: { // !{...} MDNode, !"foo" MDString + case lltok::Metadata: // !{...} MDNode, !"foo" MDString Lex.Lex(); // FIXME: This doesn't belong here. @@ -1905,20 +1905,17 @@ // Standalone metadata reference // !{ ..., !42, ... } - // FIXME: Split MetadataVal into one for MDNode and one for MDString. - if (!ParseMDNode(ID.MDNodeVal)) { + if (Lex.getKind() == lltok::APSInt) { + if (ParseMDNode(ID.MDNodeVal)) return true; ID.Kind = ValID::t_MDNode; return false; } - // FIXME: This can't work. - // MDString: // ::= '!' STRINGCONSTANT if (ParseMDString(ID.MDStringVal)) return true; ID.Kind = ValID::t_MDString; return false; - } case lltok::APSInt: ID.APSIntVal = Lex.getAPSIntVal(); ID.Kind = ValID::t_APSInt; @@ -2473,7 +2470,7 @@ case ValID::t_LocalID: V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc); break; case ValID::t_LocalName: V = PFS.GetVal(ID.StrVal, Ty, ID.Loc); break; case ValID::t_MDNode: V = ID.MDNodeVal; break; - case ValID::t_MDString: V = ID.MDStringVal; + case ValID::t_MDString: V = ID.MDStringVal; break; case ValID::t_InlineAsm: { const PointerType *PTy = dyn_cast(Ty); const FunctionType *FTy = Modified: llvm/trunk/test/Assembler/metadata.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Assembler/metadata.ll?rev=92290&r1=92289&r2=92290&view=diff ============================================================================== --- llvm/trunk/test/Assembler/metadata.ll (original) +++ llvm/trunk/test/Assembler/metadata.ll Tue Dec 29 22:13:37 2009 @@ -2,8 +2,16 @@ define void @test() { add i32 2, 1, !bar !0 add i32 1, 2, !foo !1 + + call void @llvm.dbg.func.start(metadata !"foo") + ret void, !foo !0, !bar !1 } !0 = metadata !{i32 662302, i32 26, metadata !1, null} !1 = metadata !{i32 4} + +declare void @llvm.dbg.func.start(metadata) nounwind readnone + + +; !foo = !{ !0, !"foo" } \ No newline at end of file From sabre at nondot.org Tue Dec 29 22:15:24 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 04:15:24 -0000 Subject: [llvm-commits] [llvm] r92291 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300415.nBU4FObc023086@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 22:15:23 2009 New Revision: 92291 URL: http://llvm.org/viewvc/llvm-project?rev=92291&view=rev Log: rename ParseMDNode -> ParseMDNodeID, since it parses !42, not !{... } as you'd expect. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92291&r1=92290&r2=92291&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 22:15:23 2009 @@ -472,7 +472,7 @@ // MDNode: // ::= '!' MDNodeNumber -bool LLParser::ParseMDNode(MDNode *&Result) { +bool LLParser::ParseMDNodeID(MDNode *&Result) { // !{ ..., !42, ... } unsigned MID = 0; if (ParseUInt32(MID)) return true; @@ -522,7 +522,7 @@ // FIXME: This rejects MDStrings. Are they legal in an named MDNode or not? MDNode *N = 0; - if (ParseMDNode(N)) return true; + if (ParseMDNodeID(N)) return true; Elts.push_back(N); } while (EatIfPresent(lltok::comma)); @@ -1077,7 +1077,7 @@ Lex.Lex(); MDNode *Node; - if (ParseMDNode(Node)) return true; + if (ParseMDNodeID(Node)) return true; unsigned MDK = M->getMDKindID(Name.c_str()); MDsOnInst.push_back(std::make_pair(MDK, Node)); @@ -1906,7 +1906,7 @@ // Standalone metadata reference // !{ ..., !42, ... } if (Lex.getKind() == lltok::APSInt) { - if (ParseMDNode(ID.MDNodeVal)) return true; + if (ParseMDNodeID(ID.MDNodeVal)) return true; ID.Kind = ValID::t_MDNode; return false; } @@ -3810,7 +3810,7 @@ if (Lex.getKind() == lltok::Metadata) { Lex.Lex(); MDNode *Node = 0; - if (!ParseMDNode(Node)) + if (!ParseMDNodeID(Node)) V = Node; else { MDString *MDS = 0; Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92291&r1=92290&r2=92291&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 22:15:23 2009 @@ -196,7 +196,7 @@ bool ParseStandaloneMetadata(); bool ParseNamedMetadata(); bool ParseMDString(MDString *&Result); - bool ParseMDNode(MDNode *&Result); + bool ParseMDNodeID(MDNode *&Result); // Type Parsing. bool ParseType(PATypeHolder &Result, bool AllowVoid = false); From sabre at nondot.org Tue Dec 29 22:42:58 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 04:42:58 -0000 Subject: [llvm-commits] [llvm] r92292 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300442.nBU4gxWZ023982@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 22:42:57 2009 New Revision: 92292 URL: http://llvm.org/viewvc/llvm-project?rev=92292&view=rev Log: rewrite ParseMDNodeVector to follow the normal patter used in the .ll parser. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92292&r1=92291&r2=92292&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 22:42:57 2009 @@ -2430,6 +2430,30 @@ } } +/// ConvertGlobalOrMetadataValIDToValue - Apply a type to a ValID to get a fully +/// resolved constant or metadata value. +bool LLParser::ConvertGlobalOrMetadataValIDToValue(const Type *Ty, ValID &ID, + Value *&V) { + switch (ID.Kind) { + case ValID::t_MDNode: + if (!Ty->isMetadataTy()) + return Error(ID.Loc, "metadata value must have metadata type"); + V = ID.MDNodeVal; + return false; + case ValID::t_MDString: + if (!Ty->isMetadataTy()) + return Error(ID.Loc, "metadata value must have metadata type"); + V = ID.MDStringVal; + return false; + default: + Constant *C; + if (ConvertGlobalValIDToValue(Ty, ID, C)) return true; + V = C; + return false; + } +} + + bool LLParser::ParseGlobalTypeAndValue(Constant *&V) { PATypeHolder Type(Type::getVoidTy(Context)); return ParseType(Type) || @@ -2469,8 +2493,6 @@ switch (ID.Kind) { case ValID::t_LocalID: V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc); break; case ValID::t_LocalName: V = PFS.GetVal(ID.StrVal, Ty, ID.Loc); break; - case ValID::t_MDNode: V = ID.MDNodeVal; break; - case ValID::t_MDString: V = ID.MDStringVal; break; case ValID::t_InlineAsm: { const PointerType *PTy = dyn_cast(Ty); const FunctionType *FTy = @@ -2480,12 +2502,8 @@ V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1); return false; } - default: { - Constant *C; - if (ConvertGlobalValIDToValue(Ty, ID, C)) return true; - V = C; - return false; - } + default: + return ConvertGlobalOrMetadataValIDToValue(Ty, ID, V); } return V == 0; @@ -3799,30 +3817,19 @@ /// ::= 'null' | TypeAndValue bool LLParser::ParseMDNodeVector(SmallVectorImpl &Elts) { do { - Value *V = 0; - // FIXME: REWRITE. - if (Lex.getKind() == lltok::kw_null) { - Lex.Lex(); - V = 0; - } else { - PATypeHolder Ty(Type::getVoidTy(Context)); - if (ParseType(Ty)) return true; - if (Lex.getKind() == lltok::Metadata) { - Lex.Lex(); - MDNode *Node = 0; - if (!ParseMDNodeID(Node)) - V = Node; - else { - MDString *MDS = 0; - if (ParseMDString(MDS)) return true; - V = MDS; - } - } else { - Constant *C; - if (ParseGlobalValue(Ty, C)) return true; - V = C; - } + // Null is a special case since it is typeless. + if (EatIfPresent(lltok::kw_null)) { + Elts.push_back(0); + continue; } + + Value *V = 0; + PATypeHolder Ty(Type::getVoidTy(Context)); + ValID ID; + if (ParseType(Ty) || ParseValID(ID) || + ConvertGlobalOrMetadataValIDToValue(Ty, ID, V)) + return true; + Elts.push_back(V); } while (EatIfPresent(lltok::comma)); Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92292&r1=92291&r2=92292&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 22:42:57 2009 @@ -213,6 +213,8 @@ // Constants. bool ParseValID(ValID &ID); bool ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, Constant *&V); + bool ConvertGlobalOrMetadataValIDToValue(const Type *Ty, ValID &ID, + Value *&V); bool ParseGlobalValue(const Type *Ty, Constant *&V); bool ParseGlobalTypeAndValue(Constant *&V); bool ParseGlobalValueVector(SmallVectorImpl &Elts); From sabre at nondot.org Tue Dec 29 22:51:59 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 04:51:59 -0000 Subject: [llvm-commits] [llvm] r92293 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300451.nBU4pxMg024245@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 22:51:58 2009 New Revision: 92293 URL: http://llvm.org/viewvc/llvm-project?rev=92293&view=rev Log: rename MetadataCache -> NumberedMetadata to follow the convention used by other things. Convert it to a vector since it is a dense numbering. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92293&r1=92292&r2=92293&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 22:51:58 2009 @@ -478,17 +478,8 @@ if (ParseUInt32(MID)) return true; // Check existing MDNode. - std::map >::iterator I = MetadataCache.find(MID); - if (I != MetadataCache.end()) { - Result = I->second; - return false; - } - - // Check known forward references. - std::map, LocTy> >::iterator - FI = ForwardRefMDNodes.find(MID); - if (FI != ForwardRefMDNodes.end()) { - Result = FI->second.first; + if (MID < NumberedMetadata.size() && NumberedMetadata[MID] != 0) { + Result = NumberedMetadata[MID]; return false; } @@ -499,6 +490,10 @@ Value *V = MDString::get(Context, FwdRefName); MDNode *FwdNode = MDNode::get(Context, &V, 1); ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc()); + + if (NumberedMetadata.size() <= MID) + NumberedMetadata.resize(MID+1); + NumberedMetadata[MID] = FwdNode; Result = FwdNode; return false; } @@ -553,16 +548,23 @@ ParseToken(lltok::rbrace, "expected end of metadata node")) return true; - if (MetadataCache.count(MetadataID)) - return TokError("Metadata id is already used"); - MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size()); - MetadataCache[MetadataID] = Init; + + // See if this was forward referenced, if so, handle it. std::map, LocTy> >::iterator FI = ForwardRefMDNodes.find(MetadataID); if (FI != ForwardRefMDNodes.end()) { FI->second.first->replaceAllUsesWith(Init); ForwardRefMDNodes.erase(FI); + + assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"); + } else { + if (MetadataID >= NumberedMetadata.size()) + NumberedMetadata.resize(MetadataID+1); + + if (NumberedMetadata[MetadataID] != 0) + return TokError("Metadata id is already used"); + NumberedMetadata[MetadataID] = Init; } return false; Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92293&r1=92292&r2=92293&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 22:51:58 2009 @@ -81,8 +81,7 @@ std::map > ForwardRefTypes; std::map > ForwardRefTypeIDs; std::vector NumberedTypes; - /// MetadataCache - This map keeps track of parsed metadata constants. - std::map > MetadataCache; + std::vector > NumberedMetadata; std::map, LocTy> > ForwardRefMDNodes; SmallVector, 2> MDsOnInst; struct UpRefRecord { From sabre at nondot.org Tue Dec 29 22:56:59 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 04:56:59 -0000 Subject: [llvm-commits] [llvm] r92294 - in /llvm/trunk/lib/AsmParser: LLLexer.cpp LLLexer.h LLParser.cpp LLToken.h Message-ID: <200912300457.nBU4v0iw024426@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 22:56:59 2009 New Revision: 92294 URL: http://llvm.org/viewvc/llvm-project?rev=92294&view=rev Log: rename lltok::Metadata -> lltok::exclaim. We name tokens after their syntactic form, not their semantic form. Modified: llvm/trunk/lib/AsmParser/LLLexer.cpp llvm/trunk/lib/AsmParser/LLLexer.h llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLToken.h Modified: llvm/trunk/lib/AsmParser/LLLexer.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLLexer.cpp?rev=92294&r1=92293&r2=92294&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLLexer.cpp (original) +++ llvm/trunk/lib/AsmParser/LLLexer.cpp Tue Dec 29 22:56:59 2009 @@ -254,7 +254,7 @@ case ';': SkipLineComment(); return LexToken(); - case '!': return LexMetadata(); + case '!': return LexExclaim(); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': @@ -422,11 +422,11 @@ return false; } -/// LexMetadata: +/// LexExclaim: /// !{...} /// !42 /// !foo -lltok::Kind LLLexer::LexMetadata() { +lltok::Kind LLLexer::LexExclaim() { if (isalpha(CurPtr[0])) { ++CurPtr; while (isalnum(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' || @@ -436,7 +436,7 @@ StrVal.assign(TokStart+1, CurPtr); // Skip ! return lltok::NamedOrCustomMD; } - return lltok::Metadata; + return lltok::exclaim; } /// LexIdentifier: Handle several related productions: Modified: llvm/trunk/lib/AsmParser/LLLexer.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLLexer.h?rev=92294&r1=92293&r2=92294&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLLexer.h (original) +++ llvm/trunk/lib/AsmParser/LLLexer.h Tue Dec 29 22:56:59 2009 @@ -75,7 +75,7 @@ lltok::Kind LexDigitOrNegative(); lltok::Kind LexPositive(); lltok::Kind LexAt(); - lltok::Kind LexMetadata(); + lltok::Kind LexExclaim(); lltok::Kind LexPercent(); lltok::Kind LexQuote(); lltok::Kind Lex0x(); Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92294&r1=92293&r2=92294&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 22:56:59 2009 @@ -168,7 +168,7 @@ case lltok::LocalVar: if (ParseNamedType()) return true; break; case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break; case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break; - case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break; + case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break; case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break; // The Global variable production with no name can have many different @@ -506,13 +506,13 @@ std::string Name = Lex.getStrVal(); if (ParseToken(lltok::equal, "expected '=' here") || - ParseToken(lltok::Metadata, "Expected '!' here") || + ParseToken(lltok::exclaim, "Expected '!' here") || ParseToken(lltok::lbrace, "Expected '{' here")) return true; SmallVector Elts; do { - if (ParseToken(lltok::Metadata, "Expected '!' here")) + if (ParseToken(lltok::exclaim, "Expected '!' here")) return true; // FIXME: This rejects MDStrings. Are they legal in an named MDNode or not? @@ -531,7 +531,7 @@ /// ParseStandaloneMetadata: /// !42 = !{...} bool LLParser::ParseStandaloneMetadata() { - assert(Lex.getKind() == lltok::Metadata); + assert(Lex.getKind() == lltok::exclaim); Lex.Lex(); unsigned MetadataID = 0; @@ -542,7 +542,7 @@ if (ParseUInt32(MetadataID) || ParseToken(lltok::equal, "expected '=' here") || ParseType(Ty, TyLoc) || - ParseToken(lltok::Metadata, "Expected metadata here") || + ParseToken(lltok::exclaim, "Expected '!' here") || ParseToken(lltok::lbrace, "Expected '{' here") || ParseMDNodeVector(Elts) || ParseToken(lltok::rbrace, "expected end of metadata node")) @@ -1074,12 +1074,10 @@ std::string Name = Lex.getStrVal(); Lex.Lex(); - if (Lex.getKind() != lltok::Metadata) - return TokError("expected '!' here"); - Lex.Lex(); - MDNode *Node; - if (ParseMDNodeID(Node)) return true; + if (ParseToken(lltok::exclaim, "expected '!' here") || + ParseMDNodeID(Node)) + return true; unsigned MDK = M->getMDKindID(Name.c_str()); MDsOnInst.push_back(std::make_pair(MDK, Node)); @@ -1890,7 +1888,7 @@ ID.StrVal = Lex.getStrVal(); ID.Kind = ValID::t_LocalName; break; - case lltok::Metadata: // !{...} MDNode, !"foo" MDString + case lltok::exclaim: // !{...} MDNode, !"foo" MDString Lex.Lex(); // FIXME: This doesn't belong here. Modified: llvm/trunk/lib/AsmParser/LLToken.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLToken.h?rev=92294&r1=92293&r2=92294&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLToken.h (original) +++ llvm/trunk/lib/AsmParser/LLToken.h Tue Dec 29 22:56:59 2009 @@ -29,6 +29,7 @@ less, greater, // < > lparen, rparen, // ( ) backslash, // \ (not /) + exclaim, // ! kw_x, kw_begin, kw_end, @@ -131,9 +132,6 @@ StringConstant, // "foo" NamedOrCustomMD, // !foo - // Metadata valued tokens. - Metadata, // !"foo" !{i8 42} - // Type valued tokens (TyVal). Type, From sabre at nondot.org Tue Dec 29 23:02:06 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 05:02:06 -0000 Subject: [llvm-commits] [llvm] r92295 - in /llvm/trunk/lib/AsmParser: LLLexer.cpp LLParser.cpp LLToken.h Message-ID: <200912300502.nBU526ZP024587@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 23:02:06 2009 New Revision: 92295 URL: http://llvm.org/viewvc/llvm-project?rev=92295&view=rev Log: rename NamedOrCustomMD -> MetadataVar to follow conventions of all the rest of the code. Modified: llvm/trunk/lib/AsmParser/LLLexer.cpp llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLToken.h Modified: llvm/trunk/lib/AsmParser/LLLexer.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLLexer.cpp?rev=92295&r1=92294&r2=92295&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLLexer.cpp (original) +++ llvm/trunk/lib/AsmParser/LLLexer.cpp Tue Dec 29 23:02:06 2009 @@ -423,10 +423,10 @@ } /// LexExclaim: -/// !{...} -/// !42 /// !foo +/// ! lltok::Kind LLLexer::LexExclaim() { + // Lex a metadata name as a MetadataVar. if (isalpha(CurPtr[0])) { ++CurPtr; while (isalnum(CurPtr[0]) || CurPtr[0] == '-' || CurPtr[0] == '$' || @@ -434,7 +434,7 @@ ++CurPtr; StrVal.assign(TokStart+1, CurPtr); // Skip ! - return lltok::NamedOrCustomMD; + return lltok::MetadataVar; } return lltok::exclaim; } Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92295&r1=92294&r2=92295&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 23:02:06 2009 @@ -169,7 +169,7 @@ case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break; case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break; case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break; - case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break; + case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break; // The Global variable production with no name can have many different // optional leading prefixes, the production is: @@ -501,9 +501,9 @@ /// ParseNamedMetadata: /// !foo = !{ !1, !2 } bool LLParser::ParseNamedMetadata() { - assert(Lex.getKind() == lltok::NamedOrCustomMD); - Lex.Lex(); + assert(Lex.getKind() == lltok::MetadataVar); std::string Name = Lex.getStrVal(); + Lex.Lex(); if (ParseToken(lltok::equal, "expected '=' here") || ParseToken(lltok::exclaim, "Expected '!' here") || @@ -1067,7 +1067,7 @@ /// ::= /* empty */ /// ::= !dbg !42 (',' !dbg !57)* bool LLParser::ParseOptionalCustomMetadata() { - if (Lex.getKind() != lltok::NamedOrCustomMD) + if (Lex.getKind() != lltok::MetadataVar) return false; while (1) { @@ -1087,7 +1087,7 @@ return false; // The next value must be a custom metadata id. - if (Lex.getKind() != lltok::NamedOrCustomMD) + if (Lex.getKind() != lltok::MetadataVar) return TokError("expected more custom metadata ids"); } } @@ -1112,7 +1112,7 @@ // FIXME: Handle customized metadata info attached with an instruction. do { - if (Lex.getKind() == lltok::NamedOrCustomMD) { + if (Lex.getKind() == lltok::MetadataVar) { if (ParseOptionalCustomMetadata()) return true; } else if (Lex.getKind() == lltok::kw_align) { if (ParseOptionalAlignment(Alignment)) return true; @@ -1131,7 +1131,8 @@ return TokError("expected ',' as start of index list"); while (EatIfPresent(lltok::comma)) { - if (Lex.getKind() == lltok::NamedOrCustomMD) + // FIXME: TERRIBLE HACK. Loses comma state. + if (Lex.getKind() == lltok::MetadataVar) break; unsigned Idx; if (ParseUInt32(Idx)) return true; @@ -2115,7 +2116,8 @@ ParseIndexList(Indices) || ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) return true; - if (Lex.getKind() == lltok::NamedOrCustomMD) + // FIXME: THIS ISN'T RIGHT? WHERE IS THE COMMA? + if (Lex.getKind() == lltok::MetadataVar) if (ParseOptionalCustomMetadata()) return true; if (!isa(Val->getType()) && !isa(Val->getType())) @@ -2139,7 +2141,7 @@ ParseIndexList(Indices) || ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) return true; - if (Lex.getKind() == lltok::NamedOrCustomMD) + if (Lex.getKind() == lltok::MetadataVar) if (ParseOptionalCustomMetadata()) return true; if (!isa(Val0->getType()) && !isa(Val0->getType())) return Error(ID.Loc, "extractvalue operand must be array or struct"); @@ -3014,7 +3016,7 @@ if (EatIfPresent(lltok::comma)) { // Parse optional custom metadata, e.g. !dbg - if (Lex.getKind() == lltok::NamedOrCustomMD) { + if (Lex.getKind() == lltok::MetadataVar) { if (ParseOptionalCustomMetadata()) return true; } else { // The normal case is one return value. @@ -3026,7 +3028,7 @@ do { // If optional custom metadata, e.g. !dbg is seen then this is the // end of MRV. - if (Lex.getKind() == lltok::NamedOrCustomMD) + if (Lex.getKind() == lltok::MetadataVar) break; if (ParseTypeAndValue(RV, PFS)) return true; RVs.push_back(RV); @@ -3485,7 +3487,7 @@ if (!EatIfPresent(lltok::comma)) break; - if (Lex.getKind() == lltok::NamedOrCustomMD) + if (Lex.getKind() == lltok::MetadataVar) break; if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || @@ -3496,7 +3498,7 @@ return true; } - if (Lex.getKind() == lltok::NamedOrCustomMD) + if (Lex.getKind() == lltok::MetadataVar) if (ParseOptionalCustomMetadata()) return true; if (!Ty->isFirstClassType()) @@ -3624,7 +3626,7 @@ if (EatIfPresent(lltok::comma)) { if (Lex.getKind() == lltok::kw_align - || Lex.getKind() == lltok::NamedOrCustomMD) { + || Lex.getKind() == lltok::MetadataVar) { if (ParseOptionalInfo(Alignment)) return true; } else { if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true; @@ -3744,14 +3746,14 @@ SmallVector Indices; while (EatIfPresent(lltok::comma)) { - if (Lex.getKind() == lltok::NamedOrCustomMD) + if (Lex.getKind() == lltok::MetadataVar) break; if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; if (!isa(Val->getType())) return Error(EltLoc, "getelementptr index must be an integer"); Indices.push_back(Val); } - if (Lex.getKind() == lltok::NamedOrCustomMD) + if (Lex.getKind() == lltok::MetadataVar) if (ParseOptionalCustomMetadata()) return true; if (!GetElementPtrInst::getIndexedType(Ptr->getType(), @@ -3771,7 +3773,7 @@ if (ParseTypeAndValue(Val, Loc, PFS) || ParseIndexList(Indices)) return true; - if (Lex.getKind() == lltok::NamedOrCustomMD) + if (Lex.getKind() == lltok::MetadataVar) if (ParseOptionalCustomMetadata()) return true; if (!isa(Val->getType()) && !isa(Val->getType())) @@ -3794,7 +3796,7 @@ ParseTypeAndValue(Val1, Loc1, PFS) || ParseIndexList(Indices)) return true; - if (Lex.getKind() == lltok::NamedOrCustomMD) + if (Lex.getKind() == lltok::MetadataVar) if (ParseOptionalCustomMetadata()) return true; if (!isa(Val0->getType()) && !isa(Val0->getType())) Modified: llvm/trunk/lib/AsmParser/LLToken.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLToken.h?rev=92295&r1=92294&r2=92295&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLToken.h (original) +++ llvm/trunk/lib/AsmParser/LLToken.h Tue Dec 29 23:02:06 2009 @@ -129,8 +129,8 @@ LabelStr, // foo: GlobalVar, // @foo @"foo" LocalVar, // %foo %"foo" + MetadataVar, // !foo StringConstant, // "foo" - NamedOrCustomMD, // !foo // Type valued tokens (TyVal). Type, From sabre at nondot.org Tue Dec 29 23:04:46 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 05:04:46 -0000 Subject: [llvm-commits] [llvm] r92296 - /llvm/trunk/lib/AsmParser/LLParser.cpp Message-ID: <200912300504.nBU54kL1024723@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 23:04:46 2009 New Revision: 92296 URL: http://llvm.org/viewvc/llvm-project?rev=92296&view=rev Log: remove two bogus calls that accepted metadata in the middle of insert/extract value *constant exprs*. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92296&r1=92295&r2=92296&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 23:04:46 2009 @@ -2116,9 +2116,6 @@ ParseIndexList(Indices) || ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) return true; - // FIXME: THIS ISN'T RIGHT? WHERE IS THE COMMA? - if (Lex.getKind() == lltok::MetadataVar) - if (ParseOptionalCustomMetadata()) return true; if (!isa(Val->getType()) && !isa(Val->getType())) return Error(ID.Loc, "extractvalue operand must be array or struct"); @@ -2141,8 +2138,6 @@ ParseIndexList(Indices) || ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) return true; - if (Lex.getKind() == lltok::MetadataVar) - if (ParseOptionalCustomMetadata()) return true; if (!isa(Val0->getType()) && !isa(Val0->getType())) return Error(ID.Loc, "extractvalue operand must be array or struct"); if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(), From sabre at nondot.org Tue Dec 29 23:14:00 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 05:14:00 -0000 Subject: [llvm-commits] [llvm] r92297 - in /llvm/trunk: lib/AsmParser/LLParser.cpp lib/AsmParser/LLParser.h test/Assembler/metadata.ll Message-ID: <200912300514.nBU5E1kW025016@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 23:14:00 2009 New Revision: 92297 URL: http://llvm.org/viewvc/llvm-project?rev=92297&view=rev Log: reimplement insertvalue/extractvalue metadata handling to not blindly accept invalid input. Actually add a testcase. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h llvm/trunk/test/Assembler/metadata.ll Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92297&r1=92296&r2=92297&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 23:14:00 2009 @@ -1124,16 +1124,27 @@ } +/// ParseIndexList - This parses the index list for an insert/extractvalue +/// instruction. This sets AteExtraComma in the case where we eat an extra +/// comma at the end of the line and find that it is followed by metadata. +/// Clients that don't allow metadata can call the version of this function that +/// only takes one argument. +/// /// ParseIndexList /// ::= (',' uint32)+ -bool LLParser::ParseIndexList(SmallVectorImpl &Indices) { +/// +bool LLParser::ParseIndexList(SmallVectorImpl &Indices, + bool &AteExtraComma) { + AteExtraComma = false; + if (Lex.getKind() != lltok::comma) return TokError("expected ',' as start of index list"); while (EatIfPresent(lltok::comma)) { - // FIXME: TERRIBLE HACK. Loses comma state. - if (Lex.getKind() == lltok::MetadataVar) - break; + if (Lex.getKind() == lltok::MetadataVar) { + AteExtraComma = true; + return false; + } unsigned Idx; if (ParseUInt32(Idx)) return true; Indices.push_back(Idx); @@ -2803,6 +2814,7 @@ } if (ParseInstruction(Inst, BB, PFS)) return true; + if (EatIfPresent(lltok::comma)) ParseOptionalCustomMetadata(); @@ -3765,11 +3777,14 @@ bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { Value *Val; LocTy Loc; SmallVector Indices; + bool ParsedExtraComma; if (ParseTypeAndValue(Val, Loc, PFS) || - ParseIndexList(Indices)) + ParseIndexList(Indices, ParsedExtraComma)) return true; - if (Lex.getKind() == lltok::MetadataVar) + if (ParsedExtraComma) { + assert(Lex.getKind() == lltok::MetadataVar && "Should only happen for md"); if (ParseOptionalCustomMetadata()) return true; + } if (!isa(Val->getType()) && !isa(Val->getType())) return Error(Loc, "extractvalue operand must be array or struct"); @@ -3786,14 +3801,17 @@ bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { Value *Val0, *Val1; LocTy Loc0, Loc1; SmallVector Indices; + bool ParsedExtraComma; if (ParseTypeAndValue(Val0, Loc0, PFS) || ParseToken(lltok::comma, "expected comma after insertvalue operand") || ParseTypeAndValue(Val1, Loc1, PFS) || - ParseIndexList(Indices)) + ParseIndexList(Indices, ParsedExtraComma)) return true; - if (Lex.getKind() == lltok::MetadataVar) + if (ParsedExtraComma) { + assert(Lex.getKind() == lltok::MetadataVar && "Should only happen for md"); if (ParseOptionalCustomMetadata()) return true; - + } + if (!isa(Val0->getType()) && !isa(Val0->getType())) return Error(Loc0, "extractvalue operand must be array or struct"); Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92297&r1=92296&r2=92297&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 23:14:00 2009 @@ -173,7 +173,14 @@ bool ParseOptionalAlignment(unsigned &Alignment); bool ParseOptionalCustomMetadata(); bool ParseOptionalInfo(unsigned &Alignment); - bool ParseIndexList(SmallVectorImpl &Indices); + bool ParseIndexList(SmallVectorImpl &Indices,bool &AteExtraComma); + bool ParseIndexList(SmallVectorImpl &Indices) { + bool AteExtraComma; + if (ParseIndexList(Indices, AteExtraComma)) return true; + if (AteExtraComma) + return TokError("expected index"); + return false; + } // Top-Level Entities bool ParseTopLevelEntities(); Modified: llvm/trunk/test/Assembler/metadata.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Assembler/metadata.ll?rev=92297&r1=92296&r2=92297&view=diff ============================================================================== --- llvm/trunk/test/Assembler/metadata.ll (original) +++ llvm/trunk/test/Assembler/metadata.ll Tue Dec 29 23:14:00 2009 @@ -5,11 +5,13 @@ call void @llvm.dbg.func.start(metadata !"foo") + extractvalue {{i32, i32}, i32} undef, 0, 1, !foo !0 + ret void, !foo !0, !bar !1 } !0 = metadata !{i32 662302, i32 26, metadata !1, null} -!1 = metadata !{i32 4} +!1 = metadata !{i32 4, metadata !"foo"} declare void @llvm.dbg.func.start(metadata) nounwind readnone From sabre at nondot.org Tue Dec 29 23:23:43 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 05:23:43 -0000 Subject: [llvm-commits] [llvm] r92298 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300523.nBU5Nhrg025309@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 23:23:43 2009 New Revision: 92298 URL: http://llvm.org/viewvc/llvm-project?rev=92298&view=rev Log: add facilities to start factoring instruction metadata parsing out of each opcode's handler. Change ret over so far. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92298&r1=92297&r2=92298&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 23:23:43 2009 @@ -2813,10 +2813,26 @@ return true; } - if (ParseInstruction(Inst, BB, PFS)) return true; - - if (EatIfPresent(lltok::comma)) - ParseOptionalCustomMetadata(); + switch (ParseInstruction(Inst, BB, PFS)) { + default: assert(0 && "Unknown ParseInstruction result!"); + case InstError: return true; + case InstNormal: + // With a normal result, we check to see if the instruction is followed by + // a comma and metadata. + if (EatIfPresent(lltok::comma)) + if (ParseOptionalCustomMetadata()) + return true; + break; + case InstExtraComma: + // If the instruction parser ate an extra comma at the end of it, it + // *must* be followed by metadata. + if (Lex.getKind() != lltok::MetadataVar) + return TokError("expected metadata after comma"); + // Parse it. + if (ParseOptionalCustomMetadata()) + return true; + break; + } // Set metadata attached with this instruction. for (SmallVector, 2>::iterator @@ -2839,8 +2855,8 @@ /// ParseInstruction - Parse one of the many different instructions. /// -bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, - PerFunctionState &PFS) { +int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB, + PerFunctionState &PFS) { lltok::Kind Token = Lex.getKind(); if (Token == lltok::Eof) return TokError("found end of file when expecting more instructions"); @@ -3008,8 +3024,8 @@ /// ::= 'ret' TypeAndValue (',' !dbg, !1)* /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)* /// [[obsolete: LLVM 3.0]] -bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, - PerFunctionState &PFS) { +int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB, + PerFunctionState &PFS) { PATypeHolder Ty(Type::getVoidTy(Context)); if (ParseType(Ty, true /*void allowed*/)) return true; @@ -3021,10 +3037,11 @@ Value *RV; if (ParseValue(Ty, RV, PFS)) return true; + bool ExtraComma = false; if (EatIfPresent(lltok::comma)) { // Parse optional custom metadata, e.g. !dbg if (Lex.getKind() == lltok::MetadataVar) { - if (ParseOptionalCustomMetadata()) return true; + ExtraComma = true; } else { // The normal case is one return value. // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring @@ -3051,7 +3068,7 @@ } Inst = ReturnInst::Create(Context, RV); - return false; + return ExtraComma ? InstExtraComma : InstNormal; } Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92298&r1=92297&r2=92298&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 23:23:43 2009 @@ -316,12 +316,14 @@ bool ParseFunctionBody(Function &Fn); bool ParseBasicBlock(PerFunctionState &PFS); - // Instruction Parsing. - bool ParseInstruction(Instruction *&Inst, BasicBlock *BB, - PerFunctionState &PFS); + // Instruction Parsing. Each instruction parsing routine can return with a + // normal result, an error result, or return having eaten an extra comma. + enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 }; + int ParseInstruction(Instruction *&Inst, BasicBlock *BB, + PerFunctionState &PFS); bool ParseCmpPredicate(unsigned &Pred, unsigned Opc); - bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS); + int ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS); bool ParseBr(Instruction *&Inst, PerFunctionState &PFS); bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS); bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS); From sabre at nondot.org Tue Dec 29 23:27:33 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 05:27:33 -0000 Subject: [llvm-commits] [llvm] r92299 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300527.nBU5RXWa025436@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 23:27:33 2009 New Revision: 92299 URL: http://llvm.org/viewvc/llvm-project?rev=92299&view=rev Log: convert 4 more instructions over. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92299&r1=92298&r2=92299&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 23:27:33 2009 @@ -3491,7 +3491,7 @@ /// ParsePHI /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* -bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { +int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) { PATypeHolder Ty(Type::getVoidTy(Context)); Value *Op0, *Op1; LocTy TypeLoc = Lex.getLoc(); @@ -3504,6 +3504,7 @@ ParseToken(lltok::rsquare, "expected ']' in phi value list")) return true; + bool AteExtraComma = false; SmallVector, 16> PHIVals; while (1) { PHIVals.push_back(std::make_pair(Op0, cast(Op1))); @@ -3511,8 +3512,10 @@ if (!EatIfPresent(lltok::comma)) break; - if (Lex.getKind() == lltok::MetadataVar) + if (Lex.getKind() == lltok::MetadataVar) { + AteExtraComma = true; break; + } if (ParseToken(lltok::lsquare, "expected '[' in phi value list") || ParseValue(Ty, Op0, PFS) || @@ -3522,9 +3525,6 @@ return true; } - if (Lex.getKind() == lltok::MetadataVar) - if (ParseOptionalCustomMetadata()) return true; - if (!Ty->isFirstClassType()) return Error(TypeLoc, "phi node must have first class type"); @@ -3533,7 +3533,7 @@ for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) PN->addIncoming(PHIVals[i].first, PHIVals[i].second); Inst = PN; - return false; + return AteExtraComma ? InstExtraComma : InstNormal; } /// ParseCall @@ -3758,7 +3758,7 @@ /// ParseGetElementPtr /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* -bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { +int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { Value *Ptr, *Val; LocTy Loc, EltLoc; bool InBounds = EatIfPresent(lltok::kw_inbounds); @@ -3769,16 +3769,17 @@ return Error(Loc, "base of getelementptr must be a pointer"); SmallVector Indices; + bool AteExtraComma = false; while (EatIfPresent(lltok::comma)) { - if (Lex.getKind() == lltok::MetadataVar) + if (Lex.getKind() == lltok::MetadataVar) { + AteExtraComma = true; break; + } if (ParseTypeAndValue(Val, EltLoc, PFS)) return true; if (!isa(Val->getType())) return Error(EltLoc, "getelementptr index must be an integer"); Indices.push_back(Val); } - if (Lex.getKind() == lltok::MetadataVar) - if (ParseOptionalCustomMetadata()) return true; if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices.begin(), Indices.end())) @@ -3786,22 +3787,18 @@ Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end()); if (InBounds) cast(Inst)->setIsInBounds(true); - return false; + return AteExtraComma ? InstExtraComma : InstNormal; } /// ParseExtractValue /// ::= 'extractvalue' TypeAndValue (',' uint32)+ -bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { +int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { Value *Val; LocTy Loc; SmallVector Indices; - bool ParsedExtraComma; + bool AteExtraComma; if (ParseTypeAndValue(Val, Loc, PFS) || - ParseIndexList(Indices, ParsedExtraComma)) + ParseIndexList(Indices, AteExtraComma)) return true; - if (ParsedExtraComma) { - assert(Lex.getKind() == lltok::MetadataVar && "Should only happen for md"); - if (ParseOptionalCustomMetadata()) return true; - } if (!isa(Val->getType()) && !isa(Val->getType())) return Error(Loc, "extractvalue operand must be array or struct"); @@ -3810,24 +3807,20 @@ Indices.end())) return Error(Loc, "invalid indices for extractvalue"); Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end()); - return false; + return AteExtraComma ? InstExtraComma : InstNormal; } /// ParseInsertValue /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ -bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { +int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { Value *Val0, *Val1; LocTy Loc0, Loc1; SmallVector Indices; - bool ParsedExtraComma; + bool AteExtraComma; if (ParseTypeAndValue(Val0, Loc0, PFS) || ParseToken(lltok::comma, "expected comma after insertvalue operand") || ParseTypeAndValue(Val1, Loc1, PFS) || - ParseIndexList(Indices, ParsedExtraComma)) + ParseIndexList(Indices, AteExtraComma)) return true; - if (ParsedExtraComma) { - assert(Lex.getKind() == lltok::MetadataVar && "Should only happen for md"); - if (ParseOptionalCustomMetadata()) return true; - } if (!isa(Val0->getType()) && !isa(Val0->getType())) return Error(Loc0, "extractvalue operand must be array or struct"); @@ -3836,7 +3829,7 @@ Indices.end())) return Error(Loc0, "invalid indices for insertvalue"); Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end()); - return false; + return AteExtraComma ? InstExtraComma : InstNormal; } //===----------------------------------------------------------------------===// Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92299&r1=92298&r2=92299&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 23:27:33 2009 @@ -339,7 +339,7 @@ bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS); bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS); bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS); - bool ParsePHI(Instruction *&I, PerFunctionState &PFS); + int ParsePHI(Instruction *&I, PerFunctionState &PFS); bool ParseCall(Instruction *&I, PerFunctionState &PFS, bool isTail); bool ParseAlloc(Instruction *&I, PerFunctionState &PFS, BasicBlock *BB = 0, bool isAlloca = true); @@ -347,9 +347,9 @@ bool ParseLoad(Instruction *&I, PerFunctionState &PFS, bool isVolatile); bool ParseStore(Instruction *&I, PerFunctionState &PFS, bool isVolatile); bool ParseGetResult(Instruction *&I, PerFunctionState &PFS); - bool ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS); - bool ParseExtractValue(Instruction *&I, PerFunctionState &PFS); - bool ParseInsertValue(Instruction *&I, PerFunctionState &PFS); + int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS); + int ParseExtractValue(Instruction *&I, PerFunctionState &PFS); + int ParseInsertValue(Instruction *&I, PerFunctionState &PFS); bool ResolveForwardRefBlockAddresses(Function *TheFn, std::vector > &Refs, From sabre at nondot.org Tue Dec 29 23:31:20 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 05:31:20 -0000 Subject: [llvm-commits] [llvm] r92300 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300531.nBU5VKFL025548@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 23:31:19 2009 New Revision: 92300 URL: http://llvm.org/viewvc/llvm-project?rev=92300&view=rev Log: rename ParseOptionalCustomMetadata -> ParseInstructionMetadata, and make it non-optional. This fixes the bug where we'd accept and ignore a spurious comma after some instructions. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92300&r1=92299&r2=92300&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 23:31:19 2009 @@ -1063,14 +1063,13 @@ return false; } -/// ParseOptionalCustomMetadata -/// ::= /* empty */ +/// ParseInstructionMetadata /// ::= !dbg !42 (',' !dbg !57)* -bool LLParser::ParseOptionalCustomMetadata() { - if (Lex.getKind() != lltok::MetadataVar) - return false; +bool LLParser::ParseInstructionMetadata() { + do { + if (Lex.getKind() != lltok::MetadataVar) + return TokError("expected metadata after comma"); - while (1) { std::string Name = Lex.getStrVal(); Lex.Lex(); @@ -1083,13 +1082,8 @@ MDsOnInst.push_back(std::make_pair(MDK, Node)); // If this is the end of the list, we're done. - if (!EatIfPresent(lltok::comma)) - return false; - - // The next value must be a custom metadata id. - if (Lex.getKind() != lltok::MetadataVar) - return TokError("expected more custom metadata ids"); - } + } while (EatIfPresent(lltok::comma)); + return false; } /// ParseOptionalAlignment @@ -1113,7 +1107,7 @@ // FIXME: Handle customized metadata info attached with an instruction. do { if (Lex.getKind() == lltok::MetadataVar) { - if (ParseOptionalCustomMetadata()) return true; + if (ParseInstructionMetadata()) return true; } else if (Lex.getKind() == lltok::kw_align) { if (ParseOptionalAlignment(Alignment)) return true; } else @@ -2820,16 +2814,13 @@ // With a normal result, we check to see if the instruction is followed by // a comma and metadata. if (EatIfPresent(lltok::comma)) - if (ParseOptionalCustomMetadata()) + if (ParseInstructionMetadata()) return true; break; case InstExtraComma: // If the instruction parser ate an extra comma at the end of it, it // *must* be followed by metadata. - if (Lex.getKind() != lltok::MetadataVar) - return TokError("expected metadata after comma"); - // Parse it. - if (ParseOptionalCustomMetadata()) + if (ParseInstructionMetadata()) return true; break; } Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92300&r1=92299&r2=92300&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 23:31:19 2009 @@ -171,7 +171,7 @@ bool ParseOptionalVisibility(unsigned &Visibility); bool ParseOptionalCallingConv(CallingConv::ID &CC); bool ParseOptionalAlignment(unsigned &Alignment); - bool ParseOptionalCustomMetadata(); + bool ParseInstructionMetadata(); bool ParseOptionalInfo(unsigned &Alignment); bool ParseIndexList(SmallVectorImpl &Indices,bool &AteExtraComma); bool ParseIndexList(SmallVectorImpl &Indices) { From sabre at nondot.org Tue Dec 29 23:44:31 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 05:44:31 -0000 Subject: [llvm-commits] [llvm] r92301 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300544.nBU5iV8R025937@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 23:44:30 2009 New Revision: 92301 URL: http://llvm.org/viewvc/llvm-project?rev=92301&view=rev Log: reimplement ParseOptionalInfo as ParseOptionalCommaAlign, correctly handle the comma case for metadata. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92301&r1=92300&r2=92301&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 23:44:30 2009 @@ -1100,19 +1100,27 @@ return false; } -/// ParseOptionalInfo -/// ::= OptionalInfo (',' OptionalInfo)+ -bool LLParser::ParseOptionalInfo(unsigned &Alignment) { - - // FIXME: Handle customized metadata info attached with an instruction. - do { +/// ParseOptionalCommaAlign +/// ::= +/// ::= ',' align 4 +/// +/// This returns with AteExtraComma set to true if it ate an excess comma at the +/// end. +bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment, + bool &AteExtraComma) { + AteExtraComma = false; + while (EatIfPresent(lltok::comma)) { + // Metadata at the end is an early exit. if (Lex.getKind() == lltok::MetadataVar) { - if (ParseInstructionMetadata()) return true; - } else if (Lex.getKind() == lltok::kw_align) { + AteExtraComma = true; + return false; + } + + if (Lex.getKind() == lltok::kw_align) { if (ParseOptionalAlignment(Alignment)) return true; } else return true; - } while (EatIfPresent(lltok::comma)); + } return false; } @@ -3631,22 +3639,24 @@ /// ParseAlloc /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)? /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)? -bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS, - BasicBlock* BB, bool isAlloca) { +int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS, + BasicBlock* BB, bool isAlloca) { PATypeHolder Ty(Type::getVoidTy(Context)); Value *Size = 0; LocTy SizeLoc; unsigned Alignment = 0; if (ParseType(Ty)) return true; + bool AteExtraComma = false; if (EatIfPresent(lltok::comma)) { - if (Lex.getKind() == lltok::kw_align - || Lex.getKind() == lltok::MetadataVar) { - if (ParseOptionalInfo(Alignment)) return true; + if (Lex.getKind() == lltok::kw_align) { + if (ParseOptionalAlignment(Alignment)) return true; + } else if (Lex.getKind() == lltok::MetadataVar) { + AteExtraComma = true; } else { - if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true; - if (EatIfPresent(lltok::comma)) - if (ParseOptionalInfo(Alignment)) return true; + if (ParseTypeAndValue(Size, SizeLoc, PFS) || + ParseOptionalCommaAlign(Alignment, AteExtraComma)) + return true; } } @@ -3655,7 +3665,7 @@ if (isAlloca) { Inst = new AllocaInst(Ty, Size, Alignment); - return false; + return AteExtraComma ? InstExtraComma : InstNormal; } // Autoupgrade old malloc instruction to malloc call. @@ -3669,7 +3679,7 @@ MallocF = cast( M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL)); Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF); - return false; +return AteExtraComma ? InstExtraComma : InstNormal; } /// ParseFree @@ -3686,37 +3696,36 @@ /// ParseLoad /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)? -bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS, - bool isVolatile) { +int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS, + bool isVolatile) { Value *Val; LocTy Loc; unsigned Alignment = 0; - if (ParseTypeAndValue(Val, Loc, PFS)) return true; - - if (EatIfPresent(lltok::comma)) - if (ParseOptionalInfo(Alignment)) return true; + bool AteExtraComma = false; + if (ParseTypeAndValue(Val, Loc, PFS) || + ParseOptionalCommaAlign(Alignment, AteExtraComma)) + return true; if (!isa(Val->getType()) || !cast(Val->getType())->getElementType()->isFirstClassType()) return Error(Loc, "load operand must be a pointer to a first class type"); Inst = new LoadInst(Val, "", isVolatile, Alignment); - return false; + return AteExtraComma ? InstExtraComma : InstNormal; } /// ParseStore /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)? -bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS, - bool isVolatile) { +int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS, + bool isVolatile) { Value *Val, *Ptr; LocTy Loc, PtrLoc; unsigned Alignment = 0; + bool AteExtraComma = false; if (ParseTypeAndValue(Val, Loc, PFS) || ParseToken(lltok::comma, "expected ',' after store operand") || - ParseTypeAndValue(Ptr, PtrLoc, PFS)) + ParseTypeAndValue(Ptr, PtrLoc, PFS) || + ParseOptionalCommaAlign(Alignment, AteExtraComma)) return true; - if (EatIfPresent(lltok::comma)) - if (ParseOptionalInfo(Alignment)) return true; - if (!isa(Ptr->getType())) return Error(PtrLoc, "store operand must be a pointer"); if (!Val->getType()->isFirstClassType()) @@ -3725,7 +3734,7 @@ return Error(Loc, "stored value and pointer type do not match"); Inst = new StoreInst(Val, Ptr, isVolatile, Alignment); - return false; + return AteExtraComma ? InstExtraComma : InstNormal; } /// ParseGetResult Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92301&r1=92300&r2=92301&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 23:44:30 2009 @@ -172,7 +172,7 @@ bool ParseOptionalCallingConv(CallingConv::ID &CC); bool ParseOptionalAlignment(unsigned &Alignment); bool ParseInstructionMetadata(); - bool ParseOptionalInfo(unsigned &Alignment); + bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma); bool ParseIndexList(SmallVectorImpl &Indices,bool &AteExtraComma); bool ParseIndexList(SmallVectorImpl &Indices) { bool AteExtraComma; @@ -341,11 +341,11 @@ bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS); int ParsePHI(Instruction *&I, PerFunctionState &PFS); bool ParseCall(Instruction *&I, PerFunctionState &PFS, bool isTail); - bool ParseAlloc(Instruction *&I, PerFunctionState &PFS, + int ParseAlloc(Instruction *&I, PerFunctionState &PFS, BasicBlock *BB = 0, bool isAlloca = true); bool ParseFree(Instruction *&I, PerFunctionState &PFS, BasicBlock *BB); - bool ParseLoad(Instruction *&I, PerFunctionState &PFS, bool isVolatile); - bool ParseStore(Instruction *&I, PerFunctionState &PFS, bool isVolatile); + int ParseLoad(Instruction *&I, PerFunctionState &PFS, bool isVolatile); + int ParseStore(Instruction *&I, PerFunctionState &PFS, bool isVolatile); bool ParseGetResult(Instruction *&I, PerFunctionState &PFS); int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS); int ParseExtractValue(Instruction *&I, PerFunctionState &PFS); From sabre at nondot.org Tue Dec 29 23:48:36 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 05:48:36 -0000 Subject: [llvm-commits] [llvm] r92302 - in /llvm/trunk/lib/AsmParser: LLParser.cpp LLParser.h Message-ID: <200912300548.nBU5ma59026097@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 23:48:36 2009 New Revision: 92302 URL: http://llvm.org/viewvc/llvm-project?rev=92302&view=rev Log: now that instruction metadata is only parsed in one place, eliminate the parser-global MDsOnInst vector and make ParseInstructionMetadata return its result by-ref through an argument like the entire rest of the parser. Modified: llvm/trunk/lib/AsmParser/LLParser.cpp llvm/trunk/lib/AsmParser/LLParser.h Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92302&r1=92301&r2=92302&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Tue Dec 29 23:48:36 2009 @@ -1065,7 +1065,9 @@ /// ParseInstructionMetadata /// ::= !dbg !42 (',' !dbg !57)* -bool LLParser::ParseInstructionMetadata() { +bool LLParser:: +ParseInstructionMetadata(SmallVectorImpl > &Result){ do { if (Lex.getKind() != lltok::MetadataVar) return TokError("expected metadata after comma"); @@ -1079,7 +1081,7 @@ return true; unsigned MDK = M->getMDKindID(Name.c_str()); - MDsOnInst.push_back(std::make_pair(MDK, Node)); + Result.push_back(std::make_pair(MDK, Node)); // If this is the end of the list, we're done. } while (EatIfPresent(lltok::comma)); @@ -2794,6 +2796,7 @@ // Parse the instructions in this block until we get a terminator. Instruction *Inst; + SmallVector, 4> MetadataOnInst; do { // This instruction may have three possibilities for a name: a) none // specified, b) name specified "%foo =", c) number specified: "%4 =". @@ -2822,22 +2825,21 @@ // With a normal result, we check to see if the instruction is followed by // a comma and metadata. if (EatIfPresent(lltok::comma)) - if (ParseInstructionMetadata()) + if (ParseInstructionMetadata(MetadataOnInst)) return true; break; case InstExtraComma: // If the instruction parser ate an extra comma at the end of it, it // *must* be followed by metadata. - if (ParseInstructionMetadata()) + if (ParseInstructionMetadata(MetadataOnInst)) return true; break; } // Set metadata attached with this instruction. - for (SmallVector, 2>::iterator - MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI) - Inst->setMetadata(MDI->first, MDI->second); - MDsOnInst.clear(); + for (unsigned i = 0, e = MetadataOnInst.size(); i != e; ++i) + Inst->setMetadata(MetadataOnInst[i].first, MetadataOnInst[i].second); + MetadataOnInst.clear(); BB->getInstList().push_back(Inst); Modified: llvm/trunk/lib/AsmParser/LLParser.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.h?rev=92302&r1=92301&r2=92302&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.h (original) +++ llvm/trunk/lib/AsmParser/LLParser.h Tue Dec 29 23:48:36 2009 @@ -83,7 +83,6 @@ std::vector NumberedTypes; std::vector > NumberedMetadata; std::map, LocTy> > ForwardRefMDNodes; - SmallVector, 2> MDsOnInst; struct UpRefRecord { /// Loc - This is the location of the upref. LocTy Loc; @@ -171,7 +170,8 @@ bool ParseOptionalVisibility(unsigned &Visibility); bool ParseOptionalCallingConv(CallingConv::ID &CC); bool ParseOptionalAlignment(unsigned &Alignment); - bool ParseInstructionMetadata(); + bool ParseInstructionMetadata(SmallVectorImpl > &); bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma); bool ParseIndexList(SmallVectorImpl &Indices,bool &AteExtraComma); bool ParseIndexList(SmallVectorImpl &Indices) { From sabre at nondot.org Tue Dec 29 23:54:51 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 05:54:51 -0000 Subject: [llvm-commits] [llvm] r92303 - in /llvm/trunk/test/Transforms: GlobalOpt/heap-sra-3.ll SimplifyCFG/duplicate-phis.ll Message-ID: <200912300554.nBU5spIY026316@zion.cs.uiuc.edu> Author: lattner Date: Tue Dec 29 23:54:51 2009 New Revision: 92303 URL: http://llvm.org/viewvc/llvm-project?rev=92303&view=rev Log: fix two bogus tests that the asmparser now rejects. Modified: llvm/trunk/test/Transforms/GlobalOpt/heap-sra-3.ll llvm/trunk/test/Transforms/SimplifyCFG/duplicate-phis.ll Modified: llvm/trunk/test/Transforms/GlobalOpt/heap-sra-3.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/GlobalOpt/heap-sra-3.ll?rev=92303&r1=92302&r2=92303&view=diff ============================================================================== --- llvm/trunk/test/Transforms/GlobalOpt/heap-sra-3.ll (original) +++ llvm/trunk/test/Transforms/GlobalOpt/heap-sra-3.ll Tue Dec 29 23:54:51 2009 @@ -8,7 +8,7 @@ define void @bar(i64 %Size) nounwind noinline { entry: - %mallocsize = mul i64 8, %Size, ; [#uses=1] + %mallocsize = mul i64 8, %Size ; [#uses=1] ; CHECK: mul i64 %Size, 4 %malloccall = tail call i8* @malloc(i64 %mallocsize) ; [#uses=1] %.sub = bitcast i8* %malloccall to %struct.foo* ; <%struct.foo*> [#uses=1] Modified: llvm/trunk/test/Transforms/SimplifyCFG/duplicate-phis.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/SimplifyCFG/duplicate-phis.ll?rev=92303&r1=92302&r2=92303&view=diff ============================================================================== --- llvm/trunk/test/Transforms/SimplifyCFG/duplicate-phis.ll (original) +++ llvm/trunk/test/Transforms/SimplifyCFG/duplicate-phis.ll Tue Dec 29 23:54:51 2009 @@ -6,7 +6,7 @@ define i32 @foo(i1 %t) { entry: call void @bar() - br i1 %t, label %true, label %false, + br i1 %t, label %true, label %false true: call void @bar() br label %false From sabre at nondot.org Wed Dec 30 00:00:36 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 06:00:36 -0000 Subject: [llvm-commits] [llvm] r92304 - /llvm/trunk/lib/AsmParser/LLParser.cpp Message-ID: <200912300600.nBU60aaC026488@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 00:00:36 2009 New Revision: 92304 URL: http://llvm.org/viewvc/llvm-project?rev=92304&view=rev Log: remove some fixme's Modified: llvm/trunk/lib/AsmParser/LLParser.cpp Modified: llvm/trunk/lib/AsmParser/LLParser.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/AsmParser/LLParser.cpp?rev=92304&r1=92303&r2=92304&view=diff ============================================================================== --- llvm/trunk/lib/AsmParser/LLParser.cpp (original) +++ llvm/trunk/lib/AsmParser/LLParser.cpp Wed Dec 30 00:00:36 2009 @@ -538,7 +538,6 @@ LocTy TyLoc; PATypeHolder Ty(Type::getVoidTy(Context)); SmallVector Elts; - // FIXME: This doesn't make sense here. Pull braced MD stuff parsing out! if (ParseUInt32(MetadataID) || ParseToken(lltok::equal, "expected '=' here") || ParseType(Ty, TyLoc) || @@ -1907,7 +1906,6 @@ case lltok::exclaim: // !{...} MDNode, !"foo" MDString Lex.Lex(); - // FIXME: This doesn't belong here. if (EatIfPresent(lltok::lbrace)) { SmallVector Elts; if (ParseMDNodeVector(Elts) || From dgregor at apple.com Wed Dec 30 11:23:44 2009 From: dgregor at apple.com (Douglas Gregor) Date: Wed, 30 Dec 2009 17:23:44 -0000 Subject: [llvm-commits] [llvm] r92309 - in /llvm/trunk: include/llvm/ADT/StringRef.h lib/Support/StringRef.cpp Message-ID: <200912301723.nBUHNiO4000671@zion.cs.uiuc.edu> Author: dgregor Date: Wed Dec 30 11:23:44 2009 New Revision: 92309 URL: http://llvm.org/viewvc/llvm-project?rev=92309&view=rev Log: Implement edit distance for StringRef Modified: llvm/trunk/include/llvm/ADT/StringRef.h llvm/trunk/lib/Support/StringRef.cpp Modified: llvm/trunk/include/llvm/ADT/StringRef.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/StringRef.h?rev=92309&r1=92308&r2=92309&view=diff ============================================================================== --- llvm/trunk/include/llvm/ADT/StringRef.h (original) +++ llvm/trunk/include/llvm/ADT/StringRef.h Wed Dec 30 11:23:44 2009 @@ -133,6 +133,22 @@ /// compare_lower - Compare two strings, ignoring case. int compare_lower(StringRef RHS) const; + /// \brief Determine the edit distance between this string and another + /// string. + /// + /// \param Other the string to compare this string against. + /// + /// \param AllowReplacements whether to allow character + /// replacements (change one character into another) as a single + /// operation, rather than as two operations (an insertion and a + /// removal). + /// + /// \returns the minimum number of character insertions, removals, + /// or (if \p AllowReplacements is \c true) replacements needed to + /// transform one of the given strings into the other. If zero, + /// the strings are identical. + unsigned edit_distance(StringRef Other, bool AllowReplacements = true); + /// str - Get the contents as an std::string. std::string str() const { return std::string(Data, Length); } Modified: llvm/trunk/lib/Support/StringRef.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Support/StringRef.cpp?rev=92309&r1=92308&r2=92309&view=diff ============================================================================== --- llvm/trunk/lib/Support/StringRef.cpp (original) +++ llvm/trunk/lib/Support/StringRef.cpp Wed Dec 30 11:23:44 2009 @@ -8,6 +8,7 @@ //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" +#include using namespace llvm; // MSVC emits references to this into the translation units which reference it. @@ -35,6 +36,36 @@ return Length < RHS.Length ? -1 : 1; } +/// \brief Compute the edit distance between the two given strings. +unsigned StringRef::edit_distance(llvm::StringRef Other, + bool AllowReplacements) { + size_type m = size(); + size_type n = Other.size(); + + std::vector previous(n+1, 0); + for (std::vector::size_type i = 0; i <= n; ++i) + previous[i] = i; + + std::vector current(n+1, 0); + for (size_type y = 1; y <= m; ++y) { + current.assign(n+1, 0); + current[0] = y; + for (size_type x = 1; x <= n; ++x) { + if (AllowReplacements) { + current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u), + min(current[x-1], previous[x])+1); + } + else { + if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1]; + else current[x] = min(current[x-1], previous[x]) + 1; + } + } + current.swap(previous); + } + + return previous[n]; +} + //===----------------------------------------------------------------------===// // String Searching //===----------------------------------------------------------------------===// From clattner at apple.com Wed Dec 30 13:42:23 2009 From: clattner at apple.com (Chris Lattner) Date: Wed, 30 Dec 2009 11:42:23 -0800 Subject: [llvm-commits] [llvm] r92309 - in /llvm/trunk: include/llvm/ADT/StringRef.h lib/Support/StringRef.cpp In-Reply-To: <200912301723.nBUHNiO4000671@zion.cs.uiuc.edu> References: <200912301723.nBUHNiO4000671@zion.cs.uiuc.edu> Message-ID: <3B8E7A83-A329-407D-8201-B7D5EF9F42EF@apple.com> On Dec 30, 2009, at 9:23 AM, Douglas Gregor wrote: > Author: dgregor > Date: Wed Dec 30 11:23:44 2009 > New Revision: 92309 > > URL: http://llvm.org/viewvc/llvm-project?rev=92309&view=rev > Log: > Implement edit distance for StringRef Very cool. > > +/// \brief Compute the edit distance between the two given strings. > +unsigned StringRef::edit_distance(llvm::StringRef Other, > + bool AllowReplacements) { This function is a big blob of magic :). Is there a citation or some description of the algorithm you can add? -Chris > + size_type m = size(); > + size_type n = Other.size(); > + > + std::vector previous(n+1, 0); > + for (std::vector::size_type i = 0; i <= n; ++i) > + previous[i] = i; > + > + std::vector current(n+1, 0); > + for (size_type y = 1; y <= m; ++y) { > + current.assign(n+1, 0); > + current[0] = y; > + for (size_type x = 1; x <= n; ++x) { > + if (AllowReplacements) { > + current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u), > + min(current[x-1], previous[x])+1); > + } > + else { > + if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1]; > + else current[x] = min(current[x-1], previous[x]) + 1; > + } > + } > + current.swap(previous); > + } > + > + return previous[n]; > +} > + > //===----------------------------------------------------------------------===// > // String Searching > //===----------------------------------------------------------------------===// > > > _______________________________________________ > llvm-commits mailing list > llvm-commits at cs.uiuc.edu > http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits From daniel at zuster.org Wed Dec 30 13:44:09 2009 From: daniel at zuster.org (Daniel Dunbar) Date: Wed, 30 Dec 2009 11:44:09 -0800 Subject: [llvm-commits] [llvm] r92309 - in /llvm/trunk: include/llvm/ADT/StringRef.h lib/Support/StringRef.cpp In-Reply-To: <200912301723.nBUHNiO4000671@zion.cs.uiuc.edu> References: <200912301723.nBUHNiO4000671@zion.cs.uiuc.edu> Message-ID: <6a8523d60912301144q691738ccxbda79dd0dd95d569@mail.gmail.com> On Wed, Dec 30, 2009 at 9:23 AM, Douglas Gregor wrote: > Author: dgregor > Date: Wed Dec 30 11:23:44 2009 > New Revision: 92309 > > URL: http://llvm.org/viewvc/llvm-project?rev=92309&view=rev > Log: > Implement edit distance for StringRef Nice! Can this use SmallVector instead of vector, and get a unittest? - Daniel > Modified: > ? ?llvm/trunk/include/llvm/ADT/StringRef.h > ? ?llvm/trunk/lib/Support/StringRef.cpp > > Modified: llvm/trunk/include/llvm/ADT/StringRef.h > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/StringRef.h?rev=92309&r1=92308&r2=92309&view=diff > > ============================================================================== > --- llvm/trunk/include/llvm/ADT/StringRef.h (original) > +++ llvm/trunk/include/llvm/ADT/StringRef.h Wed Dec 30 11:23:44 2009 > @@ -133,6 +133,22 @@ > ? ? /// compare_lower - Compare two strings, ignoring case. > ? ? int compare_lower(StringRef RHS) const; > > + ? ?/// \brief Determine the edit distance between this string and another > + ? ?/// string. > + ? ?/// > + ? ?/// \param Other the string to compare this string against. > + ? ?/// > + ? ?/// \param AllowReplacements whether to allow character > + ? ?/// replacements (change one character into another) as a single > + ? ?/// operation, rather than as two operations (an insertion and a > + ? ?/// removal). > + ? ?/// > + ? ?/// \returns the minimum number of character insertions, removals, > + ? ?/// or (if \p AllowReplacements is \c true) replacements needed to > + ? ?/// transform one of the given strings into the other. If zero, > + ? ?/// the strings are identical. > + ? ?unsigned edit_distance(StringRef Other, bool AllowReplacements = true); > + > ? ? /// str - Get the contents as an std::string. > ? ? std::string str() const { return std::string(Data, Length); } > > > Modified: llvm/trunk/lib/Support/StringRef.cpp > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Support/StringRef.cpp?rev=92309&r1=92308&r2=92309&view=diff > > ============================================================================== > --- llvm/trunk/lib/Support/StringRef.cpp (original) > +++ llvm/trunk/lib/Support/StringRef.cpp Wed Dec 30 11:23:44 2009 > @@ -8,6 +8,7 @@ > ?//===----------------------------------------------------------------------===// > > ?#include "llvm/ADT/StringRef.h" > +#include > ?using namespace llvm; > > ?// MSVC emits references to this into the translation units which reference it. > @@ -35,6 +36,36 @@ > ? return Length < RHS.Length ? -1 : 1; > ?} > > +/// \brief Compute the edit distance between the two given strings. > +unsigned StringRef::edit_distance(llvm::StringRef Other, > + ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?bool AllowReplacements) { > + ?size_type m = size(); > + ?size_type n = Other.size(); > + > + ?std::vector previous(n+1, 0); > + ?for (std::vector::size_type i = 0; i <= n; ++i) > + ? ?previous[i] = i; > + > + ?std::vector current(n+1, 0); > + ?for (size_type y = 1; y <= m; ++y) { > + ? ?current.assign(n+1, 0); > + ? ?current[0] = y; > + ? ?for (size_type x = 1; x <= n; ++x) { > + ? ? ?if (AllowReplacements) { > + ? ? ? ?current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u), > + ? ? ? ? ? ? ? ? ? ? ? ? min(current[x-1], previous[x])+1); > + ? ? ?} > + ? ? ?else { > + ? ? ? ?if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1]; > + ? ? ? ?else current[x] = min(current[x-1], previous[x]) + 1; > + ? ? ?} > + ? ?} > + ? ?current.swap(previous); > + ?} > + > + ?return previous[n]; > +} > + > ?//===----------------------------------------------------------------------===// > ?// String Searching > ?//===----------------------------------------------------------------------===// > > > _______________________________________________ > llvm-commits mailing list > llvm-commits at cs.uiuc.edu > http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits > From sabre at nondot.org Wed Dec 30 14:25:09 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 20:25:09 -0000 Subject: [llvm-commits] [llvm] r92311 - /llvm/trunk/lib/VMCore/Constants.cpp Message-ID: <200912302025.nBUKP9HC007209@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 14:25:09 2009 New Revision: 92311 URL: http://llvm.org/viewvc/llvm-project?rev=92311&view=rev Log: remove some misleading comments. Modified: llvm/trunk/lib/VMCore/Constants.cpp Modified: llvm/trunk/lib/VMCore/Constants.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Constants.cpp?rev=92311&r1=92310&r2=92311&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Constants.cpp (original) +++ llvm/trunk/lib/VMCore/Constants.cpp Wed Dec 30 14:25:09 2009 @@ -481,15 +481,12 @@ // If this is an all-zero array, return a ConstantAggregateZero object if (!V.empty()) { Constant *C = V[0]; - if (!C->isNullValue()) { - // Implicitly locked. + if (!C->isNullValue()) return pImpl->ArrayConstants.getOrCreate(Ty, V); - } + for (unsigned i = 1, e = V.size(); i != e; ++i) - if (V[i] != C) { - // Implicitly locked. + if (V[i] != C) return pImpl->ArrayConstants.getOrCreate(Ty, V); - } } return ConstantAggregateZero::get(Ty); @@ -550,7 +547,6 @@ // Create a ConstantAggregateZero value if all elements are zeros... for (unsigned i = 0, e = V.size(); i != e; ++i) if (!V[i]->isNullValue()) - // Implicitly locked. return pImpl->StructConstants.getOrCreate(T, V); return ConstantAggregateZero::get(T); @@ -613,7 +609,6 @@ if (isUndef) return UndefValue::get(T); - // Implicitly locked. return pImpl->VectorConstants.getOrCreate(T, V); } @@ -894,14 +889,12 @@ "Cannot create an aggregate zero of non-aggregate type!"); LLVMContextImpl *pImpl = Ty->getContext().pImpl; - // Implicitly locked. return pImpl->AggZeroConstants.getOrCreate(Ty, 0); } /// destroyConstant - Remove the constant from the constant table... /// void ConstantAggregateZero::destroyConstant() { - // Implicitly locked. getType()->getContext().pImpl->AggZeroConstants.remove(this); destroyConstantImpl(); } @@ -909,7 +902,6 @@ /// destroyConstant - Remove the constant from the constant table... /// void ConstantArray::destroyConstant() { - // Implicitly locked. getType()->getContext().pImpl->ArrayConstants.remove(this); destroyConstantImpl(); } @@ -974,7 +966,6 @@ // destroyConstant - Remove the constant from the constant table... // void ConstantStruct::destroyConstant() { - // Implicitly locked. getType()->getContext().pImpl->StructConstants.remove(this); destroyConstantImpl(); } @@ -982,7 +973,6 @@ // destroyConstant - Remove the constant from the constant table... // void ConstantVector::destroyConstant() { - // Implicitly locked. getType()->getContext().pImpl->VectorConstants.remove(this); destroyConstantImpl(); } @@ -1018,14 +1008,12 @@ // ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) { - // Implicitly locked. return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0); } // destroyConstant - Remove the constant from the constant table... // void ConstantPointerNull::destroyConstant() { - // Implicitly locked. getType()->getContext().pImpl->NullPtrConstants.remove(this); destroyConstantImpl(); } @@ -1137,7 +1125,6 @@ std::vector argVec(1, C); ExprMapKeyType Key(opc, argVec); - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(Ty, Key); } @@ -1383,8 +1370,6 @@ ExprMapKeyType Key(Opcode, argVec, 0, Flags); LLVMContextImpl *pImpl = ReqTy->getContext().pImpl; - - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(ReqTy, Key); } @@ -1535,8 +1520,6 @@ ExprMapKeyType Key(Instruction::Select, argVec); LLVMContextImpl *pImpl = ReqTy->getContext().pImpl; - - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(ReqTy, Key); } @@ -1564,8 +1547,6 @@ const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec); LLVMContextImpl *pImpl = ReqTy->getContext().pImpl; - - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(ReqTy, Key); } @@ -1595,8 +1576,6 @@ GEPOperator::IsInBounds); LLVMContextImpl *pImpl = ReqTy->getContext().pImpl; - - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(ReqTy, Key); } @@ -1650,8 +1629,6 @@ const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred); LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; - - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key); } @@ -1673,8 +1650,6 @@ const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred); LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; - - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key); } @@ -1683,15 +1658,13 @@ Constant *Idx) { if (Constant *FC = ConstantFoldExtractElementInstruction( ReqTy->getContext(), Val, Idx)) - return FC; // Fold a few common cases... + return FC; // Fold a few common cases. // Look up the constant in the table first to ensure uniqueness std::vector ArgVec(1, Val); ArgVec.push_back(Idx); const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec); LLVMContextImpl *pImpl = ReqTy->getContext().pImpl; - - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(ReqTy, Key); } @@ -1708,7 +1681,7 @@ Constant *Elt, Constant *Idx) { if (Constant *FC = ConstantFoldInsertElementInstruction( ReqTy->getContext(), Val, Elt, Idx)) - return FC; // Fold a few common cases... + return FC; // Fold a few common cases. // Look up the constant in the table first to ensure uniqueness std::vector ArgVec(1, Val); ArgVec.push_back(Elt); @@ -1716,8 +1689,6 @@ const ExprMapKeyType Key(Instruction::InsertElement,ArgVec); LLVMContextImpl *pImpl = ReqTy->getContext().pImpl; - - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(ReqTy, Key); } @@ -1744,8 +1715,6 @@ const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec); LLVMContextImpl *pImpl = ReqTy->getContext().pImpl; - - // Implicitly locked. return pImpl->ExprConstants.getOrCreate(ReqTy, Key); } @@ -1914,9 +1883,7 @@ // destroyConstant - Remove the constant from the constant table... // void ConstantExpr::destroyConstant() { - // Implicitly locked. - LLVMContextImpl *pImpl = getType()->getContext().pImpl; - pImpl->ExprConstants.remove(this); + getType()->getContext().pImpl->ExprConstants.remove(this); destroyConstantImpl(); } From anton at korobeynikov.info Wed Dec 30 14:55:47 2009 From: anton at korobeynikov.info (Anton Korobeynikov) Date: Wed, 30 Dec 2009 23:55:47 +0300 Subject: [llvm-commits] [llvm] r92309 - in /llvm/trunk: include/llvm/ADT/StringRef.h lib/Support/StringRef.cpp In-Reply-To: <3B8E7A83-A329-407D-8201-B7D5EF9F42EF@apple.com> References: <200912301723.nBUHNiO4000671@zion.cs.uiuc.edu> <3B8E7A83-A329-407D-8201-B7D5EF9F42EF@apple.com> Message-ID: Hi, Chris > This function is a big blob of magic :). ?Is there a citation or some description of the algorithm you can add? It seems to me a standard dynamic programming-based approach for edit distance computation (aka 'Levenstein algorithm'). It's only written in "compact" form to reduce memory complexity. -- With best regards, Anton Korobeynikov Faculty of Mathematics and Mechanics, Saint Petersburg State University From clattner at apple.com Wed Dec 30 15:20:33 2009 From: clattner at apple.com (Chris Lattner) Date: Wed, 30 Dec 2009 13:20:33 -0800 Subject: [llvm-commits] [llvm] r92309 - in /llvm/trunk: include/llvm/ADT/StringRef.h lib/Support/StringRef.cpp In-Reply-To: References: <200912301723.nBUHNiO4000671@zion.cs.uiuc.edu> <3B8E7A83-A329-407D-8201-B7D5EF9F42EF@apple.com> Message-ID: <50091DB7-3AE6-4E9A-B14C-D440FCD5D01A@apple.com> On Dec 30, 2009, at 12:55 PM, Anton Korobeynikov wrote: > Hi, Chris > >> This function is a big blob of magic :). Is there a citation or some description of the algorithm you can add? > It seems to me a standard dynamic programming-based approach for edit > distance computation (aka 'Levenstein algorithm'). It's only written > in "compact" form to reduce memory complexity. Sure, but a comment stating that would be nice :) -Chris From sabre at nondot.org Wed Dec 30 15:42:12 2009 From: sabre at nondot.org (Chris Lattner) Date: Wed, 30 Dec 2009 21:42:12 -0000 Subject: [llvm-commits] [llvm] r92315 - in /llvm/trunk: include/llvm/Metadata.h lib/VMCore/Metadata.cpp Message-ID: <200912302142.nBULgCRT009843@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 15:42:11 2009 New Revision: 92315 URL: http://llvm.org/viewvc/llvm-project?rev=92315&view=rev Log: do not bother reuniquing mdnodes whose operands drop to null. Doing so can be a huge performance issue when tearing down modules and mdnodes are not guaranteed to be unique anyway. This speeds up: $ time ~/llvm/Release/bin/clang gcc.c -w -S -g from 72 to 35s, where gcc.c is from: http://people.csail.mit.edu/smcc/projects/single-file-programs/ Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92315&r1=92314&r2=92315&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Wed Dec 30 15:42:11 2009 @@ -85,8 +85,6 @@ //===----------------------------------------------------------------------===// /// MDNode - a tuple of other values. -/// These contain a list of the values that represent the metadata. -/// MDNode is always unnamed. class MDNode : public MetadataBase, public FoldingSetNode { MDNode(const MDNode &); // DO NOT IMPLEMENT void operator=(const MDNode &); // DO NOT IMPLEMENT @@ -97,7 +95,14 @@ // Subclass data enums. enum { - FunctionLocalBit = 1 + /// FunctionLocalBit - This bit is set if this MDNode is function local. + /// This is true when it (potentially transitively) contains a reference to + /// something in a function, like an argument, basicblock, or instruction. + FunctionLocalBit = 1 << 0, + + /// NotUniquedBit - This is set on MDNodes that are not uniqued because they + /// have a null perand. + NotUniquedBit = 1 << 1 }; // Replace each instance of F from the element list of this node with T. @@ -138,6 +143,13 @@ return V->getValueID() == MDNodeVal; } private: + bool isNotUniqued() const { + return (getSubclassDataFromValue() & NotUniquedBit) != 0; + } + void setIsNotUniqued() { + setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit); + } + // Shadow Value::setValueSubclassData with a private forwarding method so that // any future subclasses cannot accidentally use it. void setValueSubclassData(unsigned short D) { Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92315&r1=92314&r2=92315&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Wed Dec 30 15:42:11 2009 @@ -87,8 +87,10 @@ /// ~MDNode - Destroy MDNode. MDNode::~MDNode() { - LLVMContextImpl *pImpl = getType()->getContext().pImpl; - pImpl->MDNodeSet.RemoveNode(this); + if (!isNotUniqued()) { + LLVMContextImpl *pImpl = getType()->getContext().pImpl; + pImpl->MDNodeSet.RemoveNode(this); + } delete [] Operands; Operands = NULL; } @@ -97,6 +99,7 @@ bool isFunctionLocal) : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) { NumOperands = NumVals; + // FIXME: Coallocate the operand list. These have fixed arity. Operands = new MDNodeElement[NumOperands]; for (unsigned i = 0; i != NumVals; ++i) @@ -146,25 +149,40 @@ if (From == To) return; + // Update the operand. + Op->set(To, this); + + // If this node is already not being uniqued (because one of the operands + // already went to null), then there is nothing else to do here. + if (isNotUniqued()) return; + LLVMContextImpl *pImpl = getType()->getContext().pImpl; // Remove "this" from the context map. FoldingSet doesn't have to reprofile // this node to remove it, so we don't care what state the operands are in. pImpl->MDNodeSet.RemoveNode(this); - // Update the operand. - Op->set(To, this); - - // Insert updated "this" into the context's folding node set. - // If a node with same element list already exist then before inserting - // updated "this" into the folding node set, replace all uses of existing - // node with updated "this" node. + // If we are dropping an argument to null, we choose to not unique the MDNode + // anymore. This commonly occurs during destruction, and uniquing these + // brings little reuse. + if (To == 0) { + setIsNotUniqued(); + return; + } + + // Now that the node is out of the folding set, get ready to reinsert it. + // First, check to see if another node with the same operands already exists + // in the set. If it doesn't exist, this returns the position to insert it. FoldingSetNodeID ID; Profile(ID); void *InsertPoint; MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); if (N) { + // FIXME: + // If it already exists in the set, we don't reinsert it, we just claim it + // isn't uniqued. + N->replaceAllUsesWith(this); delete N; N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); From sabre at nondot.org Wed Dec 30 18:51:46 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 00:51:46 -0000 Subject: [llvm-commits] [llvm] r92320 - /llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp Message-ID: <200912310051.nBV0ploW016173@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 18:51:46 2009 New Revision: 92320 URL: http://llvm.org/viewvc/llvm-project?rev=92320&view=rev Log: tidy Modified: llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp Modified: llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp?rev=92320&r1=92319&r2=92320&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp Wed Dec 30 18:51:46 2009 @@ -78,6 +78,8 @@ // the module symbol table can refer to them... EnumerateValueSymbolTable(M->getValueSymbolTable()); + SmallVector, 8> MDs; + // Enumerate types used by function bodies and argument lists. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { @@ -85,7 +87,6 @@ I != E; ++I) EnumerateType(I->getType()); - SmallVector, 2> MDs; for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){ for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); @@ -229,13 +230,13 @@ } // Add the value. + assert(isa(MD) && "Unknown metadata kind"); MDValues.push_back(std::make_pair(MD, 1U)); MDValueID = MDValues.size(); } void ValueEnumerator::EnumerateValue(const Value *V) { - assert(V->getType() != Type::getVoidTy(V->getContext()) && - "Can't insert void values!"); + assert(!V->getType()->isVoidTy() && "Can't insert void values!"); if (const MetadataBase *MB = dyn_cast(V)) return EnumerateMetadata(MB); From sabre at nondot.org Wed Dec 30 19:05:46 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 01:05:46 -0000 Subject: [llvm-commits] [llvm] r92321 - in /llvm/trunk: include/llvm/Metadata.h lib/Analysis/DebugInfo.cpp lib/VMCore/Metadata.cpp Message-ID: <200912310105.nBV15kdq016575@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 19:05:46 2009 New Revision: 92321 URL: http://llvm.org/viewvc/llvm-project?rev=92321&view=rev Log: Optimize MDNode to coallocate the operand list immediately after the MDNode in memory. This eliminates the operands pointer and saves a new[] per node. Note that the code in DIDerivedType::replaceAllUsesWith is wrong and quite scary. A MDNode should not be RAUW'd with something else: this changes all uses of the mdnode, which may not be debug info related! Debug info should use something non-mdnode for declarations. Modified: llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/Analysis/DebugInfo.cpp llvm/trunk/lib/VMCore/Metadata.cpp Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92321&r1=92320&r2=92321&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Wed Dec 30 19:05:46 2009 @@ -90,7 +90,8 @@ void operator=(const MDNode &); // DO NOT IMPLEMENT friend class MDNodeElement; - MDNodeElement *Operands; + /// NumOperands - This many 'MDNodeElement' items are co-allocated onto the + /// end of this MDNode. unsigned NumOperands; // Subclass data enums. @@ -102,11 +103,16 @@ /// NotUniquedBit - This is set on MDNodes that are not uniqued because they /// have a null perand. - NotUniquedBit = 1 << 1 + NotUniquedBit = 1 << 1, + + /// DestroyFlag - This bit is set by destroy() so the destructor can assert + /// that the node isn't being destroyed with a plain 'delete'. + DestroyFlag = 1 << 2 }; // Replace each instance of F from the element list of this node with T. void replaceElement(MDNodeElement *Op, Value *NewVal); + ~MDNode(); protected: explicit MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, @@ -115,9 +121,6 @@ // Constructors and destructors. static MDNode *get(LLVMContext &Context, Value *const *Vals, unsigned NumVals, bool isFunctionLocal = false); - - /// ~MDNode - Destroy MDNode. - ~MDNode(); /// getElement - Return specified element. Value *getElement(unsigned i) const; @@ -133,6 +136,9 @@ return (getSubclassDataFromValue() & FunctionLocalBit) != 0; } + // destroy - Delete this node. Only when there are no uses. + void destroy(); + /// Profile - calculate a unique identifier for this MDNode to collapse /// duplicates void Profile(FoldingSetNodeID &ID) const; Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=92321&r1=92320&r2=92321&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Wed Dec 30 19:05:46 2009 @@ -284,7 +284,7 @@ if (getNode() != D.getNode()) { MDNode *Node = DbgNode; Node->replaceAllUsesWith(D.getNode()); - delete Node; + Node->destroy(); } } Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92321&r1=92320&r2=92321&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Wed Dec 30 19:05:46 2009 @@ -56,13 +56,11 @@ class MDNodeElement : public CallbackVH { MDNode *Parent; public: - MDNodeElement() {} MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {} ~MDNodeElement() {} - void set(Value *V, MDNode *P) { + void set(Value *V) { setValPtr(V); - Parent = P; } virtual void deleted(); @@ -85,30 +83,52 @@ // MDNode implementation. // +/// getOperandPtr - Helper function to get the MDNodeElement's coallocated on +/// the end of the MDNode. +static MDNodeElement *getOperandPtr(MDNode *N, unsigned Op) { + assert(Op < N->getNumElements() && "Invalid operand number"); + return reinterpret_cast(N+1)+Op; +} + +MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, + bool isFunctionLocal) +: MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) { + NumOperands = NumVals; + + if (isFunctionLocal) + setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit); + + // Initialize the operand list, which is co-allocated on the end of the node. + for (MDNodeElement *Op = getOperandPtr(this, 0), *E = Op+NumOperands; + Op != E; ++Op, ++Vals) + new (Op) MDNodeElement(*Vals, this); +} + + /// ~MDNode - Destroy MDNode. MDNode::~MDNode() { + assert((getSubclassDataFromValue() & DestroyFlag) != 0 && + "Not being destroyed through destroy()?"); if (!isNotUniqued()) { LLVMContextImpl *pImpl = getType()->getContext().pImpl; pImpl->MDNodeSet.RemoveNode(this); } - delete [] Operands; - Operands = NULL; + + // Destroy the operands. + for (MDNodeElement *Op = getOperandPtr(this, 0), *E = Op+NumOperands; + Op != E; ++Op) + Op->~MDNodeElement(); } -MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, - bool isFunctionLocal) - : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) { - NumOperands = NumVals; - // FIXME: Coallocate the operand list. These have fixed arity. - Operands = new MDNodeElement[NumOperands]; - - for (unsigned i = 0; i != NumVals; ++i) - Operands[i].set(Vals[i], this); - - if (isFunctionLocal) - setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit); +// destroy - Delete this node. Only when there are no uses. +void MDNode::destroy() { + setValueSubclassData(getSubclassDataFromValue() | DestroyFlag); + // Placement delete, the free the memory. + this->~MDNode(); + free(this); } + MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals, bool isFunctionLocal) { LLVMContextImpl *pImpl = Context.pImpl; @@ -119,27 +139,25 @@ void *InsertPoint; MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); if (!N) { + // Coallocate space for the node and elements together, then placement new. + void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeElement)); + N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal); + // InsertPoint will have been set by the FindNodeOrInsertPos call. - N = new MDNode(Context, Vals, NumVals, isFunctionLocal); pImpl->MDNodeSet.InsertNode(N, InsertPoint); } return N; } -void MDNode::Profile(FoldingSetNodeID &ID) const { - for (unsigned i = 0, e = getNumElements(); i != e; ++i) - ID.AddPointer(getElement(i)); - // HASH TABLE COLLISIONS? - // DO NOT REINSERT AFTER AN OPERAND DROPS TO NULL! -} - - /// getElement - Return specified element. Value *MDNode::getElement(unsigned i) const { - assert(i < getNumElements() && "Invalid element number!"); - return Operands[i]; + return *getOperandPtr(const_cast(this), i); } +void MDNode::Profile(FoldingSetNodeID &ID) const { + for (unsigned i = 0, e = getNumElements(); i != e; ++i) + ID.AddPointer(getElement(i)); +} // Replace value from this node's element list. @@ -150,7 +168,7 @@ return; // Update the operand. - Op->set(To, this); + Op->set(To); // If this node is already not being uniqued (because one of the operands // already went to null), then there is nothing else to do here. @@ -179,12 +197,8 @@ MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); if (N) { - // FIXME: - // If it already exists in the set, we don't reinsert it, we just claim it - // isn't uniqued. - N->replaceAllUsesWith(this); - delete N; + N->destroy(); N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); assert(N == 0 && "shouldn't be in the map now!"); (void)N; } @@ -261,7 +275,7 @@ //===----------------------------------------------------------------------===// -// MetadataContext implementation. +// LLVMContext MDKind naming implementation. // #ifndef NDEBUG From sabre at nondot.org Wed Dec 30 19:22:30 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 01:22:30 -0000 Subject: [llvm-commits] [llvm] r92322 - in /llvm/trunk: include/llvm/Analysis/DebugInfo.h include/llvm/IntrinsicInst.h include/llvm/Metadata.h lib/Analysis/DebugInfo.cpp lib/Bitcode/Writer/BitcodeWriter.cpp lib/Bitcode/Writer/ValueEnumerator.cpp lib/Linker/LinkModules.cpp lib/Transforms/Utils/CloneFunction.cpp lib/VMCore/AsmWriter.cpp lib/VMCore/IntrinsicInst.cpp lib/VMCore/Metadata.cpp lib/VMCore/Verifier.cpp unittests/VMCore/MetadataTest.cpp Message-ID: <200912310122.nBV1MUq4017100@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 19:22:29 2009 New Revision: 92322 URL: http://llvm.org/viewvc/llvm-project?rev=92322&view=rev Log: rename "elements" of metadata to "operands". "Elements" are things that occur in types. "operands" are things that occur in values. Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h llvm/trunk/include/llvm/IntrinsicInst.h llvm/trunk/include/llvm/Metadata.h llvm/trunk/lib/Analysis/DebugInfo.cpp llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp llvm/trunk/lib/Linker/LinkModules.cpp llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp llvm/trunk/lib/VMCore/AsmWriter.cpp llvm/trunk/lib/VMCore/IntrinsicInst.cpp llvm/trunk/lib/VMCore/Metadata.cpp llvm/trunk/lib/VMCore/Verifier.cpp llvm/trunk/unittests/VMCore/MetadataTest.cpp Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Analysis/DebugInfo.h?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/include/llvm/Analysis/DebugInfo.h (original) +++ llvm/trunk/include/llvm/Analysis/DebugInfo.h Wed Dec 30 19:22:29 2009 @@ -369,19 +369,19 @@ unsigned isDefinition() const { return getUnsignedField(10); } unsigned getVirtuality() const { - if (DbgNode->getNumElements() < 14) + if (DbgNode->getNumOperands() < 14) return 0; return getUnsignedField(11); } unsigned getVirtualIndex() const { - if (DbgNode->getNumElements() < 14) + if (DbgNode->getNumOperands() < 14) return 0; return getUnsignedField(12); } DICompositeType getContainingType() const { - assert (DbgNode->getNumElements() >= 14 && "Invalid type!"); + assert (DbgNode->getNumOperands() >= 14 && "Invalid type!"); return getFieldAs(13); } @@ -439,7 +439,7 @@ return getNumAddrElements() > 0; } - unsigned getNumAddrElements() const { return DbgNode->getNumElements()-6; } + unsigned getNumAddrElements() const { return DbgNode->getNumOperands()-6; } uint64_t getAddrElement(unsigned Idx) const { return getUInt64Field(Idx+6); Modified: llvm/trunk/include/llvm/IntrinsicInst.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/IntrinsicInst.h?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/include/llvm/IntrinsicInst.h (original) +++ llvm/trunk/include/llvm/IntrinsicInst.h Wed Dec 30 19:22:29 2009 @@ -98,8 +98,8 @@ return unsigned(cast(getOperand(2))->getZExtValue()); } - Value* getFileName() const; - Value* getDirectory() const; + Value *getFileName() const; + Value *getDirectory() const; // Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const DbgStopPointInst *) { return true; } @@ -175,8 +175,8 @@ /// DbgValueInst - This represents the llvm.dbg.value instruction. /// struct DbgValueInst : public DbgInfoIntrinsic { - Value *getValue() const { - return cast(getOperand(1))->getElement(0); + Value *getValue() const { + return cast(getOperand(1))->getOperand(0); } Value *getOffset() const { return getOperand(2); } MDNode *getVariable() const { return cast(getOperand(3)); } Modified: llvm/trunk/include/llvm/Metadata.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Metadata.h?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/include/llvm/Metadata.h (original) +++ llvm/trunk/include/llvm/Metadata.h Wed Dec 30 19:22:29 2009 @@ -26,7 +26,10 @@ class LLVMContext; class Module; template class SmallVectorImpl; - +template + class SymbolTableListTraits; + + //===----------------------------------------------------------------------===// // MetadataBase - A base class for MDNode, MDString and NamedMDNode. class MetadataBase : public Value { @@ -81,16 +84,16 @@ }; -class MDNodeElement; +class MDNodeOperand; //===----------------------------------------------------------------------===// /// MDNode - a tuple of other values. class MDNode : public MetadataBase, public FoldingSetNode { MDNode(const MDNode &); // DO NOT IMPLEMENT void operator=(const MDNode &); // DO NOT IMPLEMENT - friend class MDNodeElement; + friend class MDNodeOperand; - /// NumOperands - This many 'MDNodeElement' items are co-allocated onto the + /// NumOperands - This many 'MDNodeOperand' items are co-allocated onto the /// end of this MDNode. unsigned NumOperands; @@ -110,8 +113,8 @@ DestroyFlag = 1 << 2 }; - // Replace each instance of F from the element list of this node with T. - void replaceElement(MDNodeElement *Op, Value *NewVal); + // Replace each instance of F from the operand list of this node with T. + void replaceOperand(MDNodeOperand *Op, Value *NewVal); ~MDNode(); protected: @@ -122,11 +125,11 @@ static MDNode *get(LLVMContext &Context, Value *const *Vals, unsigned NumVals, bool isFunctionLocal = false); - /// getElement - Return specified element. - Value *getElement(unsigned i) const; + /// getOperand - Return specified operand. + Value *getOperand(unsigned i) const; - /// getNumElements - Return number of MDNode elements. - unsigned getNumElements() const { return NumOperands; } + /// getNumOperands - Return number of MDNode operands. + unsigned getNumOperands() const { return NumOperands; } /// isFunctionLocal - Return whether MDNode is local to a function. /// Note: MDNodes are designated as function-local when created, and keep @@ -165,10 +168,7 @@ //===----------------------------------------------------------------------===// /// NamedMDNode - a tuple of other metadata. -/// NamedMDNode is always named. All NamedMDNode element has a type of metadata. -template - class SymbolTableListTraits; - +/// NamedMDNode is always named. All NamedMDNode operand has a type of metadata. class NamedMDNode : public MetadataBase, public ilist_node { friend class SymbolTableListTraits; friend class LLVMContextImpl; @@ -205,14 +205,14 @@ inline Module *getParent() { return Parent; } inline const Module *getParent() const { return Parent; } - /// getElement - Return specified element. - MetadataBase *getElement(unsigned i) const; + /// getOperand - Return specified operand. + MetadataBase *getOperand(unsigned i) const; - /// getNumElements - Return number of NamedMDNode elements. - unsigned getNumElements() const; + /// getNumOperands - Return the number of NamedMDNode operands. + unsigned getNumOperands() const; - /// addElement - Add metadata element. - void addElement(MetadataBase *M); + /// addOperand - Add metadata operand. + void addOperand(MetadataBase *M); /// Methods for support type inquiry through isa, cast, and dyn_cast: static inline bool classof(const NamedMDNode *) { return true; } Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Wed Dec 30 19:22:29 2009 @@ -83,8 +83,8 @@ if (DbgNode == 0) return StringRef(); - if (Elt < DbgNode->getNumElements()) - if (MDString *MDS = dyn_cast_or_null(DbgNode->getElement(Elt))) + if (Elt < DbgNode->getNumOperands()) + if (MDString *MDS = dyn_cast_or_null(DbgNode->getOperand(Elt))) return MDS->getString(); return StringRef(); @@ -94,8 +94,8 @@ if (DbgNode == 0) return 0; - if (Elt < DbgNode->getNumElements()) - if (ConstantInt *CI = dyn_cast(DbgNode->getElement(Elt))) + if (Elt < DbgNode->getNumOperands()) + if (ConstantInt *CI = dyn_cast(DbgNode->getOperand(Elt))) return CI->getZExtValue(); return 0; @@ -105,8 +105,8 @@ if (DbgNode == 0) return DIDescriptor(); - if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt)) - return DIDescriptor(dyn_cast(DbgNode->getElement(Elt))); + if (Elt < DbgNode->getNumOperands() && DbgNode->getOperand(Elt)) + return DIDescriptor(dyn_cast(DbgNode->getOperand(Elt))); return DIDescriptor(); } @@ -115,8 +115,8 @@ if (DbgNode == 0) return 0; - if (Elt < DbgNode->getNumElements()) - return dyn_cast_or_null(DbgNode->getElement(Elt)); + if (Elt < DbgNode->getNumOperands()) + return dyn_cast_or_null(DbgNode->getOperand(Elt)); return 0; } @@ -264,7 +264,7 @@ unsigned DIArray::getNumElements() const { assert(DbgNode && "Invalid DIArray"); - return DbgNode->getNumElements(); + return DbgNode->getNumOperands(); } /// replaceAllUsesWith - Replace all uses of debug info referenced by @@ -886,18 +886,18 @@ Value *Elts[] = { GetTagConstant(dwarf::DW_TAG_subprogram), llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)), - DeclNode->getElement(2), // Context - DeclNode->getElement(3), // Name - DeclNode->getElement(4), // DisplayName - DeclNode->getElement(5), // LinkageName - DeclNode->getElement(6), // CompileUnit - DeclNode->getElement(7), // LineNo - DeclNode->getElement(8), // Type - DeclNode->getElement(9), // isLocalToUnit + DeclNode->getOperand(2), // Context + DeclNode->getOperand(3), // Name + DeclNode->getOperand(4), // DisplayName + DeclNode->getOperand(5), // LinkageName + DeclNode->getOperand(6), // CompileUnit + DeclNode->getOperand(7), // LineNo + DeclNode->getOperand(8), // Type + DeclNode->getOperand(9), // isLocalToUnit ConstantInt::get(Type::getInt1Ty(VMContext), true), - DeclNode->getElement(11), // Virtuality - DeclNode->getElement(12), // VIndex - DeclNode->getElement(13) // Containting Type + DeclNode->getOperand(11), // Virtuality + DeclNode->getOperand(12), // VIndex + DeclNode->getOperand(13) // Containting Type }; return DISubprogram(MDNode::get(VMContext, &Elts[0], 14)); } @@ -930,7 +930,7 @@ // Create a named metadata so that we do not lose this mdnode. NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv"); - NMD->addElement(Node); + NMD->addOperand(Node); return DIGlobalVariable(Node); } @@ -1106,8 +1106,8 @@ if (!NMD) return; - for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { - DIGlobalVariable DIG(cast(NMD->getElement(i))); + for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { + DIGlobalVariable DIG(cast(NMD->getOperand(i))); if (addGlobalVariable(DIG)) { addCompileUnit(DIG.getCompileUnit()); processType(DIG.getType()); @@ -1289,8 +1289,8 @@ if (!NMD) return 0; - for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { - DIGlobalVariable DIG(cast_or_null(NMD->getElement(i))); + for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { + DIGlobalVariable DIG(cast_or_null(NMD->getOperand(i))); if (DIG.isNull()) continue; if (DIG.getGlobal() == V) Modified: llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/BitcodeWriter.cpp Wed Dec 30 19:22:29 2009 @@ -475,10 +475,10 @@ const ValueEnumerator &VE, BitstreamWriter &Stream, SmallVector &Record) { - for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) { - if (N->getElement(i)) { - Record.push_back(VE.getTypeID(N->getElement(i)->getType())); - Record.push_back(VE.getValueID(N->getElement(i))); + for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { + if (N->getOperand(i)) { + Record.push_back(VE.getTypeID(N->getOperand(i)->getType())); + Record.push_back(VE.getValueID(N->getOperand(i))); } else { Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext()))); Record.push_back(0); @@ -535,10 +535,10 @@ Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/); Record.clear(); - // Write named metadata elements. - for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { - if (NMD->getElement(i)) - Record.push_back(VE.getValueID(NMD->getElement(i))); + // Write named metadata operands. + for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { + if (NMD->getOperand(i)) + Record.push_back(VE.getValueID(NMD->getOperand(i))); else Record.push_back(0); } Modified: llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/ValueEnumerator.cpp Wed Dec 30 19:22:29 2009 @@ -212,8 +212,8 @@ MDValues.push_back(std::make_pair(MD, 1U)); MDValueMap[MD] = MDValues.size(); MDValueID = MDValues.size(); - for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) { - if (Value *V = N->getElement(i)) + for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { + if (Value *V = N->getOperand(i)) EnumerateValue(V); else EnumerateType(Type::getVoidTy(MD->getContext())); @@ -222,8 +222,8 @@ } if (const NamedMDNode *N = dyn_cast(MD)) { - for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) - EnumerateValue(N->getElement(i)); + for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) + EnumerateValue(N->getOperand(i)); MDValues.push_back(std::make_pair(MD, 1U)); MDValueMap[MD] = Values.size(); return; @@ -327,8 +327,8 @@ } if (const MDNode *N = dyn_cast(V)) { - for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) - if (Value *Elem = N->getElement(i)) + for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) + if (Value *Elem = N->getOperand(i)) EnumerateOperandType(Elem); } } else if (isa(V) || isa(V)) Modified: llvm/trunk/lib/Linker/LinkModules.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Linker/LinkModules.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/lib/Linker/LinkModules.cpp (original) +++ llvm/trunk/lib/Linker/LinkModules.cpp Wed Dec 30 19:22:29 2009 @@ -538,8 +538,8 @@ NamedMDNode::Create(SrcNMD, Dest); else { // Add Src elements into Dest node. - for (unsigned i = 0, e = SrcNMD->getNumElements(); i != e; ++i) - DestNMD->addElement(SrcNMD->getElement(i)); + for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i) + DestNMD->addOperand(SrcNMD->getOperand(i)); } } } Modified: llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp (original) +++ llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Wed Dec 30 19:22:29 2009 @@ -360,9 +360,9 @@ NewLoc = UpdateInlinedAtInfo(OrigLocation.getNode(), TheCallMD); Value *MDVs[] = { - InsnMD->getElement(0), // Line - InsnMD->getElement(1), // Col - InsnMD->getElement(2), // Scope + InsnMD->getOperand(0), // Line + InsnMD->getOperand(1), // Col + InsnMD->getOperand(2), // Scope NewLoc }; return MDNode::get(InsnMD->getContext(), MDVs, 4); Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 19:22:29 2009 @@ -648,8 +648,8 @@ I = TheModule->named_metadata_begin(), E = TheModule->named_metadata_end(); I != E; ++I) { const NamedMDNode *NMD = I; - for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { - MDNode *MD = dyn_cast_or_null(NMD->getElement(i)); + for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { + MDNode *MD = dyn_cast_or_null(NMD->getOperand(i)); if (MD) CreateMetadataSlot(MD); } @@ -722,8 +722,8 @@ void SlotTracker::processNamedMDNode() { ST_DEBUG("begin processNamedMDNode!\n"); mdnNext = 0; - for (unsigned i = 0, e = TheNamedMDNode->getNumElements(); i != e; ++i) { - MDNode *MD = dyn_cast_or_null(TheNamedMDNode->getElement(i)); + for (unsigned i = 0, e = TheNamedMDNode->getNumOperands(); i != e; ++i) { + MDNode *MD = dyn_cast_or_null(TheNamedMDNode->getOperand(i)); if (MD) CreateMetadataSlot(MD); } @@ -819,8 +819,8 @@ unsigned DestSlot = mdnNext++; mdnMap[N] = DestSlot; - for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) { - const Value *TV = N->getElement(i); + for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { + const Value *TV = N->getOperand(i); if (TV) if (const MDNode *N2 = dyn_cast(TV)) CreateMetadataSlot(N2); @@ -872,9 +872,9 @@ static void WriteMDNodeComment(const MDNode *Node, formatted_raw_ostream &Out) { - if (Node->getNumElements() < 1) + if (Node->getNumOperands() < 1) return; - ConstantInt *CI = dyn_cast_or_null(Node->getElement(0)); + ConstantInt *CI = dyn_cast_or_null(Node->getOperand(0)); if (!CI) return; unsigned Val = CI->getZExtValue(); unsigned Tag = Val & ~LLVMDebugVersionMask; @@ -908,8 +908,8 @@ Out << '!' << i << " = metadata "; const MDNode *Node = Nodes[i]; Out << "!{"; - for (unsigned mi = 0, me = Node->getNumElements(); mi != me; ++mi) { - const Value *V = Node->getElement(mi); + for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { + const Value *V = Node->getOperand(mi); if (!V) Out << "null"; else if (const MDNode *N = dyn_cast(V)) { @@ -919,7 +919,7 @@ else { TypePrinter.print(V->getType(), Out); Out << ' '; - WriteAsOperandInternal(Out, Node->getElement(mi), + WriteAsOperandInternal(Out, Node->getOperand(mi), &TypePrinter, &Machine); } if (mi + 1 != me) @@ -1231,14 +1231,14 @@ if (N->isFunctionLocal()) { // Print metadata inline, not via slot reference number. Out << "!{"; - for (unsigned mi = 0, me = N->getNumElements(); mi != me; ++mi) { - const Value *Val = N->getElement(mi); + for (unsigned mi = 0, me = N->getNumOperands(); mi != me; ++mi) { + const Value *Val = N->getOperand(mi); if (!Val) Out << "null"; else { - TypePrinter->print(N->getElement(0)->getType(), Out); + TypePrinter->print(N->getOperand(0)->getType(), Out); Out << ' '; - WriteAsOperandInternal(Out, N->getElement(0), TypePrinter, Machine); + WriteAsOperandInternal(Out, N->getOperand(0), TypePrinter, Machine); } if (mi + 1 != me) Out << ", "; @@ -1478,9 +1478,9 @@ E = M->named_metadata_end(); I != E; ++I) { const NamedMDNode *NMD = I; Out << "!" << NMD->getName() << " = !{"; - for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) { + for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { if (i) Out << ", "; - MDNode *MD = dyn_cast_or_null(NMD->getElement(i)); + MDNode *MD = dyn_cast_or_null(NMD->getOperand(i)); Out << '!' << Machine.getMetadataSlot(MD); } Out << "}\n"; @@ -2138,9 +2138,9 @@ TypePrinting TypePrinter; SlotTable.initialize(); OS << "!" << N->getName() << " = !{"; - for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) { + for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { if (i) OS << ", "; - MDNode *MD = dyn_cast_or_null(N->getElement(i)); + MDNode *MD = dyn_cast_or_null(N->getOperand(i)); if (MD) OS << '!' << SlotTable.getMetadataSlot(MD); else Modified: llvm/trunk/lib/VMCore/IntrinsicInst.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/IntrinsicInst.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/IntrinsicInst.cpp (original) +++ llvm/trunk/lib/VMCore/IntrinsicInst.cpp Wed Dec 30 19:22:29 2009 @@ -61,11 +61,11 @@ Value *DbgStopPointInst::getFileName() const { // Once the operand indices are verified, update this assert assert(LLVMDebugVersion == (7 << 16) && "Verify operand indices"); - return getContext()->getElement(3); + return getContext()->getOperand(3); } Value *DbgStopPointInst::getDirectory() const { // Once the operand indices are verified, update this assert assert(LLVMDebugVersion == (7 << 16) && "Verify operand indices"); - return getContext()->getElement(4); + return getContext()->getOperand(4); } Modified: llvm/trunk/lib/VMCore/Metadata.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Metadata.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Metadata.cpp (original) +++ llvm/trunk/lib/VMCore/Metadata.cpp Wed Dec 30 19:22:29 2009 @@ -48,16 +48,16 @@ } //===----------------------------------------------------------------------===// -// MDNodeElement implementation. +// MDNodeOperand implementation. // -// Use CallbackVH to hold MDNode elements. +// Use CallbackVH to hold MDNode operands. namespace llvm { -class MDNodeElement : public CallbackVH { +class MDNodeOperand : public CallbackVH { MDNode *Parent; public: - MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {} - ~MDNodeElement() {} + MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {} + ~MDNodeOperand() {} void set(Value *V) { setValPtr(V); @@ -69,12 +69,12 @@ } // end namespace llvm. -void MDNodeElement::deleted() { - Parent->replaceElement(this, 0); +void MDNodeOperand::deleted() { + Parent->replaceOperand(this, 0); } -void MDNodeElement::allUsesReplacedWith(Value *NV) { - Parent->replaceElement(this, NV); +void MDNodeOperand::allUsesReplacedWith(Value *NV) { + Parent->replaceOperand(this, NV); } @@ -83,11 +83,11 @@ // MDNode implementation. // -/// getOperandPtr - Helper function to get the MDNodeElement's coallocated on +/// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on /// the end of the MDNode. -static MDNodeElement *getOperandPtr(MDNode *N, unsigned Op) { - assert(Op < N->getNumElements() && "Invalid operand number"); - return reinterpret_cast(N+1)+Op; +static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) { + assert(Op < N->getNumOperands() && "Invalid operand number"); + return reinterpret_cast(N+1)+Op; } MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals, @@ -99,9 +99,9 @@ setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit); // Initialize the operand list, which is co-allocated on the end of the node. - for (MDNodeElement *Op = getOperandPtr(this, 0), *E = Op+NumOperands; + for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands; Op != E; ++Op, ++Vals) - new (Op) MDNodeElement(*Vals, this); + new (Op) MDNodeOperand(*Vals, this); } @@ -115,9 +115,9 @@ } // Destroy the operands. - for (MDNodeElement *Op = getOperandPtr(this, 0), *E = Op+NumOperands; + for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands; Op != E; ++Op) - Op->~MDNodeElement(); + Op->~MDNodeOperand(); } // destroy - Delete this node. Only when there are no uses. @@ -139,8 +139,8 @@ void *InsertPoint; MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint); if (!N) { - // Coallocate space for the node and elements together, then placement new. - void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeElement)); + // Coallocate space for the node and Operands together, then placement new. + void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand)); N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal); // InsertPoint will have been set by the FindNodeOrInsertPos call. @@ -149,19 +149,19 @@ return N; } -/// getElement - Return specified element. -Value *MDNode::getElement(unsigned i) const { +/// getOperand - Return specified operand. +Value *MDNode::getOperand(unsigned i) const { return *getOperandPtr(const_cast(this), i); } void MDNode::Profile(FoldingSetNodeID &ID) const { - for (unsigned i = 0, e = getNumElements(); i != e; ++i) - ID.AddPointer(getElement(i)); + for (unsigned i = 0, e = getNumOperands(); i != e; ++i) + ID.AddPointer(getOperand(i)); } -// Replace value from this node's element list. -void MDNode::replaceElement(MDNodeElement *Op, Value *To) { +// Replace value from this node's operand list. +void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) { Value *From = *Op; if (From == To) @@ -233,10 +233,10 @@ NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) { assert(NMD && "Invalid source NamedMDNode!"); SmallVector Elems; - Elems.reserve(NMD->getNumElements()); + Elems.reserve(NMD->getNumOperands()); - for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) - Elems.push_back(NMD->getElement(i)); + for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) + Elems.push_back(NMD->getOperand(i)); return new NamedMDNode(NMD->getContext(), NMD->getName().data(), Elems.data(), Elems.size(), M); } @@ -246,19 +246,19 @@ delete &getNMDOps(Operands); } -/// getNumElements - Return number of NamedMDNode elements. -unsigned NamedMDNode::getNumElements() const { +/// getNumOperands - Return number of NamedMDNode operands. +unsigned NamedMDNode::getNumOperands() const { return (unsigned)getNMDOps(Operands).size(); } -/// getElement - Return specified element. -MetadataBase *NamedMDNode::getElement(unsigned i) const { - assert(i < getNumElements() && "Invalid element number!"); +/// getOperand - Return specified operand. +MetadataBase *NamedMDNode::getOperand(unsigned i) const { + assert(i < getNumOperands() && "Invalid Operand number!"); return getNMDOps(Operands)[i]; } -/// addElement - Add metadata element. -void NamedMDNode::addElement(MetadataBase *M) { +/// addOperand - Add metadata Operand. +void NamedMDNode::addOperand(MetadataBase *M) { getNMDOps(Operands).push_back(TrackingVH(M)); } Modified: llvm/trunk/lib/VMCore/Verifier.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Verifier.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Verifier.cpp (original) +++ llvm/trunk/lib/VMCore/Verifier.cpp Wed Dec 30 19:22:29 2009 @@ -1538,8 +1538,8 @@ if (!Visited.insert(N)) return; - for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) { - Value *V = N->getElement(i); + for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { + Value *V = N->getOperand(i); if (!V) continue; Function *ActualF = 0; Modified: llvm/trunk/unittests/VMCore/MetadataTest.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/VMCore/MetadataTest.cpp?rev=92322&r1=92321&r2=92322&view=diff ============================================================================== --- llvm/trunk/unittests/VMCore/MetadataTest.cpp (original) +++ llvm/trunk/unittests/VMCore/MetadataTest.cpp Wed Dec 30 19:22:29 2009 @@ -92,13 +92,13 @@ (void) n3; #endif - EXPECT_EQ(3u, n1->getNumElements()); - EXPECT_EQ(s1, n1->getElement(0)); - EXPECT_EQ(CI, n1->getElement(1)); - EXPECT_EQ(s2, n1->getElement(2)); + EXPECT_EQ(3u, n1->getNumOperands()); + EXPECT_EQ(s1, n1->getOperand(0)); + EXPECT_EQ(CI, n1->getOperand(1)); + EXPECT_EQ(s2, n1->getOperand(2)); - EXPECT_EQ(1u, n2->getNumElements()); - EXPECT_EQ(n1, n2->getElement(0)); + EXPECT_EQ(1u, n2->getNumOperands()); + EXPECT_EQ(n1, n2->getOperand(0)); std::string Str; raw_string_ostream oss(Str); From sabre at nondot.org Wed Dec 30 19:32:41 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 01:32:41 -0000 Subject: [llvm-commits] [llvm] r92323 - in /llvm/trunk: include/llvm/IntrinsicInst.h include/llvm/Value.h lib/VMCore/IntrinsicInst.cpp Message-ID: <200912310132.nBV1Wf0V017577@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 19:32:41 2009 New Revision: 92323 URL: http://llvm.org/viewvc/llvm-project?rev=92323&view=rev Log: Remove #include of metadata.h from intrinsicinst.h. The only method that needs it (DbgValueInst::getValue) has been moved out of line. Modified: llvm/trunk/include/llvm/IntrinsicInst.h llvm/trunk/include/llvm/Value.h llvm/trunk/lib/VMCore/IntrinsicInst.cpp Modified: llvm/trunk/include/llvm/IntrinsicInst.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/IntrinsicInst.h?rev=92323&r1=92322&r2=92323&view=diff ============================================================================== --- llvm/trunk/include/llvm/IntrinsicInst.h (original) +++ llvm/trunk/include/llvm/IntrinsicInst.h Wed Dec 30 19:32:41 2009 @@ -25,7 +25,6 @@ #define LLVM_INTRINSICINST_H #include "llvm/Constants.h" -#include "llvm/Metadata.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" @@ -175,9 +174,7 @@ /// DbgValueInst - This represents the llvm.dbg.value instruction. /// struct DbgValueInst : public DbgInfoIntrinsic { - Value *getValue() const { - return cast(getOperand(1))->getOperand(0); - } + Value *getValue() const; Value *getOffset() const { return getOperand(2); } MDNode *getVariable() const { return cast(getOperand(3)); } Modified: llvm/trunk/include/llvm/Value.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Value.h?rev=92323&r1=92322&r2=92323&view=diff ============================================================================== --- llvm/trunk/include/llvm/Value.h (original) +++ llvm/trunk/include/llvm/Value.h Wed Dec 30 19:32:41 2009 @@ -42,6 +42,7 @@ class ValueHandleBase; class LLVMContext; class Twine; +class MDNode; //===----------------------------------------------------------------------===// // Value Class @@ -350,6 +351,9 @@ return isa(Val) || isa(Val) || isa(Val); } +template <> inline bool isa_impl(const Value &Val) { + return Val.getValueID() == Value::MDNodeVal; +} // Value* is only 4-byte aligned. Modified: llvm/trunk/lib/VMCore/IntrinsicInst.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/IntrinsicInst.cpp?rev=92323&r1=92322&r2=92323&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/IntrinsicInst.cpp (original) +++ llvm/trunk/lib/VMCore/IntrinsicInst.cpp Wed Dec 30 19:32:41 2009 @@ -69,3 +69,11 @@ assert(LLVMDebugVersion == (7 << 16) && "Verify operand indices"); return getContext()->getOperand(4); } + +//===----------------------------------------------------------------------===// +/// DbgValueInst - This represents the llvm.dbg.value instruction. +/// + +Value *DbgValueInst::getValue() const { + return cast(getOperand(1))->getOperand(0); +} From sabre at nondot.org Wed Dec 30 19:36:50 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 01:36:50 -0000 Subject: [llvm-commits] [llvm] r92324 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310136.nBV1apYI017706@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 19:36:50 2009 New Revision: 92324 URL: http://llvm.org/viewvc/llvm-project?rev=92324&view=rev Log: simplify asmprinting of NamedMDNode Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92324&r1=92323&r2=92324&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 19:36:50 2009 @@ -475,9 +475,6 @@ /// TheMDNode - The MDNode for which we are holding slot numbers. const MDNode *TheMDNode; - /// TheNamedMDNode - The MDNode for which we are holding slot numbers. - const NamedMDNode *TheNamedMDNode; - /// mMap - The TypePlanes map for the module level data. ValueMap mMap; unsigned mNext; @@ -496,8 +493,6 @@ explicit SlotTracker(const Function *F); /// Construct from a mdnode. explicit SlotTracker(const MDNode *N); - /// Construct from a named mdnode. - explicit SlotTracker(const NamedMDNode *N); /// Return the slot number of the specified value in it's type /// plane. If something is not in the SlotTracker, return -1. @@ -547,9 +542,6 @@ /// Add all MDNode operands. void processMDNode(); - /// Add all MDNode operands. - void processNamedMDNode(); - SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT void operator=(const SlotTracker &); // DO NOT IMPLEMENT }; @@ -589,26 +581,20 @@ // to be added to the slot table. SlotTracker::SlotTracker(const Module *M) : TheModule(M), TheFunction(0), FunctionProcessed(false), TheMDNode(0), - TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) { + mNext(0), fNext(0), mdnNext(0) { } // Function level constructor. Causes the contents of the Module and the one // function provided to be added to the slot table. SlotTracker::SlotTracker(const Function *F) : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false), - TheMDNode(0), TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) { + TheMDNode(0), mNext(0), fNext(0), mdnNext(0) { } // Constructor to handle single MDNode. SlotTracker::SlotTracker(const MDNode *C) : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(C), - TheNamedMDNode(0), mNext(0), fNext(0), mdnNext(0) { -} - -// Constructor to handle single NamedMDNode. -SlotTracker::SlotTracker(const NamedMDNode *N) - : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(0), - TheNamedMDNode(N), mNext(0), fNext(0), mdnNext(0) { + mNext(0), fNext(0), mdnNext(0) { } inline void SlotTracker::initialize() { @@ -622,9 +608,6 @@ if (TheMDNode) processMDNode(); - - if (TheNamedMDNode) - processNamedMDNode(); } // Iterate through all the global variables, functions, and global @@ -718,19 +701,6 @@ ST_DEBUG("end processMDNode!\n"); } -/// processNamedMDNode - Process TheNamedMDNode. -void SlotTracker::processNamedMDNode() { - ST_DEBUG("begin processNamedMDNode!\n"); - mdnNext = 0; - for (unsigned i = 0, e = TheNamedMDNode->getNumOperands(); i != e; ++i) { - MDNode *MD = dyn_cast_or_null(TheNamedMDNode->getOperand(i)); - if (MD) - CreateMetadataSlot(MD); - } - TheNamedMDNode = 0; - ST_DEBUG("end processNamedMDNode!\n"); -} - /// Clean up after incorporating a function. This is the only way to get out of /// the function incorporation state that affects get*Slot/Create*Slot. Function /// incorporation state is indicated by TheFunction != 0. @@ -2134,7 +2104,7 @@ SlotTable.initialize(); WriteMDNodes(OS, TypePrinter, SlotTable); } else if (const NamedMDNode *N = dyn_cast(this)) { - SlotTracker SlotTable(N); + SlotTracker SlotTable(N->getParent()); TypePrinting TypePrinter; SlotTable.initialize(); OS << "!" << N->getName() << " = !{"; From sabre at nondot.org Wed Dec 30 19:41:15 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 01:41:15 -0000 Subject: [llvm-commits] [llvm] r92325 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310141.nBV1fF4F017851@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 19:41:14 2009 New Revision: 92325 URL: http://llvm.org/viewvc/llvm-project?rev=92325&view=rev Log: simplify printing of mdstring and Argument. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92325&r1=92324&r2=92325&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 19:41:14 2009 @@ -57,9 +57,11 @@ const Function *M = I->getParent() ? I->getParent()->getParent() : 0; return M ? M->getParent() : 0; } - + if (const GlobalValue *GV = dyn_cast(V)) return GV->getParent(); + if (const NamedMDNode *NMD = dyn_cast(V)) + return NMD->getParent(); return 0; } @@ -2091,13 +2093,6 @@ SlotTracker SlotTable(GV->getParent()); AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW); W.write(GV); - } else if (const MDString *MDS = dyn_cast(this)) { - TypePrinting TypePrinter; - TypePrinter.print(MDS->getType(), OS); - OS << ' '; - OS << "!\""; - PrintEscapedString(MDS->getString(), OS); - OS << '"'; } else if (const MDNode *N = dyn_cast(this)) { SlotTracker SlotTable(N); TypePrinting TypePrinter; @@ -2123,10 +2118,8 @@ TypePrinter.print(C->getType(), OS); OS << ' '; WriteConstantInt(OS, C, TypePrinter, 0); - } else if (const Argument *A = dyn_cast(this)) { - WriteAsOperand(OS, this, true, - A->getParent() ? A->getParent()->getParent() : 0); - } else if (isa(this)) { + } else if (isa(this) || isa(this) || + isa(this)) { WriteAsOperand(OS, this, true, 0); } else { // Otherwise we don't know what it is. Call the virtual function to From sabre at nondot.org Wed Dec 30 19:44:44 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 01:44:44 -0000 Subject: [llvm-commits] [llvm] r92326 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310144.nBV1ii2Q017962@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 19:44:44 2009 New Revision: 92326 URL: http://llvm.org/viewvc/llvm-project?rev=92326&view=rev Log: fix printing of function-local metadata to print all the operands of the mdnode, not just operand 0 over and over. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92326&r1=92325&r2=92326&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 19:44:44 2009 @@ -1208,9 +1208,9 @@ if (!Val) Out << "null"; else { - TypePrinter->print(N->getOperand(0)->getType(), Out); + TypePrinter->print(N->getOperand(mi)->getType(), Out); Out << ' '; - WriteAsOperandInternal(Out, N->getOperand(0), TypePrinter, Machine); + WriteAsOperandInternal(Out, N->getOperand(mi), TypePrinter, Machine); } if (mi + 1 != me) Out << ", "; From sabre at nondot.org Wed Dec 30 19:54:05 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 01:54:05 -0000 Subject: [llvm-commits] [llvm] r92327 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310154.nBV1s5Q6018238@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 19:54:05 2009 New Revision: 92327 URL: http://llvm.org/viewvc/llvm-project?rev=92327&view=rev Log: unify two copies of the NamedMDNode printing code. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92327&r1=92326&r2=92327&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 19:54:05 2009 @@ -634,8 +634,8 @@ E = TheModule->named_metadata_end(); I != E; ++I) { const NamedMDNode *NMD = I; for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { - MDNode *MD = dyn_cast_or_null(NMD->getOperand(i)); - if (MD) + // FIXME: Change accessor to be type safe. + if (MDNode *MD = cast_or_null(NMD->getOperand(i))) CreateMetadataSlot(MD); } } @@ -1312,6 +1312,8 @@ M->getMDKindNames(MDNames); } + void printNamedMDNode(const NamedMDNode *NMD); + void write(const Module *M) { printModule(M); } void write(const GlobalValue *G) { @@ -1446,23 +1448,29 @@ // Output named metadata. if (!M->named_metadata_empty()) Out << '\n'; + for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), - E = M->named_metadata_end(); I != E; ++I) { - const NamedMDNode *NMD = I; - Out << "!" << NMD->getName() << " = !{"; - for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { - if (i) Out << ", "; - MDNode *MD = dyn_cast_or_null(NMD->getOperand(i)); - Out << '!' << Machine.getMetadataSlot(MD); - } - Out << "}\n"; - } + E = M->named_metadata_end(); I != E; ++I) + printNamedMDNode(I); // Output metadata. if (!Machine.mdnEmpty()) Out << '\n'; WriteMDNodes(Out, TypePrinter, Machine); } +void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { + Out << "!" << NMD->getName() << " = !{"; + for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { + if (i) Out << ", "; + // FIXME: Change accessor to be typesafe. + // FIXME: This doesn't handle null?? + MDNode *MD = cast_or_null(NMD->getOperand(i)); + Out << '!' << Machine.getMetadataSlot(MD); + } + Out << "}\n"; +} + + static void PrintLinkage(GlobalValue::LinkageTypes LT, formatted_raw_ostream &Out) { switch (LT) { @@ -2100,19 +2108,8 @@ WriteMDNodes(OS, TypePrinter, SlotTable); } else if (const NamedMDNode *N = dyn_cast(this)) { SlotTracker SlotTable(N->getParent()); - TypePrinting TypePrinter; - SlotTable.initialize(); - OS << "!" << N->getName() << " = !{"; - for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { - if (i) OS << ", "; - MDNode *MD = dyn_cast_or_null(N->getOperand(i)); - if (MD) - OS << '!' << SlotTable.getMetadataSlot(MD); - else - OS << "null"; - } - OS << "}\n"; - WriteMDNodes(OS, TypePrinter, SlotTable); + AssemblyWriter W(OS, SlotTable, N->getParent(), AAW); + W.printNamedMDNode(N); } else if (const Constant *C = dyn_cast(this)) { TypePrinting TypePrinter; TypePrinter.print(C->getType(), OS); From sabre at nondot.org Wed Dec 30 20:12:14 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 02:12:14 -0000 Subject: [llvm-commits] [llvm] r92328 - /llvm/trunk/unittests/VMCore/MetadataTest.cpp Message-ID: <200912310212.nBV2CEnK018759@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 20:12:13 2009 New Revision: 92328 URL: http://llvm.org/viewvc/llvm-project?rev=92328&view=rev Log: don't unittest mdnode printing, we have disassembler tests for this. Modified: llvm/trunk/unittests/VMCore/MetadataTest.cpp Modified: llvm/trunk/unittests/VMCore/MetadataTest.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/VMCore/MetadataTest.cpp?rev=92328&r1=92327&r2=92328&view=diff ============================================================================== --- llvm/trunk/unittests/VMCore/MetadataTest.cpp (original) +++ llvm/trunk/unittests/VMCore/MetadataTest.cpp Wed Dec 30 20:12:13 2009 @@ -99,17 +99,6 @@ EXPECT_EQ(1u, n2->getNumOperands()); EXPECT_EQ(n1, n2->getOperand(0)); - - std::string Str; - raw_string_ostream oss(Str); - n1->print(oss); - EXPECT_STREQ("!0 = metadata !{metadata !\"abc\", i8 0, metadata !\"123\"}\n", - oss.str().c_str()); - Str.clear(); - n2->print(oss); - EXPECT_STREQ("!0 = metadata !{metadata !1}\n" - "!1 = metadata !{metadata !\"abc\", i8 0, metadata !\"123\"}\n", - oss.str().c_str()); } TEST(MDNodeTest, Delete) { @@ -123,11 +112,6 @@ EXPECT_EQ(n, wvh); delete I; - - std::string Str; - raw_string_ostream oss(Str); - wvh->print(oss); - EXPECT_STREQ("!0 = metadata !{null}\n", oss.str().c_str()); } TEST(NamedMDNodeTest, Search) { @@ -147,8 +131,7 @@ std::string Str; raw_string_ostream oss(Str); NMD->print(oss); - EXPECT_STREQ("!llvm.NMD1 = !{!0, !1}\n!0 = metadata !{i32 1}\n" - "!1 = metadata !{i32 2}\n", + EXPECT_STREQ("!llvm.NMD1 = !{!0, !1}\n", oss.str().c_str()); } } From sabre at nondot.org Wed Dec 30 20:13:35 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 02:13:35 -0000 Subject: [llvm-commits] [llvm] r92329 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310213.nBV2DZQp018812@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 20:13:35 2009 New Revision: 92329 URL: http://llvm.org/viewvc/llvm-project?rev=92329&view=rev Log: simplify mdnode printing logic. Now N->dump() only dumps one node instead of all of them. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92329&r1=92328&r2=92329&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 20:13:35 2009 @@ -474,9 +474,6 @@ const Function* TheFunction; bool FunctionProcessed; - /// TheMDNode - The MDNode for which we are holding slot numbers. - const MDNode *TheMDNode; - /// mMap - The TypePlanes map for the module level data. ValueMap mMap; unsigned mNext; @@ -493,8 +490,6 @@ explicit SlotTracker(const Module *M); /// Construct from a function, starting out in incorp state. explicit SlotTracker(const Function *F); - /// Construct from a mdnode. - explicit SlotTracker(const MDNode *N); /// Return the slot number of the specified value in it's type /// plane. If something is not in the SlotTracker, return -1. @@ -541,9 +536,6 @@ /// Add all of the functions arguments, basic blocks, and instructions. void processFunction(); - /// Add all MDNode operands. - void processMDNode(); - SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT void operator=(const SlotTracker &); // DO NOT IMPLEMENT }; @@ -582,7 +574,7 @@ // Module level constructor. Causes the contents of the Module (sans functions) // to be added to the slot table. SlotTracker::SlotTracker(const Module *M) - : TheModule(M), TheFunction(0), FunctionProcessed(false), TheMDNode(0), + : TheModule(M), TheFunction(0), FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0) { } @@ -590,13 +582,7 @@ // function provided to be added to the slot table. SlotTracker::SlotTracker(const Function *F) : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false), - TheMDNode(0), mNext(0), fNext(0), mdnNext(0) { -} - -// Constructor to handle single MDNode. -SlotTracker::SlotTracker(const MDNode *C) - : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(C), - mNext(0), fNext(0), mdnNext(0) { + mNext(0), fNext(0), mdnNext(0) { } inline void SlotTracker::initialize() { @@ -607,9 +593,6 @@ if (TheFunction && !FunctionProcessed) processFunction(); - - if (TheMDNode) - processMDNode(); } // Iterate through all the global variables, functions, and global @@ -662,7 +645,7 @@ ST_DEBUG("Inserting Instructions:\n"); - SmallVector, 2> MDForInst; + SmallVector, 4> MDForInst; // Add all of the basic blocks and instructions with no names. for (Function::const_iterator BB = TheFunction->begin(), @@ -682,10 +665,10 @@ CreateMetadataSlot(N); // Process metadata attached with this instruction. - MDForInst.clear(); I->getAllMetadata(MDForInst); for (unsigned i = 0, e = MDForInst.size(); i != e; ++i) CreateMetadataSlot(MDForInst[i].second); + MDForInst.clear(); } } @@ -694,15 +677,6 @@ ST_DEBUG("end processFunction!\n"); } -/// processMDNode - Process TheMDNode. -void SlotTracker::processMDNode() { - ST_DEBUG("begin processMDNode!\n"); - mdnNext = 0; - CreateMetadataSlot(TheMDNode); - TheMDNode = 0; - ST_DEBUG("end processMDNode!\n"); -} - /// Clean up after incorporating a function. This is the only way to get out of /// the function incorporation state that affects get*Slot/Create*Slot. Function /// incorporation state is indicated by TheFunction != 0. @@ -812,97 +786,36 @@ static const char *getPredicateText(unsigned predicate) { const char * pred = "unknown"; switch (predicate) { - case FCmpInst::FCMP_FALSE: pred = "false"; break; - case FCmpInst::FCMP_OEQ: pred = "oeq"; break; - case FCmpInst::FCMP_OGT: pred = "ogt"; break; - case FCmpInst::FCMP_OGE: pred = "oge"; break; - case FCmpInst::FCMP_OLT: pred = "olt"; break; - case FCmpInst::FCMP_OLE: pred = "ole"; break; - case FCmpInst::FCMP_ONE: pred = "one"; break; - case FCmpInst::FCMP_ORD: pred = "ord"; break; - case FCmpInst::FCMP_UNO: pred = "uno"; break; - case FCmpInst::FCMP_UEQ: pred = "ueq"; break; - case FCmpInst::FCMP_UGT: pred = "ugt"; break; - case FCmpInst::FCMP_UGE: pred = "uge"; break; - case FCmpInst::FCMP_ULT: pred = "ult"; break; - case FCmpInst::FCMP_ULE: pred = "ule"; break; - case FCmpInst::FCMP_UNE: pred = "une"; break; - case FCmpInst::FCMP_TRUE: pred = "true"; break; - case ICmpInst::ICMP_EQ: pred = "eq"; break; - case ICmpInst::ICMP_NE: pred = "ne"; break; - case ICmpInst::ICMP_SGT: pred = "sgt"; break; - case ICmpInst::ICMP_SGE: pred = "sge"; break; - case ICmpInst::ICMP_SLT: pred = "slt"; break; - case ICmpInst::ICMP_SLE: pred = "sle"; break; - case ICmpInst::ICMP_UGT: pred = "ugt"; break; - case ICmpInst::ICMP_UGE: pred = "uge"; break; - case ICmpInst::ICMP_ULT: pred = "ult"; break; - case ICmpInst::ICMP_ULE: pred = "ule"; break; + case FCmpInst::FCMP_FALSE: pred = "false"; break; + case FCmpInst::FCMP_OEQ: pred = "oeq"; break; + case FCmpInst::FCMP_OGT: pred = "ogt"; break; + case FCmpInst::FCMP_OGE: pred = "oge"; break; + case FCmpInst::FCMP_OLT: pred = "olt"; break; + case FCmpInst::FCMP_OLE: pred = "ole"; break; + case FCmpInst::FCMP_ONE: pred = "one"; break; + case FCmpInst::FCMP_ORD: pred = "ord"; break; + case FCmpInst::FCMP_UNO: pred = "uno"; break; + case FCmpInst::FCMP_UEQ: pred = "ueq"; break; + case FCmpInst::FCMP_UGT: pred = "ugt"; break; + case FCmpInst::FCMP_UGE: pred = "uge"; break; + case FCmpInst::FCMP_ULT: pred = "ult"; break; + case FCmpInst::FCMP_ULE: pred = "ule"; break; + case FCmpInst::FCMP_UNE: pred = "une"; break; + case FCmpInst::FCMP_TRUE: pred = "true"; break; + case ICmpInst::ICMP_EQ: pred = "eq"; break; + case ICmpInst::ICMP_NE: pred = "ne"; break; + case ICmpInst::ICMP_SGT: pred = "sgt"; break; + case ICmpInst::ICMP_SGE: pred = "sge"; break; + case ICmpInst::ICMP_SLT: pred = "slt"; break; + case ICmpInst::ICMP_SLE: pred = "sle"; break; + case ICmpInst::ICMP_UGT: pred = "ugt"; break; + case ICmpInst::ICMP_UGE: pred = "uge"; break; + case ICmpInst::ICMP_ULT: pred = "ult"; break; + case ICmpInst::ICMP_ULE: pred = "ule"; break; } return pred; } -static void WriteMDNodeComment(const MDNode *Node, - formatted_raw_ostream &Out) { - if (Node->getNumOperands() < 1) - return; - ConstantInt *CI = dyn_cast_or_null(Node->getOperand(0)); - if (!CI) return; - unsigned Val = CI->getZExtValue(); - unsigned Tag = Val & ~LLVMDebugVersionMask; - if (Val < LLVMDebugVersion) - return; - - Out.PadToColumn(50); - if (Tag == dwarf::DW_TAG_auto_variable) - Out << "; [ DW_TAG_auto_variable ]"; - else if (Tag == dwarf::DW_TAG_arg_variable) - Out << "; [ DW_TAG_arg_variable ]"; - else if (Tag == dwarf::DW_TAG_return_variable) - Out << "; [ DW_TAG_return_variable ]"; - else if (Tag == dwarf::DW_TAG_vector_type) - Out << "; [ DW_TAG_vector_type ]"; - else if (Tag == dwarf::DW_TAG_user_base) - Out << "; [ DW_TAG_user_base ]"; - else if (const char *TagName = dwarf::TagString(Tag)) - Out << "; [ " << TagName << " ]"; -} - -static void WriteMDNodes(formatted_raw_ostream &Out, TypePrinting &TypePrinter, - SlotTracker &Machine) { - SmallVector Nodes; - Nodes.resize(Machine.mdnSize()); - for (SlotTracker::ValueMap::iterator I = - Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I) - Nodes[I->second] = cast(I->first); - - for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { - Out << '!' << i << " = metadata "; - const MDNode *Node = Nodes[i]; - Out << "!{"; - for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { - const Value *V = Node->getOperand(mi); - if (!V) - Out << "null"; - else if (const MDNode *N = dyn_cast(V)) { - Out << "metadata "; - Out << '!' << Machine.getMetadataSlot(N); - } - else { - TypePrinter.print(V->getType(), Out); - Out << ' '; - WriteAsOperandInternal(Out, Node->getOperand(mi), - &TypePrinter, &Machine); - } - if (mi + 1 != me) - Out << ", "; - } - - Out << "}"; - WriteMDNodeComment(Node, Out); - Out << "\n"; - } -} static void WriteOptimizationInfo(raw_ostream &Out, const User *U) { if (const OverflowingBinaryOperator *OBO = @@ -1312,6 +1225,7 @@ M->getMDKindNames(MDNames); } + void printMDNodeBody(const MDNode *MD); void printNamedMDNode(const NamedMDNode *NMD); void write(const Module *M) { printModule(M); } @@ -1333,6 +1247,8 @@ void writeOperand(const Value *Op, bool PrintType); void writeParamOperand(const Value *Operand, Attributes Attrs); + void writeAllMDNodes(); + private: void printModule(const Module *M); void printTypeSymbolTable(const TypeSymbolTable &ST); @@ -1450,12 +1366,14 @@ if (!M->named_metadata_empty()) Out << '\n'; for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), - E = M->named_metadata_end(); I != E; ++I) + E = M->named_metadata_end(); I != E; ++I) printNamedMDNode(I); // Output metadata. - if (!Machine.mdnEmpty()) Out << '\n'; - WriteMDNodes(Out, TypePrinter, Machine); + if (!Machine.mdnEmpty()) { + Out << '\n'; + writeAllMDNodes(); + } } void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { @@ -2061,6 +1979,68 @@ printInfoComment(I); } +static void WriteMDNodeComment(const MDNode *Node, + formatted_raw_ostream &Out) { + if (Node->getNumOperands() < 1) + return; + ConstantInt *CI = dyn_cast_or_null(Node->getOperand(0)); + if (!CI) return; + unsigned Val = CI->getZExtValue(); + unsigned Tag = Val & ~LLVMDebugVersionMask; + if (Val < LLVMDebugVersion) + return; + + Out.PadToColumn(50); + if (Tag == dwarf::DW_TAG_auto_variable) + Out << "; [ DW_TAG_auto_variable ]"; + else if (Tag == dwarf::DW_TAG_arg_variable) + Out << "; [ DW_TAG_arg_variable ]"; + else if (Tag == dwarf::DW_TAG_return_variable) + Out << "; [ DW_TAG_return_variable ]"; + else if (Tag == dwarf::DW_TAG_vector_type) + Out << "; [ DW_TAG_vector_type ]"; + else if (Tag == dwarf::DW_TAG_user_base) + Out << "; [ DW_TAG_user_base ]"; + else if (const char *TagName = dwarf::TagString(Tag)) + Out << "; [ " << TagName << " ]"; +} + +void AssemblyWriter::writeAllMDNodes() { + SmallVector Nodes; + Nodes.resize(Machine.mdnSize()); + for (SlotTracker::ValueMap::iterator I = + Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I) + Nodes[I->second] = cast(I->first); + + for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { + Out << '!' << i << " = metadata "; + const MDNode *Node = Nodes[i]; + printMDNodeBody(Node); + } +} + +void AssemblyWriter::printMDNodeBody(const MDNode *Node) { + Out << "!{"; + for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { + const Value *V = Node->getOperand(mi); + if (V == 0) + Out << "null"; + else if (const MDNode *N = dyn_cast(V)) { + Out << "metadata !" << Machine.getMetadataSlot(N); + } else { + TypePrinter.print(V->getType(), Out); + Out << ' '; + WriteAsOperandInternal(Out, Node->getOperand(mi), + &TypePrinter, &Machine); + } + if (mi + 1 != me) + Out << ", "; + } + + Out << "}"; + WriteMDNodeComment(Node, Out); + Out << "\n"; +} //===----------------------------------------------------------------------===// // External Interface declarations @@ -2090,22 +2070,20 @@ if (const Instruction *I = dyn_cast(this)) { const Function *F = I->getParent() ? I->getParent()->getParent() : 0; SlotTracker SlotTable(F); - AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW); + AssemblyWriter W(OS, SlotTable, getModuleFromVal(F), AAW); W.write(I); } else if (const BasicBlock *BB = dyn_cast(this)) { SlotTracker SlotTable(BB->getParent()); - AssemblyWriter W(OS, SlotTable, - BB->getParent() ? BB->getParent()->getParent() : 0, AAW); + AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW); W.write(BB); } else if (const GlobalValue *GV = dyn_cast(this)) { SlotTracker SlotTable(GV->getParent()); AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW); W.write(GV); } else if (const MDNode *N = dyn_cast(this)) { - SlotTracker SlotTable(N); - TypePrinting TypePrinter; - SlotTable.initialize(); - WriteMDNodes(OS, TypePrinter, SlotTable); + SlotTracker SlotTable((Function*)0); + AssemblyWriter W(OS, SlotTable, 0, AAW); + W.printMDNodeBody(N); } else if (const NamedMDNode *N = dyn_cast(this)) { SlotTracker SlotTable(N->getParent()); AssemblyWriter W(OS, SlotTable, N->getParent(), AAW); From sabre at nondot.org Wed Dec 30 20:15:45 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 02:15:45 -0000 Subject: [llvm-commits] [llvm] r92330 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310215.nBV2FjVd018887@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 20:15:45 2009 New Revision: 92330 URL: http://llvm.org/viewvc/llvm-project?rev=92330&view=rev Log: metadata can't be a global var initializer. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92330&r1=92329&r2=92330&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 20:15:45 2009 @@ -605,10 +605,6 @@ E = TheModule->global_end(); I != E; ++I) { if (!I->hasName()) CreateModuleSlot(I); - if (I->hasInitializer()) { - if (MDNode *N = dyn_cast(I->getInitializer())) - CreateMetadataSlot(N); - } } // Add metadata used by named metadata. From sabre at nondot.org Wed Dec 30 20:20:12 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 02:20:12 -0000 Subject: [llvm-commits] [llvm] r92331 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310220.nBV2KCpq019034@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 20:20:11 2009 New Revision: 92331 URL: http://llvm.org/viewvc/llvm-project?rev=92331&view=rev Log: make mdnMap type safe, rename accessors for consistency with the rest of llvm. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92331&r1=92330&r2=92331&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 20:20:11 2009 @@ -483,7 +483,7 @@ unsigned fNext; /// mdnMap - Map for MDNodes. - ValueMap mdnMap; + DenseMap mdnMap; unsigned mdnNext; public: /// Construct from a module @@ -510,10 +510,11 @@ void purgeFunction(); /// MDNode map iterators. - ValueMap::iterator mdnBegin() { return mdnMap.begin(); } - ValueMap::iterator mdnEnd() { return mdnMap.end(); } - unsigned mdnSize() const { return mdnMap.size(); } - bool mdnEmpty() const { return mdnMap.empty(); } + typedef DenseMap::iterator mdn_iterator; + mdn_iterator mdn_begin() { return mdnMap.begin(); } + mdn_iterator mdn_end() { return mdnMap.end(); } + unsigned mdn_size() const { return mdnMap.size(); } + bool mdn_empty() const { return mdnMap.empty(); } /// This function does the actual initialization. inline void initialize(); @@ -694,13 +695,13 @@ return MI == mMap.end() ? -1 : (int)MI->second; } -/// getGlobalSlot - Get the slot number of a MDNode. +/// getMetadataSlot - Get the slot number of a MDNode. int SlotTracker::getMetadataSlot(const MDNode *N) { // Check for uninitialized state and do lazy initialization. initialize(); // Find the type plane in the module map - ValueMap::iterator MI = mdnMap.find(N); + mdn_iterator MI = mdnMap.find(N); return MI == mdnMap.end() ? -1 : (int)MI->second; } @@ -754,7 +755,7 @@ if (N->isFunctionLocal()) return; - ValueMap::iterator I = mdnMap.find(N); + mdn_iterator I = mdnMap.find(N); if (I != mdnMap.end()) return; @@ -1366,7 +1367,7 @@ printNamedMDNode(I); // Output metadata. - if (!Machine.mdnEmpty()) { + if (!Machine.mdn_empty()) { Out << '\n'; writeAllMDNodes(); } @@ -2003,9 +2004,9 @@ void AssemblyWriter::writeAllMDNodes() { SmallVector Nodes; - Nodes.resize(Machine.mdnSize()); - for (SlotTracker::ValueMap::iterator I = - Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I) + Nodes.resize(Machine.mdn_size()); + for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end(); + I != E; ++I) Nodes[I->second] = cast(I->first); for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { From sabre at nondot.org Wed Dec 30 20:23:35 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 02:23:35 -0000 Subject: [llvm-commits] [llvm] r92332 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310223.nBV2NZcq019148@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 20:23:35 2009 New Revision: 92332 URL: http://llvm.org/viewvc/llvm-project?rev=92332&view=rev Log: eliminate a bunch of useless forwarding functions with one caller. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92332&r1=92331&r2=92332&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 20:23:35 2009 @@ -1225,29 +1225,13 @@ void printMDNodeBody(const MDNode *MD); void printNamedMDNode(const NamedMDNode *NMD); - void write(const Module *M) { printModule(M); } - - void write(const GlobalValue *G) { - if (const GlobalVariable *GV = dyn_cast(G)) - printGlobal(GV); - else if (const GlobalAlias *GA = dyn_cast(G)) - printAlias(GA); - else if (const Function *F = dyn_cast(G)) - printFunction(F); - else - llvm_unreachable("Unknown global"); - } - - void write(const BasicBlock *BB) { printBasicBlock(BB); } - void write(const Instruction *I) { printInstruction(*I); } + void printModule(const Module *M); void writeOperand(const Value *Op, bool PrintType); void writeParamOperand(const Value *Operand, Attributes Attrs); void writeAllMDNodes(); -private: - void printModule(const Module *M); void printTypeSymbolTable(const TypeSymbolTable &ST); void printGlobal(const GlobalVariable *GV); void printAlias(const GlobalAlias *GV); @@ -1255,6 +1239,7 @@ void printArgument(const Argument *FA, Attributes Attrs); void printBasicBlock(const BasicBlock *BB); void printInstruction(const Instruction &I); +private: // printInfoComment - Print a little comment after the instruction indicating // which slot it occupies. @@ -2047,7 +2032,7 @@ SlotTracker SlotTable(this); formatted_raw_ostream OS(ROS); AssemblyWriter W(OS, SlotTable, this, AAW); - W.write(this); + W.printModule(this); } void Type::print(raw_ostream &OS) const { @@ -2068,15 +2053,20 @@ const Function *F = I->getParent() ? I->getParent()->getParent() : 0; SlotTracker SlotTable(F); AssemblyWriter W(OS, SlotTable, getModuleFromVal(F), AAW); - W.write(I); + W.printInstruction(*I); } else if (const BasicBlock *BB = dyn_cast(this)) { SlotTracker SlotTable(BB->getParent()); AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW); - W.write(BB); + W.printBasicBlock(BB); } else if (const GlobalValue *GV = dyn_cast(this)) { SlotTracker SlotTable(GV->getParent()); AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW); - W.write(GV); + if (const GlobalVariable *V = dyn_cast(GV)) + W.printGlobal(V); + else if (const Function *F = dyn_cast(GV)) + W.printFunction(F); + else + W.printAlias(cast(GV)); } else if (const MDNode *N = dyn_cast(this)) { SlotTracker SlotTable((Function*)0); AssemblyWriter W(OS, SlotTable, 0, AAW); From sabre at nondot.org Wed Dec 30 20:27:30 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 02:27:30 -0000 Subject: [llvm-commits] [llvm] r92333 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310227.nBV2RU1V019284@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 20:27:30 2009 New Revision: 92333 URL: http://llvm.org/viewvc/llvm-project?rev=92333&view=rev Log: random tidying for MDNode printing. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92333&r1=92332&r2=92333&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 20:27:30 2009 @@ -751,7 +751,8 @@ void SlotTracker::CreateMetadataSlot(const MDNode *N) { assert(N && "Can't insert a null Value into SlotTracker!"); - // Don't insert if N is a function-local metadata. + // Don't insert if N is a function-local metadata, these are always printed + // inline. if (N->isFunctionLocal()) return; @@ -762,12 +763,10 @@ unsigned DestSlot = mdnNext++; mdnMap[N] = DestSlot; - for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { - const Value *TV = N->getOperand(i); - if (TV) - if (const MDNode *N2 = dyn_cast(TV)) - CreateMetadataSlot(N2); - } + // Recursively add any MDNodes referenced by operands. + for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) + if (const MDNode *Op = dyn_cast_or_null(N->getOperand(i))) + CreateMetadataSlot(Op); } //===----------------------------------------------------------------------===// @@ -1217,7 +1216,6 @@ AssemblyAnnotationWriter *AAW) : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) { AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M); - // FIXME: Provide MDPrinter if (M) M->getMDKindNames(MDNames); } @@ -1996,8 +1994,7 @@ for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { Out << '!' << i << " = metadata "; - const MDNode *Node = Nodes[i]; - printMDNodeBody(Node); + printMDNodeBody(Nodes[i]); } } From sabre at nondot.org Wed Dec 30 20:31:59 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 02:31:59 -0000 Subject: [llvm-commits] [llvm] r92334 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310231.nBV2VxSw019410@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 20:31:59 2009 New Revision: 92334 URL: http://llvm.org/viewvc/llvm-project?rev=92334&view=rev Log: eliminate another copy of the mdnode printing logic, simplify the one that remains. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92334&r1=92333&r2=92334&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 20:31:59 2009 @@ -1074,6 +1074,27 @@ Out << ""; } +static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, + TypePrinting *TypePrinter, + SlotTracker *Machine) { + Out << "!{"; + for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { + const Value *V = Node->getOperand(mi); + if (V == 0) + Out << "null"; + else { + TypePrinter->print(V->getType(), Out); + Out << ' '; + WriteAsOperandInternal(Out, Node->getOperand(mi), + TypePrinter, Machine); + } + if (mi + 1 != me) + Out << ", "; + } + + Out << "}"; +} + /// WriteAsOperand - Write the name of the specified value out to the specified /// ostream. This can be useful when you just want to print int %reg126, not @@ -1111,20 +1132,7 @@ if (const MDNode *N = dyn_cast(V)) { if (N->isFunctionLocal()) { // Print metadata inline, not via slot reference number. - Out << "!{"; - for (unsigned mi = 0, me = N->getNumOperands(); mi != me; ++mi) { - const Value *Val = N->getOperand(mi); - if (!Val) - Out << "null"; - else { - TypePrinter->print(N->getOperand(mi)->getType(), Out); - Out << ' '; - WriteAsOperandInternal(Out, N->getOperand(mi), TypePrinter, Machine); - } - if (mi + 1 != me) - Out << ", "; - } - Out << '}'; + WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine); return; } @@ -1999,24 +2007,7 @@ } void AssemblyWriter::printMDNodeBody(const MDNode *Node) { - Out << "!{"; - for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { - const Value *V = Node->getOperand(mi); - if (V == 0) - Out << "null"; - else if (const MDNode *N = dyn_cast(V)) { - Out << "metadata !" << Machine.getMetadataSlot(N); - } else { - TypePrinter.print(V->getType(), Out); - Out << ' '; - WriteAsOperandInternal(Out, Node->getOperand(mi), - &TypePrinter, &Machine); - } - if (mi + 1 != me) - Out << ", "; - } - - Out << "}"; + WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine); WriteMDNodeComment(Node, Out); Out << "\n"; } From sabre at nondot.org Wed Dec 30 20:33:14 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 02:33:14 -0000 Subject: [llvm-commits] [llvm] r92335 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310233.nBV2XEak019482@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 20:33:14 2009 New Revision: 92335 URL: http://llvm.org/viewvc/llvm-project?rev=92335&view=rev Log: use early exits to reduce indentation. Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92335&r1=92334&r2=92335&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Wed Dec 30 20:33:14 2009 @@ -1257,29 +1257,30 @@ void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { if (Operand == 0) { Out << ""; - } else { - if (PrintType) { - TypePrinter.print(Operand->getType(), Out); - Out << ' '; - } - WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine); + return; } + if (PrintType) { + TypePrinter.print(Operand->getType(), Out); + Out << ' '; + } + WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine); } void AssemblyWriter::writeParamOperand(const Value *Operand, Attributes Attrs) { if (Operand == 0) { Out << ""; - } else { - // Print the type - TypePrinter.print(Operand->getType(), Out); - // Print parameter attributes list - if (Attrs != Attribute::None) - Out << ' ' << Attribute::getAsString(Attrs); - Out << ' '; - // Print the operand - WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine); + return; } + + // Print the type + TypePrinter.print(Operand->getType(), Out); + // Print parameter attributes list + if (Attrs != Attribute::None) + Out << ' ' << Attribute::getAsString(Attrs); + Out << ' '; + // Print the operand + WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine); } void AssemblyWriter::printModule(const Module *M) { From sabre at nondot.org Wed Dec 30 21:00:49 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 03:00:49 -0000 Subject: [llvm-commits] [llvm] r92336 - /llvm/trunk/test/Assembler/metadata.ll Message-ID: <200912310300.nBV30nq6020329@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 21:00:49 2009 New Revision: 92336 URL: http://llvm.org/viewvc/llvm-project?rev=92336&view=rev Log: add some basic named MD tests. Modified: llvm/trunk/test/Assembler/metadata.ll Modified: llvm/trunk/test/Assembler/metadata.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Assembler/metadata.ll?rev=92336&r1=92335&r2=92336&view=diff ============================================================================== --- llvm/trunk/test/Assembler/metadata.ll (original) +++ llvm/trunk/test/Assembler/metadata.ll Wed Dec 30 21:00:49 2009 @@ -16,4 +16,7 @@ declare void @llvm.dbg.func.start(metadata) nounwind readnone +!foo = !{ !0 } +!bar = !{ !1 } + ; !foo = !{ !0, !"foo" } \ No newline at end of file From sabre at nondot.org Wed Dec 30 21:02:08 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 03:02:08 -0000 Subject: [llvm-commits] [llvm] r92337 - in /llvm/trunk: include/llvm/Analysis/DebugInfo.h lib/Analysis/DbgInfoPrinter.cpp lib/Analysis/DebugInfo.cpp lib/Transforms/Utils/CloneFunction.cpp Message-ID: <200912310302.nBV328tN020382@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 21:02:08 2009 New Revision: 92337 URL: http://llvm.org/viewvc/llvm-project?rev=92337&view=rev Log: fix Analysis/DebugInfo.h to not include Metadata.h. Do this by moving one method out of line and eliminating redundant checks from other methods. Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h llvm/trunk/lib/Analysis/DbgInfoPrinter.cpp llvm/trunk/lib/Analysis/DebugInfo.cpp llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Analysis/DebugInfo.h?rev=92337&r1=92336&r2=92337&view=diff ============================================================================== --- llvm/trunk/include/llvm/Analysis/DebugInfo.h (original) +++ llvm/trunk/include/llvm/Analysis/DebugInfo.h Wed Dec 30 21:02:08 2009 @@ -17,9 +17,9 @@ #ifndef LLVM_ANALYSIS_DEBUGINFO_H #define LLVM_ANALYSIS_DEBUGINFO_H -#include "llvm/Metadata.h" // FIXME: Should not need this. #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/StringRef.h" #include "llvm/Support/Dwarf.h" // FIXME: Should not need this. namespace llvm { @@ -38,6 +38,8 @@ class DebugLoc; struct DebugLocTracker; class Instruction; + class MDNode; + class LLVMContext; /// DIDescriptor - A thin wraper around MDNode to access encoded debug info. /// This should not be stored in a container, because underly MDNode may @@ -368,20 +370,10 @@ unsigned isLocalToUnit() const { return getUnsignedField(9); } unsigned isDefinition() const { return getUnsignedField(10); } - unsigned getVirtuality() const { - if (DbgNode->getNumOperands() < 14) - return 0; - return getUnsignedField(11); - } - - unsigned getVirtualIndex() const { - if (DbgNode->getNumOperands() < 14) - return 0; - return getUnsignedField(12); - } + unsigned getVirtuality() const { return getUnsignedField(11); } + unsigned getVirtualIndex() const { return getUnsignedField(12); } DICompositeType getContainingType() const { - assert (DbgNode->getNumOperands() >= 14 && "Invalid type!"); return getFieldAs(13); } @@ -439,8 +431,8 @@ return getNumAddrElements() > 0; } - unsigned getNumAddrElements() const { return DbgNode->getNumOperands()-6; } - + unsigned getNumAddrElements() const; + uint64_t getAddrElement(unsigned Idx) const { return getUInt64Field(Idx+6); } Modified: llvm/trunk/lib/Analysis/DbgInfoPrinter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DbgInfoPrinter.cpp?rev=92337&r1=92336&r2=92337&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DbgInfoPrinter.cpp (original) +++ llvm/trunk/lib/Analysis/DbgInfoPrinter.cpp Wed Dec 30 21:02:08 2009 @@ -19,6 +19,7 @@ #include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/IntrinsicInst.h" +#include "llvm/Metadata.h" #include "llvm/Assembly/Writer.h" #include "llvm/Analysis/DebugInfo.h" #include "llvm/Analysis/Passes.h" Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=92337&r1=92336&r2=92337&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Wed Dec 30 21:02:08 2009 @@ -120,6 +120,11 @@ return 0; } +unsigned DIVariable::getNumAddrElements() const { + return DbgNode->getNumOperands()-6; +} + + //===----------------------------------------------------------------------===// // Predicates //===----------------------------------------------------------------------===// Modified: llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp?rev=92337&r1=92336&r2=92337&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp (original) +++ llvm/trunk/lib/Transforms/Utils/CloneFunction.cpp Wed Dec 30 21:02:08 2009 @@ -21,6 +21,7 @@ #include "llvm/GlobalVariable.h" #include "llvm/Function.h" #include "llvm/LLVMContext.h" +#include "llvm/Metadata.h" #include "llvm/Support/CFG.h" #include "llvm/Transforms/Utils/ValueMapper.h" #include "llvm/Analysis/ConstantFolding.h" From sabre at nondot.org Wed Dec 30 21:02:42 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 03:02:42 -0000 Subject: [llvm-commits] [llvm] r92338 - /llvm/trunk/include/llvm/Analysis/DebugInfo.h Message-ID: <200912310302.nBV32gdP020406@zion.cs.uiuc.edu> Author: lattner Date: Wed Dec 30 21:02:42 2009 New Revision: 92338 URL: http://llvm.org/viewvc/llvm-project?rev=92338&view=rev Log: this #include is ok. Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h Modified: llvm/trunk/include/llvm/Analysis/DebugInfo.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Analysis/DebugInfo.h?rev=92338&r1=92337&r2=92338&view=diff ============================================================================== --- llvm/trunk/include/llvm/Analysis/DebugInfo.h (original) +++ llvm/trunk/include/llvm/Analysis/DebugInfo.h Wed Dec 30 21:02:42 2009 @@ -20,7 +20,7 @@ #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringRef.h" -#include "llvm/Support/Dwarf.h" // FIXME: Should not need this. +#include "llvm/Support/Dwarf.h" namespace llvm { class BasicBlock; From dgregor at apple.com Wed Dec 30 22:24:37 2009 From: dgregor at apple.com (Douglas Gregor) Date: Thu, 31 Dec 2009 04:24:37 -0000 Subject: [llvm-commits] [llvm] r92340 - in /llvm/trunk: lib/Support/StringRef.cpp unittests/ADT/StringRefTest.cpp Message-ID: <200912310424.nBV4Ockn023461@zion.cs.uiuc.edu> Author: dgregor Date: Wed Dec 30 22:24:34 2009 New Revision: 92340 URL: http://llvm.org/viewvc/llvm-project?rev=92340&view=rev Log: Document the edit-distance algorithm used in StringRef, switch it over to SmallVector, and add a unit test. Modified: llvm/trunk/lib/Support/StringRef.cpp llvm/trunk/unittests/ADT/StringRefTest.cpp Modified: llvm/trunk/lib/Support/StringRef.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Support/StringRef.cpp?rev=92340&r1=92339&r2=92340&view=diff ============================================================================== --- llvm/trunk/lib/Support/StringRef.cpp (original) +++ llvm/trunk/lib/Support/StringRef.cpp Wed Dec 30 22:24:34 2009 @@ -8,7 +8,7 @@ //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" -#include +#include "llvm/ADT/SmallVector.h" using namespace llvm; // MSVC emits references to this into the translation units which reference it. @@ -36,17 +36,26 @@ return Length < RHS.Length ? -1 : 1; } -/// \brief Compute the edit distance between the two given strings. +// Compute the edit distance between the two given strings. unsigned StringRef::edit_distance(llvm::StringRef Other, bool AllowReplacements) { + // The algorithm implemented below is the "classic" + // dynamic-programming algorithm for computing the Levenshtein + // distance, which is described here: + // + // http://en.wikipedia.org/wiki/Levenshtein_distance + // + // Although the algorithm is typically described using an m x n + // array, only two rows are used at a time, so this implemenation + // just keeps two separate vectors for those two rows. size_type m = size(); size_type n = Other.size(); - std::vector previous(n+1, 0); - for (std::vector::size_type i = 0; i <= n; ++i) + SmallVector previous(n+1, 0); + for (SmallVector::size_type i = 0; i <= n; ++i) previous[i] = i; - std::vector current(n+1, 0); + SmallVector current(n+1, 0); for (size_type y = 1; y <= m; ++y) { current.assign(n+1, 0); current[0] = y; Modified: llvm/trunk/unittests/ADT/StringRefTest.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/ADT/StringRefTest.cpp?rev=92340&r1=92339&r2=92340&view=diff ============================================================================== --- llvm/trunk/unittests/ADT/StringRefTest.cpp (original) +++ llvm/trunk/unittests/ADT/StringRefTest.cpp Wed Dec 30 22:24:34 2009 @@ -247,6 +247,11 @@ EXPECT_EQ(0U, Str.count("zz")); } +TEST(StringRefTest, EditDistance) { + StringRef Str("hello"); + EXPECT_EQ(2, Str.edit_distance("hill")); +} + TEST(StringRefTest, Misc) { std::string Storage; raw_string_ostream OS(Storage); From sabre at nondot.org Thu Dec 31 01:17:37 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 07:17:37 -0000 Subject: [llvm-commits] [llvm] r92343 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912310717.nBV7Hbrv028740@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 01:17:37 2009 New Revision: 92343 URL: http://llvm.org/viewvc/llvm-project?rev=92343&view=rev Log: clean up -debug output. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92343&r1=92342&r2=92343&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 01:17:37 2009 @@ -61,10 +61,11 @@ static void PrintOps(Instruction *I, const std::vector &Ops) { Module *M = I->getParent()->getParent()->getParent(); errs() << Instruction::getOpcodeName(I->getOpcode()) << " " - << *Ops[0].Op->getType(); + << *Ops[0].Op->getType() << '\t'; for (unsigned i = 0, e = Ops.size(); i != e; ++i) { - WriteAsOperand(errs() << " ", Ops[i].Op, false, M); - errs() << "," << Ops[i].Rank; + errs() << "[ "; + WriteAsOperand(errs(), Ops[i].Op, false, M); + errs() << ", #" << Ops[i].Rank << "] "; } } #endif From sabre at nondot.org Thu Dec 31 01:33:14 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 07:33:14 -0000 Subject: [llvm-commits] [llvm] r92344 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912310733.nBV7XEl9029203@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 01:33:14 2009 New Revision: 92344 URL: http://llvm.org/viewvc/llvm-project?rev=92344&view=rev Log: use more modern datastructures. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92344&r1=92343&r2=92344&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 01:33:14 2009 @@ -35,6 +35,7 @@ #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/Statistic.h" +#include "llvm/ADT/DenseMap.h" #include #include using namespace llvm; @@ -600,7 +601,7 @@ } if (Ops.size() == 1) return Ops[0].Op; - // Handle destructive annihilation do to identities between elements in the + // Handle destructive annihilation due to identities between elements in the // argument list here. switch (Opcode) { default: break; @@ -688,7 +689,7 @@ // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies. // To efficiently find this, we count the number of times a factor occurs // for any ADD operands that are MULs. - std::map FactorOccurrences; + DenseMap FactorOccurrences; unsigned MaxOcc = 0; Value *MaxOccVal = 0; for (unsigned i = 0, e = Ops.size(); i != e; ++i) { @@ -708,9 +709,9 @@ if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[1]; } } } else { - std::set Duplicates; + SmallPtrSet Duplicates; for (unsigned i = 0, e = Factors.size(); i != e; ++i) { - if (Duplicates.insert(Factors[i]).second) { + if (Duplicates.insert(Factors[i])) { unsigned Occ = ++FactorOccurrences[Factors[i]]; if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[i]; } } From sabre at nondot.org Thu Dec 31 01:48:51 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 07:48:51 -0000 Subject: [llvm-commits] [llvm] r92346 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912310748.nBV7mqSr029645@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 01:48:51 2009 New Revision: 92346 URL: http://llvm.org/viewvc/llvm-project?rev=92346&view=rev Log: switch some std::vector's to smallvector. Reduce nesting. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92346&r1=92345&r2=92346&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 01:48:51 2009 @@ -494,7 +494,7 @@ /// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together /// and returning the result. Insert the tree before I. -static Value *EmitAddTreeOfValues(Instruction *I, std::vector &Ops) { +static Value *EmitAddTreeOfValues(Instruction *I, SmallVectorImpl &Ops){ if (Ops.size() == 1) return Ops.back(); Value *V1 = Ops.back(); @@ -535,7 +535,7 @@ /// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively /// add its operands as factors, otherwise add V to the list of factors. static void FindSingleUseMultiplyFactors(Value *V, - std::vector &Factors) { + SmallVectorImpl &Factors) { BinaryOperator *BO; if ((!V->hasOneUse() && !V->use_empty()) || !(BO = dyn_cast(V)) || @@ -575,17 +575,18 @@ if (CstVal->isZero()) { // ... & 0 -> 0 ++NumAnnihil; return CstVal; - } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ... - Ops.pop_back(); } + if (CstVal->isAllOnesValue()) // ... & -1 -> ... + Ops.pop_back(); break; case Instruction::Mul: if (CstVal->isZero()) { // ... * 0 -> 0 ++NumAnnihil; return CstVal; - } else if (cast(CstVal)->isOne()) { - Ops.pop_back(); // ... * 1 -> ... } + + if (cast(CstVal)->isOne()) + Ops.pop_back(); // ... * 1 -> ... break; case Instruction::Or: if (CstVal->isAllOnesValue()) { // ... | -1 -> -1 @@ -620,7 +621,9 @@ if (Opcode == Instruction::And) { // ...&X&~X = 0 ++NumAnnihil; return Constant::getNullValue(X->getType()); - } else if (Opcode == Instruction::Or) { // ...|X|~X = -1 + } + + if (Opcode == Instruction::Or) { // ...|X|~X = -1 ++NumAnnihil; return Constant::getAllOnesValue(X->getType()); } @@ -659,30 +662,30 @@ for (unsigned i = 0, e = Ops.size(); i != e; ++i) { assert(i < Ops.size()); // Check for X and -X in the operand list. - if (BinaryOperator::isNeg(Ops[i].Op)) { - Value *X = BinaryOperator::getNegArgument(Ops[i].Op); - unsigned FoundX = FindInOperandList(Ops, i, X); - if (FoundX != i) { - // Remove X and -X from the operand list. - if (Ops.size() == 2) { - ++NumAnnihil; - return Constant::getNullValue(X->getType()); - } else { - Ops.erase(Ops.begin()+i); - if (i < FoundX) - --FoundX; - else - --i; // Need to back up an extra one. - Ops.erase(Ops.begin()+FoundX); - IterateOptimization = true; - ++NumAnnihil; - --i; // Revisit element. - e -= 2; // Removed two elements. - } - } + if (!BinaryOperator::isNeg(Ops[i].Op)) + continue; + + Value *X = BinaryOperator::getNegArgument(Ops[i].Op); + unsigned FoundX = FindInOperandList(Ops, i, X); + if (FoundX == i) + continue; + + // Remove X and -X from the operand list. + if (Ops.size() == 2) { + ++NumAnnihil; + return Constant::getNullValue(X->getType()); } + Ops.erase(Ops.begin()+i); + if (i < FoundX) + --FoundX; + else + --i; // Need to back up an extra one. + Ops.erase(Ops.begin()+FoundX); + IterateOptimization = true; + ++NumAnnihil; + --i; // Revisit element. + e -= 2; // Removed two elements. } - // Scan the operand list, checking to see if there are any common factors // between operands. Consider something like A*A+A*B*C+D. We would like to @@ -693,30 +696,30 @@ unsigned MaxOcc = 0; Value *MaxOccVal = 0; for (unsigned i = 0, e = Ops.size(); i != e; ++i) { - if (BinaryOperator *BOp = dyn_cast(Ops[i].Op)) { - if (BOp->getOpcode() == Instruction::Mul && BOp->use_empty()) { - // Compute all of the factors of this added value. - std::vector Factors; - FindSingleUseMultiplyFactors(BOp, Factors); - assert(Factors.size() > 1 && "Bad linearize!"); - - // Add one to FactorOccurrences for each unique factor in this op. - if (Factors.size() == 2) { - unsigned Occ = ++FactorOccurrences[Factors[0]]; - if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[0]; } - if (Factors[0] != Factors[1]) { // Don't double count A*A. - Occ = ++FactorOccurrences[Factors[1]]; - if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[1]; } - } - } else { - SmallPtrSet Duplicates; - for (unsigned i = 0, e = Factors.size(); i != e; ++i) { - if (Duplicates.insert(Factors[i])) { - unsigned Occ = ++FactorOccurrences[Factors[i]]; - if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[i]; } - } - } - } + BinaryOperator *BOp = dyn_cast(Ops[i].Op); + if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty()) + continue; + + // Compute all of the factors of this added value. + SmallVector Factors; + FindSingleUseMultiplyFactors(BOp, Factors); + assert(Factors.size() > 1 && "Bad linearize!"); + + // Add one to FactorOccurrences for each unique factor in this op. + if (Factors.size() == 2) { + unsigned Occ = ++FactorOccurrences[Factors[0]]; + if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[0]; } + if (Factors[0] != Factors[1]) { // Don't double count A*A. + Occ = ++FactorOccurrences[Factors[1]]; + if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[1]; } + } + } else { + SmallPtrSet Duplicates; + for (unsigned i = 0, e = Factors.size(); i != e; ++i) { + if (!Duplicates.insert(Factors[i])) continue; + + unsigned Occ = ++FactorOccurrences[Factors[i]]; + if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[i]; } } } } @@ -730,7 +733,7 @@ // from an expression will drop a use of maxocc, and this can cause // RemoveFactorFromExpression on successive values to behave differently. Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal); - std::vector NewMulOps; + SmallVector NewMulOps; for (unsigned i = 0, e = Ops.size(); i != e; ++i) { if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) { NewMulOps.push_back(V); From sabre at nondot.org Thu Dec 31 01:59:35 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 07:59:35 -0000 Subject: [llvm-commits] [llvm] r92347 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912310759.nBV7xZnI029970@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 01:59:34 2009 New Revision: 92347 URL: http://llvm.org/viewvc/llvm-project?rev=92347&view=rev Log: factor code out into helper functions. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92347&r1=92346&r2=92347&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 01:59:34 2009 @@ -92,6 +92,7 @@ void RewriteExprTree(BinaryOperator *I, std::vector &Ops, unsigned Idx = 0); Value *OptimizeExpression(BinaryOperator *I, std::vector &Ops); + Value *OptimizeAdd(std::vector &Ops); void LinearizeExprTree(BinaryOperator *I, std::vector &Ops); void LinearizeExpr(BinaryOperator *I); Value *RemoveFactorFromExpression(Value *V, Value *Factor); @@ -284,15 +285,15 @@ I->setOperand(0, UndefValue::get(I->getType())); I->setOperand(1, UndefValue::get(I->getType())); return; - } else { - // Turn X+(Y+Z) -> (Y+Z)+X - std::swap(LHSBO, RHSBO); - std::swap(LHS, RHS); - bool Success = !I->swapOperands(); - assert(Success && "swapOperands failed"); - Success = false; - MadeChange = true; } + + // Turn X+(Y+Z) -> (Y+Z)+X + std::swap(LHSBO, RHSBO); + std::swap(LHS, RHS); + bool Success = !I->swapOperands(); + assert(Success && "swapOperands failed"); + Success = false; + MadeChange = true; } else if (RHSBO) { // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not // part of the expression tree. @@ -462,11 +463,10 @@ (isReassociableOp(Shl->use_back(), Instruction::Mul) || isReassociableOp(Shl->use_back(), Instruction::Add)))) { Constant *MulCst = ConstantInt::get(Shl->getType(), 1); - MulCst = - ConstantExpr::getShl(MulCst, cast(Shl->getOperand(1))); + MulCst = ConstantExpr::getShl(MulCst, cast(Shl->getOperand(1))); - Instruction *Mul = BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, - "", Shl); + Instruction *Mul = + BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl); ValueRankMap.erase(Shl); Mul->takeName(Shl); Shl->replaceAllUsesWith(Mul); @@ -549,7 +549,92 @@ FindSingleUseMultiplyFactors(BO->getOperand(0), Factors); } +/// OptimizeAndOrXor - Optimize a series of operands to an 'and', 'or', or 'xor' +/// instruction. This optimizes based on identities. If it can be reduced to +/// a single Value, it is returned, otherwise the Ops list is mutated as +/// necessary. +static Value *OptimizeAndOrXor(unsigned Opcode, std::vector &Ops) { + // Scan the operand lists looking for X and ~X pairs, along with X,X pairs. + // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1. + for (unsigned i = 0, e = Ops.size(); i != e; ++i) { + // First, check for X and ~X in the operand list. + assert(i < Ops.size()); + if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^. + Value *X = BinaryOperator::getNotArgument(Ops[i].Op); + unsigned FoundX = FindInOperandList(Ops, i, X); + if (FoundX != i) { + if (Opcode == Instruction::And) { // ...&X&~X = 0 + ++NumAnnihil; + return Constant::getNullValue(X->getType()); + } + + if (Opcode == Instruction::Or) { // ...|X|~X = -1 + ++NumAnnihil; + return Constant::getAllOnesValue(X->getType()); + } + } + } + + // Next, check for duplicate pairs of values, which we assume are next to + // each other, due to our sorting criteria. + assert(i < Ops.size()); + if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) { + if (Opcode == Instruction::And || Opcode == Instruction::Or) { + // Drop duplicate values. + Ops.erase(Ops.begin()+i); + --i; --e; + ++NumAnnihil; + } else { + assert(Opcode == Instruction::Xor); + if (e == 2) { + ++NumAnnihil; + return Constant::getNullValue(Ops[0].Op->getType()); + } + // ... X^X -> ... + Ops.erase(Ops.begin()+i, Ops.begin()+i+2); + i -= 1; e -= 2; + ++NumAnnihil; + } + } + } + return 0; +} +/// OptimizeAdd - Optimize a series of operands to an 'add' instruction. This +/// optimizes based on identities. If it can be reduced to a single Value, it +/// is returned, otherwise the Ops list is mutated as necessary. +Value *Reassociate::OptimizeAdd(std::vector &Ops) { + // Scan the operand lists looking for X and -X pairs. If we find any, we + // can simplify the expression. X+-X == 0. + for (unsigned i = 0, e = Ops.size(); i != e; ++i) { + assert(i < Ops.size()); + // Check for X and -X in the operand list. + if (!BinaryOperator::isNeg(Ops[i].Op)) + continue; + + Value *X = BinaryOperator::getNegArgument(Ops[i].Op); + unsigned FoundX = FindInOperandList(Ops, i, X); + if (FoundX == i) + continue; + + // Remove X and -X from the operand list. + if (Ops.size() == 2) { + ++NumAnnihil; + return Constant::getNullValue(X->getType()); + } + + Ops.erase(Ops.begin()+i); + if (i < FoundX) + --FoundX; + else + --i; // Need to back up an extra one. + Ops.erase(Ops.begin()+FoundX); + ++NumAnnihil; + --i; // Revisit element. + e -= 2; // Removed two elements. + } + return 0; +} Value *Reassociate::OptimizeExpression(BinaryOperator *I, std::vector &Ops) { @@ -608,84 +693,20 @@ default: break; case Instruction::And: case Instruction::Or: - case Instruction::Xor: - // Scan the operand lists looking for X and ~X pairs, along with X,X pairs. - // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1. - for (unsigned i = 0, e = Ops.size(); i != e; ++i) { - // First, check for X and ~X in the operand list. - assert(i < Ops.size()); - if (BinaryOperator::isNot(Ops[i].Op)) { // Cannot occur for ^. - Value *X = BinaryOperator::getNotArgument(Ops[i].Op); - unsigned FoundX = FindInOperandList(Ops, i, X); - if (FoundX != i) { - if (Opcode == Instruction::And) { // ...&X&~X = 0 - ++NumAnnihil; - return Constant::getNullValue(X->getType()); - } - - if (Opcode == Instruction::Or) { // ...|X|~X = -1 - ++NumAnnihil; - return Constant::getAllOnesValue(X->getType()); - } - } - } - - // Next, check for duplicate pairs of values, which we assume are next to - // each other, due to our sorting criteria. - assert(i < Ops.size()); - if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) { - if (Opcode == Instruction::And || Opcode == Instruction::Or) { - // Drop duplicate values. - Ops.erase(Ops.begin()+i); - --i; --e; - IterateOptimization = true; - ++NumAnnihil; - } else { - assert(Opcode == Instruction::Xor); - if (e == 2) { - ++NumAnnihil; - return Constant::getNullValue(Ops[0].Op->getType()); - } - // ... X^X -> ... - Ops.erase(Ops.begin()+i, Ops.begin()+i+2); - i -= 1; e -= 2; - IterateOptimization = true; - ++NumAnnihil; - } - } - } + case Instruction::Xor: { + unsigned NumOps = Ops.size(); + if (Value *Result = OptimizeAndOrXor(Opcode, Ops)) + return Result; + IterateOptimization |= Ops.size() != NumOps; break; + } - case Instruction::Add: - // Scan the operand lists looking for X and -X pairs. If we find any, we - // can simplify the expression. X+-X == 0. - for (unsigned i = 0, e = Ops.size(); i != e; ++i) { - assert(i < Ops.size()); - // Check for X and -X in the operand list. - if (!BinaryOperator::isNeg(Ops[i].Op)) - continue; - - Value *X = BinaryOperator::getNegArgument(Ops[i].Op); - unsigned FoundX = FindInOperandList(Ops, i, X); - if (FoundX == i) - continue; - - // Remove X and -X from the operand list. - if (Ops.size() == 2) { - ++NumAnnihil; - return Constant::getNullValue(X->getType()); - } - Ops.erase(Ops.begin()+i); - if (i < FoundX) - --FoundX; - else - --i; // Need to back up an extra one. - Ops.erase(Ops.begin()+FoundX); - IterateOptimization = true; - ++NumAnnihil; - --i; // Revisit element. - e -= 2; // Removed two elements. - } + case Instruction::Add: { + unsigned NumOps = Ops.size(); + if (Value *Result = OptimizeAdd(Ops)) + return Result; + IterateOptimization |= Ops.size() != NumOps; + } // Scan the operand list, checking to see if there are any common factors // between operands. Consider something like A*A+A*B*C+D. We would like to From sabre at nondot.org Thu Dec 31 02:23:09 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 08:23:09 -0000 Subject: [llvm-commits] [llvm] r92349 - /llvm/trunk/lib/VMCore/AsmWriter.cpp Message-ID: <200912310823.nBV8N93s030694@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 02:23:09 2009 New Revision: 92349 URL: http://llvm.org/viewvc/llvm-project?rev=92349&view=rev Log: fix refactoro Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp Modified: llvm/trunk/lib/VMCore/AsmWriter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/AsmWriter.cpp?rev=92349&r1=92348&r2=92349&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/AsmWriter.cpp (original) +++ llvm/trunk/lib/VMCore/AsmWriter.cpp Thu Dec 31 02:23:09 2009 @@ -2041,7 +2041,7 @@ if (const Instruction *I = dyn_cast(this)) { const Function *F = I->getParent() ? I->getParent()->getParent() : 0; SlotTracker SlotTable(F); - AssemblyWriter W(OS, SlotTable, getModuleFromVal(F), AAW); + AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW); W.printInstruction(*I); } else if (const BasicBlock *BB = dyn_cast(this)) { SlotTracker SlotTable(BB->getParent()); From sabre at nondot.org Thu Dec 31 02:29:56 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 08:29:56 -0000 Subject: [llvm-commits] [llvm] r92352 - in /llvm/trunk/test/Transforms/Reassociate: basictest.ll basictest2.ll basictest3.ll basictest4.ll Message-ID: <200912310829.nBV8TumX030923@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 02:29:56 2009 New Revision: 92352 URL: http://llvm.org/viewvc/llvm-project?rev=92352&view=rev Log: filecheckize Removed: llvm/trunk/test/Transforms/Reassociate/basictest2.ll llvm/trunk/test/Transforms/Reassociate/basictest3.ll llvm/trunk/test/Transforms/Reassociate/basictest4.ll Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest.ll?rev=92352&r1=92351&r2=92352&view=diff ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest.ll Thu Dec 31 02:29:56 2009 @@ -1,10 +1,107 @@ ; With reassociation, constant folding can eliminate the 12 and -12 constants. ; -; RUN: opt < %s -reassociate -constprop -instcombine -die -S | not grep add +; RUN: opt < %s -reassociate -gvn -instcombine -S | FileCheck %s -define i32 @test(i32 %arg) { - %tmp1 = sub i32 -12, %arg ; [#uses=1] - %tmp2 = add i32 %tmp1, 12 ; [#uses=1] +define i32 @test1(i32 %arg) { + %tmp1 = sub i32 -12, %arg + %tmp2 = add i32 %tmp1, 12 ret i32 %tmp2 +; CHECK: @test1 +; CHECK-NEXT: sub i32 0, %arg +; CHECK-NEXT: ret i32 } +define i32 @test2(i32 %reg109, i32 %reg1111) { + %reg115 = add i32 %reg109, -30 ; [#uses=1] + %reg116 = add i32 %reg115, %reg1111 ; [#uses=1] + %reg117 = add i32 %reg116, 30 ; [#uses=1] + ret i32 %reg117 +; CHECK: @test2 +; CHECK-NEXT: add i32 %reg1111, %reg109 +; CHECK-NEXT: ret i32 +} + + at e = external global i32 ; [#uses=3] + at a = external global i32 ; [#uses=3] + at b = external global i32 ; [#uses=3] + at c = external global i32 ; [#uses=3] + at f = external global i32 ; [#uses=3] + +define void @test3() { + %A = load i32* @a ; [#uses=2] + %B = load i32* @b ; [#uses=2] + %C = load i32* @c ; [#uses=2] + %t1 = add i32 %A, %B ; [#uses=1] + %t2 = add i32 %t1, %C ; [#uses=1] + %t3 = add i32 %C, %A ; [#uses=1] + %t4 = add i32 %t3, %B ; [#uses=1] + ; e = (a+b)+c; + store i32 %t2, i32* @e + ; f = (a+c)+b + store i32 %t4, i32* @f + ret void +; CHECK: @test3 +; CHECK: add i32 +; CHECK: add i32 +; CHECK-NOT: add i32 +; CHECK: ret void +} + +define void @test4() { + %A = load i32* @a ; [#uses=2] + %B = load i32* @b ; [#uses=2] + %C = load i32* @c ; [#uses=2] + %t1 = add i32 %A, %B ; [#uses=1] + %t2 = add i32 %t1, %C ; [#uses=1] + %t3 = add i32 %C, %A ; [#uses=1] + %t4 = add i32 %t3, %B ; [#uses=1] + ; e = c+(a+b) + store i32 %t2, i32* @e + ; f = (c+a)+b + store i32 %t4, i32* @f + ret void +; CHECK: @test4 +; CHECK: add i32 +; CHECK: add i32 +; CHECK-NOT: add i32 +; CHECK: ret void +} + +define void @test5() { + %A = load i32* @a ; [#uses=2] + %B = load i32* @b ; [#uses=2] + %C = load i32* @c ; [#uses=2] + %t1 = add i32 %B, %A ; [#uses=1] + %t2 = add i32 %t1, %C ; [#uses=1] + %t3 = add i32 %C, %A ; [#uses=1] + %t4 = add i32 %t3, %B ; [#uses=1] + ; e = c+(b+a) + store i32 %t2, i32* @e + ; f = (c+a)+b + store i32 %t4, i32* @f + ret void +; CHECK: @test5 +; CHECK: add i32 +; CHECK: add i32 +; CHECK-NOT: add i32 +; CHECK: ret void +} + +define i32 @test6() { + %tmp.0 = load i32* @a ; [#uses=2] + %tmp.1 = load i32* @b ; [#uses=2] + ; (a+b) + %tmp.2 = add i32 %tmp.0, %tmp.1 ; [#uses=1] + %tmp.4 = load i32* @c ; [#uses=2] + ; (a+b)+c + %tmp.5 = add i32 %tmp.2, %tmp.4 ; [#uses=1] + ; (a+c) + %tmp.8 = add i32 %tmp.0, %tmp.4 ; [#uses=1] + ; (a+c)+b + %tmp.11 = add i32 %tmp.8, %tmp.1 ; [#uses=1] + ; X ^ X = 0 + %RV = xor i32 %tmp.5, %tmp.11 ; [#uses=1] + ret i32 %RV +; CHECK: @test6 +; CHECK: ret i32 0 +} Removed: llvm/trunk/test/Transforms/Reassociate/basictest2.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest2.ll?rev=92351&view=auto ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest2.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest2.ll (removed) @@ -1,11 +0,0 @@ -; With reassociation, constant folding can eliminate the +/- 30 constants. -; -; RUN: opt < %s -reassociate -constprop -instcombine -die -S | not grep 30 - -define i32 @test(i32 %reg109, i32 %reg1111) { - %reg115 = add i32 %reg109, -30 ; [#uses=1] - %reg116 = add i32 %reg115, %reg1111 ; [#uses=1] - %reg117 = add i32 %reg116, 30 ; [#uses=1] - ret i32 %reg117 -} - Removed: llvm/trunk/test/Transforms/Reassociate/basictest3.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest3.ll?rev=92351&view=auto ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest3.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest3.ll (removed) @@ -1,54 +0,0 @@ -; RUN: opt < %s -reassociate -gvn -S | grep add | count 6 -; Each of these functions should turn into two adds each. - - at e = external global i32 ; [#uses=3] - at a = external global i32 ; [#uses=3] - at b = external global i32 ; [#uses=3] - at c = external global i32 ; [#uses=3] - at f = external global i32 ; [#uses=3] - -define void @test1() { - %A = load i32* @a ; [#uses=2] - %B = load i32* @b ; [#uses=2] - %C = load i32* @c ; [#uses=2] - %t1 = add i32 %A, %B ; [#uses=1] - %t2 = add i32 %t1, %C ; [#uses=1] - %t3 = add i32 %C, %A ; [#uses=1] - %t4 = add i32 %t3, %B ; [#uses=1] - ; e = (a+b)+c; - store i32 %t2, i32* @e - ; f = (a+c)+b - store i32 %t4, i32* @f - ret void -} - -define void @test2() { - %A = load i32* @a ; [#uses=2] - %B = load i32* @b ; [#uses=2] - %C = load i32* @c ; [#uses=2] - %t1 = add i32 %A, %B ; [#uses=1] - %t2 = add i32 %t1, %C ; [#uses=1] - %t3 = add i32 %C, %A ; [#uses=1] - %t4 = add i32 %t3, %B ; [#uses=1] - ; e = c+(a+b) - store i32 %t2, i32* @e - ; f = (c+a)+b - store i32 %t4, i32* @f - ret void -} - -define void @test3() { - %A = load i32* @a ; [#uses=2] - %B = load i32* @b ; [#uses=2] - %C = load i32* @c ; [#uses=2] - %t1 = add i32 %B, %A ; [#uses=1] - %t2 = add i32 %t1, %C ; [#uses=1] - %t3 = add i32 %C, %A ; [#uses=1] - %t4 = add i32 %t3, %B ; [#uses=1] - ; e = c+(b+a) - store i32 %t2, i32* @e - ; f = (c+a)+b - store i32 %t4, i32* @f - ret void -} - Removed: llvm/trunk/test/Transforms/Reassociate/basictest4.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest4.ll?rev=92351&view=auto ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest4.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest4.ll (removed) @@ -1,23 +0,0 @@ -; RUN: opt < %s -reassociate -gvn -instcombine -S | not grep add - - at a = weak global i32 0 ; [#uses=1] - at b = weak global i32 0 ; [#uses=1] - at c = weak global i32 0 ; [#uses=1] - at d = weak global i32 0 ; [#uses=0] - -define i32 @foo() { - %tmp.0 = load i32* @a ; [#uses=2] - %tmp.1 = load i32* @b ; [#uses=2] - ; (a+b) - %tmp.2 = add i32 %tmp.0, %tmp.1 ; [#uses=1] - %tmp.4 = load i32* @c ; [#uses=2] - ; (a+b)+c - %tmp.5 = add i32 %tmp.2, %tmp.4 ; [#uses=1] - ; (a+c) - %tmp.8 = add i32 %tmp.0, %tmp.4 ; [#uses=1] - ; (a+c)+b - %tmp.11 = add i32 %tmp.8, %tmp.1 ; [#uses=1] - ; X ^ X = 0 - %RV = xor i32 %tmp.5, %tmp.11 ; [#uses=1] - ret i32 %RV -} From sabre at nondot.org Thu Dec 31 02:32:22 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 08:32:22 -0000 Subject: [llvm-commits] [llvm] r92353 - in /llvm/trunk/test/Transforms/Reassociate: basictest.ll mul-factor3.ll mul-neg-add.ll Message-ID: <200912310832.nBV8WMfc031152@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 02:32:22 2009 New Revision: 92353 URL: http://llvm.org/viewvc/llvm-project?rev=92353&view=rev Log: merge some more tests in. Removed: llvm/trunk/test/Transforms/Reassociate/mul-factor3.ll llvm/trunk/test/Transforms/Reassociate/mul-neg-add.ll Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest.ll?rev=92353&r1=92352&r2=92353&view=diff ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest.ll Thu Dec 31 02:32:22 2009 @@ -105,3 +105,31 @@ ; CHECK: @test6 ; CHECK: ret i32 0 } + +; This should be one add and two multiplies. +define i32 @test7(i32 %A, i32 %B, i32 %C) { + %aa = mul i32 %A, %A + %aab = mul i32 %aa, %B + %ac = mul i32 %A, %C + %aac = mul i32 %ac, %A + %r = add i32 %aab, %aac + ret i32 %r +; CHECK: @test7 +; CHECK-NEXT: add i32 %C, %B +; CHECK-NEXT: mul i32 +; CHECK-NEXT: mul i32 +; CHECK-NEXT: ret i32 +} + + +define i32 @test8(i32 %X, i32 %Y, i32 %Z) { + %A = sub i32 0, %X + %B = mul i32 %A, %Y + ; (-X)*Y + Z -> Z-X*Y + %C = add i32 %B, %Z + ret i32 %C +; CHECK: @test8 +; CHECK-NEXT: %A = mul i32 %Y, %X +; CHECK-NEXT: %C = sub i32 %Z, %A +; CHECK-NEXT: ret i32 %C +} Removed: llvm/trunk/test/Transforms/Reassociate/mul-factor3.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/mul-factor3.ll?rev=92352&view=auto ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/mul-factor3.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/mul-factor3.ll (removed) @@ -1,15 +0,0 @@ -; This should be one add and two multiplies. - -; RUN: opt < %s -reassociate -instcombine -S > %t -; RUN: grep mul %t | count 2 -; RUN: grep add %t | count 1 - -define i32 @test(i32 %A, i32 %B, i32 %C) { - %aa = mul i32 %A, %A ; [#uses=1] - %aab = mul i32 %aa, %B ; [#uses=1] - %ac = mul i32 %A, %C ; [#uses=1] - %aac = mul i32 %ac, %A ; [#uses=1] - %r = add i32 %aab, %aac ; [#uses=1] - ret i32 %r -} - Removed: llvm/trunk/test/Transforms/Reassociate/mul-neg-add.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/mul-neg-add.ll?rev=92352&view=auto ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/mul-neg-add.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/mul-neg-add.ll (removed) @@ -1,10 +0,0 @@ -; RUN: opt < %s -reassociate -instcombine -S |\ -; RUN: not grep {sub i32 0} - -define i32 @test(i32 %X, i32 %Y, i32 %Z) { - %A = sub i32 0, %X ; [#uses=1] - %B = mul i32 %A, %Y ; [#uses=1] - ; (-X)*Y + Z -> Z-X*Y - %C = add i32 %B, %Z ; [#uses=1] - ret i32 %C -} From sabre at nondot.org Thu Dec 31 02:33:49 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 08:33:49 -0000 Subject: [llvm-commits] [llvm] r92354 - in /llvm/trunk: lib/Transforms/Scalar/Reassociate.cpp test/Transforms/Reassociate/basictest.ll Message-ID: <200912310833.nBV8XnH2031199@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 02:33:49 2009 New Revision: 92354 URL: http://llvm.org/viewvc/llvm-project?rev=92354&view=rev Log: simple fix for an incorrect factoring which causes a miscompilation, PR5458. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp llvm/trunk/test/Transforms/Reassociate/basictest.ll Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92354&r1=92353&r2=92354&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 02:33:49 2009 @@ -714,6 +714,10 @@ // To efficiently find this, we count the number of times a factor occurs // for any ADD operands that are MULs. DenseMap FactorOccurrences; + + // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4) + // where they are actually the same multiply. + SmallPtrSet Multiplies; unsigned MaxOcc = 0; Value *MaxOccVal = 0; for (unsigned i = 0, e = Ops.size(); i != e; ++i) { @@ -721,6 +725,9 @@ if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty()) continue; + // If we've already seen this multiply, don't revisit it. + if (!Multiplies.insert(BOp)) continue; + // Compute all of the factors of this added value. SmallVector Factors; FindSingleUseMultiplyFactors(BOp, Factors); Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest.ll?rev=92354&r1=92353&r2=92354&view=diff ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest.ll Thu Dec 31 02:33:49 2009 @@ -133,3 +133,14 @@ ; CHECK-NEXT: %C = sub i32 %Z, %A ; CHECK-NEXT: ret i32 %C } + + +; PR5458 +define i32 @test9(i32 %X) { + %Y = mul i32 %X, 47 + %Z = add i32 %Y, %Y + ret i32 %Z +; CHECK: @test9 +; CHECK-NEXT: %Z = mul i32 %X, 94 +; CHECK-NEXT: ret i32 %Z +} From benny.kra at googlemail.com Thu Dec 31 10:27:14 2009 From: benny.kra at googlemail.com (Benjamin Kramer) Date: Thu, 31 Dec 2009 16:27:14 -0000 Subject: [llvm-commits] [llvm] r92359 - /llvm/trunk/unittests/ADT/StringRefTest.cpp Message-ID: <200912311627.nBVGREQF029361@zion.cs.uiuc.edu> Author: d0k Date: Thu Dec 31 10:27:13 2009 New Revision: 92359 URL: http://llvm.org/viewvc/llvm-project?rev=92359&view=rev Log: Silence compiler warning. warning: comparison between signed and unsigned integer expressions Modified: llvm/trunk/unittests/ADT/StringRefTest.cpp Modified: llvm/trunk/unittests/ADT/StringRefTest.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/unittests/ADT/StringRefTest.cpp?rev=92359&r1=92358&r2=92359&view=diff ============================================================================== --- llvm/trunk/unittests/ADT/StringRefTest.cpp (original) +++ llvm/trunk/unittests/ADT/StringRefTest.cpp Thu Dec 31 10:27:13 2009 @@ -249,7 +249,7 @@ TEST(StringRefTest, EditDistance) { StringRef Str("hello"); - EXPECT_EQ(2, Str.edit_distance("hill")); + EXPECT_EQ(2U, Str.edit_distance("hill")); } TEST(StringRefTest, Misc) { From dgregor at apple.com Thu Dec 31 11:04:59 2009 From: dgregor at apple.com (Douglas Gregor) Date: Thu, 31 Dec 2009 12:04:59 -0500 Subject: [llvm-commits] [llvm] r92309 - in /llvm/trunk: include/llvm/ADT/StringRef.h lib/Support/StringRef.cpp In-Reply-To: <6a8523d60912301144q691738ccxbda79dd0dd95d569@mail.gmail.com> References: <200912301723.nBUHNiO4000671@zion.cs.uiuc.edu> <6a8523d60912301144q691738ccxbda79dd0dd95d569@mail.gmail.com> Message-ID: <9EE066DA-86EB-4219-A187-2D4A340E04CD@apple.com> Sent from my iPhone On Dec 30, 2009, at 2:44 PM, Daniel Dunbar wrote: > On Wed, Dec 30, 2009 at 9:23 AM, Douglas Gregor > wrote: >> Author: dgregor >> Date: Wed Dec 30 11:23:44 2009 >> New Revision: 92309 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=92309&view=rev >> Log: >> Implement edit distance for StringRef > > Nice! Can this use SmallVector instead of vector, and get a unittest? Done, thanks! > - Daniel > >> Modified: >> llvm/trunk/include/llvm/ADT/StringRef.h >> llvm/trunk/lib/Support/StringRef.cpp >> >> Modified: llvm/trunk/include/llvm/ADT/StringRef.h >> URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/ADT/StringRef.h?rev=92309&r1=92308&r2=92309&view=diff >> >> === >> === >> === >> ===================================================================== >> --- llvm/trunk/include/llvm/ADT/StringRef.h (original) >> +++ llvm/trunk/include/llvm/ADT/StringRef.h Wed Dec 30 11:23:44 2009 >> @@ -133,6 +133,22 @@ >> /// compare_lower - Compare two strings, ignoring case. >> int compare_lower(StringRef RHS) const; >> >> + /// \brief Determine the edit distance between this string and >> another >> + /// string. >> + /// >> + /// \param Other the string to compare this string against. >> + /// >> + /// \param AllowReplacements whether to allow character >> + /// replacements (change one character into another) as a single >> + /// operation, rather than as two operations (an insertion and a >> + /// removal). >> + /// >> + /// \returns the minimum number of character insertions, >> removals, >> + /// or (if \p AllowReplacements is \c true) replacements >> needed to >> + /// transform one of the given strings into the other. If zero, >> + /// the strings are identical. >> + unsigned edit_distance(StringRef Other, bool AllowReplacements >> = true); >> + >> /// str - Get the contents as an std::string. >> std::string str() const { return std::string(Data, Length); } >> >> >> Modified: llvm/trunk/lib/Support/StringRef.cpp >> URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Support/StringRef.cpp?rev=92309&r1=92308&r2=92309&view=diff >> >> === >> === >> === >> ===================================================================== >> --- llvm/trunk/lib/Support/StringRef.cpp (original) >> +++ llvm/trunk/lib/Support/StringRef.cpp Wed Dec 30 11:23:44 2009 >> @@ -8,6 +8,7 @@ >> // >> === >> --- >> ------------------------------------------------------------------- >> ===// >> >> #include "llvm/ADT/StringRef.h" >> +#include >> using namespace llvm; >> >> // MSVC emits references to this into the translation units which >> reference it. >> @@ -35,6 +36,36 @@ >> return Length < RHS.Length ? -1 : 1; >> } >> >> +/// \brief Compute the edit distance between the two given strings. >> +unsigned StringRef::edit_distance(llvm::StringRef Other, >> + bool AllowReplacements) { >> + size_type m = size(); >> + size_type n = Other.size(); >> + >> + std::vector previous(n+1, 0); >> + for (std::vector::size_type i = 0; i <= n; ++i) >> + previous[i] = i; >> + >> + std::vector current(n+1, 0); >> + for (size_type y = 1; y <= m; ++y) { >> + current.assign(n+1, 0); >> + current[0] = y; >> + for (size_type x = 1; x <= n; ++x) { >> + if (AllowReplacements) { >> + current[x] = min(previous[x-1] + ((*this)[y-1] == Other >> [x-1]? 0u:1u), >> + min(current[x-1], previous[x])+1); >> + } >> + else { >> + if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1]; >> + else current[x] = min(current[x-1], previous[x]) + 1; >> + } >> + } >> + current.swap(previous); >> + } >> + >> + return previous[n]; >> +} >> + >> // >> === >> --- >> ------------------------------------------------------------------- >> ===// >> // String Searching >> // >> === >> --- >> ------------------------------------------------------------------- >> ===// >> >> >> _______________________________________________ >> llvm-commits mailing list >> llvm-commits at cs.uiuc.edu >> http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits >> From sabre at nondot.org Thu Dec 31 11:51:05 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 17:51:05 -0000 Subject: [llvm-commits] [llvm] r92362 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912311751.nBVHp5W1032086@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 11:51:05 2009 New Revision: 92362 URL: http://llvm.org/viewvc/llvm-project?rev=92362&view=rev Log: factor statistic updating better. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92362&r1=92361&r2=92362&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 11:51:05 2009 @@ -563,15 +563,11 @@ Value *X = BinaryOperator::getNotArgument(Ops[i].Op); unsigned FoundX = FindInOperandList(Ops, i, X); if (FoundX != i) { - if (Opcode == Instruction::And) { // ...&X&~X = 0 - ++NumAnnihil; + if (Opcode == Instruction::And) // ...&X&~X = 0 return Constant::getNullValue(X->getType()); - } - if (Opcode == Instruction::Or) { // ...|X|~X = -1 - ++NumAnnihil; + if (Opcode == Instruction::Or) // ...|X|~X = -1 return Constant::getAllOnesValue(X->getType()); - } } } @@ -586,10 +582,9 @@ ++NumAnnihil; } else { assert(Opcode == Instruction::Xor); - if (e == 2) { - ++NumAnnihil; + if (e == 2) return Constant::getNullValue(Ops[0].Op->getType()); - } + // ... X^X -> ... Ops.erase(Ops.begin()+i, Ops.begin()+i+2); i -= 1; e -= 2; @@ -618,10 +613,8 @@ continue; // Remove X and -X from the operand list. - if (Ops.size() == 2) { - ++NumAnnihil; + if (Ops.size() == 2) return Constant::getNullValue(X->getType()); - } Ops.erase(Ops.begin()+i); if (i < FoundX) @@ -657,11 +650,9 @@ switch (Opcode) { default: break; case Instruction::And: - if (CstVal->isZero()) { // ... & 0 -> 0 - ++NumAnnihil; + if (CstVal->isZero()) // ... & 0 -> 0 return CstVal; - } - if (CstVal->isAllOnesValue()) // ... & -1 -> ... + if (CstVal->isAllOnesValue()) // ... & -1 -> ... Ops.pop_back(); break; case Instruction::Mul: @@ -674,10 +665,8 @@ Ops.pop_back(); // ... * 1 -> ... break; case Instruction::Or: - if (CstVal->isAllOnesValue()) { // ... | -1 -> -1 - ++NumAnnihil; + if (CstVal->isAllOnesValue()) // ... | -1 -> -1 return CstVal; - } // FALLTHROUGH! case Instruction::Add: case Instruction::Xor: @@ -883,6 +872,7 @@ DEBUG(errs() << "Reassoc to scalar: " << *V << "\n"); I->replaceAllUsesWith(V); RemoveDeadBinaryOp(I); + ++NumAnnihil; return; } From sabre at nondot.org Thu Dec 31 12:17:13 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 18:17:13 -0000 Subject: [llvm-commits] [llvm] r92363 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912311817.nBVIHDej000387@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 12:17:13 2009 New Revision: 92363 URL: http://llvm.org/viewvc/llvm-project?rev=92363&view=rev Log: move the rest of the add optimization code out to OptimizeAdd, improve some comments, simplify a bit of code. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92363&r1=92362&r2=92363&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 12:17:13 2009 @@ -92,7 +92,7 @@ void RewriteExprTree(BinaryOperator *I, std::vector &Ops, unsigned Idx = 0); Value *OptimizeExpression(BinaryOperator *I, std::vector &Ops); - Value *OptimizeAdd(std::vector &Ops); + Value *OptimizeAdd(Instruction *I, std::vector &Ops); void LinearizeExprTree(BinaryOperator *I, std::vector &Ops); void LinearizeExpr(BinaryOperator *I); Value *RemoveFactorFromExpression(Value *V, Value *Factor); @@ -598,7 +598,7 @@ /// OptimizeAdd - Optimize a series of operands to an 'add' instruction. This /// optimizes based on identities. If it can be reduced to a single Value, it /// is returned, otherwise the Ops list is mutated as necessary. -Value *Reassociate::OptimizeAdd(std::vector &Ops) { +Value *Reassociate::OptimizeAdd(Instruction *I, std::vector &Ops) { // Scan the operand lists looking for X and -X pairs. If we find any, we // can simplify the expression. X+-X == 0. for (unsigned i = 0, e = Ops.size(); i != e; ++i) { @@ -626,6 +626,94 @@ --i; // Revisit element. e -= 2; // Removed two elements. } + + // Scan the operand list, checking to see if there are any common factors + // between operands. Consider something like A*A+A*B*C+D. We would like to + // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies. + // To efficiently find this, we count the number of times a factor occurs + // for any ADD operands that are MULs. + DenseMap FactorOccurrences; + + // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4) + // where they are actually the same multiply. + SmallPtrSet Multiplies; + unsigned MaxOcc = 0; + Value *MaxOccVal = 0; + for (unsigned i = 0, e = Ops.size(); i != e; ++i) { + BinaryOperator *BOp = dyn_cast(Ops[i].Op); + if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty()) + continue; + + // If we've already seen this multiply, don't revisit it. + if (!Multiplies.insert(BOp)) continue; + + // Compute all of the factors of this added value. + SmallVector Factors; + FindSingleUseMultiplyFactors(BOp, Factors); + assert(Factors.size() > 1 && "Bad linearize!"); + + // Add one to FactorOccurrences for each unique factor in this op. + if (Factors.size() == 2) { + unsigned Occ = ++FactorOccurrences[Factors[0]]; + if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[0]; } + if (Factors[0] != Factors[1]) { // Don't double count A*A. + Occ = ++FactorOccurrences[Factors[1]]; + if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[1]; } + } + } else { + SmallPtrSet Duplicates; + for (unsigned i = 0, e = Factors.size(); i != e; ++i) { + if (!Duplicates.insert(Factors[i])) continue; + + unsigned Occ = ++FactorOccurrences[Factors[i]]; + if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[i]; } + } + } + } + + // If any factor occurred more than one time, we can pull it out. + if (MaxOcc > 1) { + DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << "\n"); + ++NumFactor; + + // Create a new instruction that uses the MaxOccVal twice. If we don't do + // this, we could otherwise run into situations where removing a factor + // from an expression will drop a use of maxocc, and this can cause + // RemoveFactorFromExpression on successive values to behave differently. + Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal); + SmallVector NewMulOps; + for (unsigned i = 0, e = Ops.size(); i != e; ++i) { + if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) { + NewMulOps.push_back(V); + Ops.erase(Ops.begin()+i); + --i; --e; + } + } + + // No need for extra uses anymore. + delete DummyInst; + + unsigned NumAddedValues = NewMulOps.size(); + Value *V = EmitAddTreeOfValues(I, NewMulOps); + Value *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I); + + // Now that we have inserted V and its sole use, optimize it. This allows + // us to handle cases that require multiple factoring steps, such as this: + // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C)) + if (NumAddedValues > 1) + ReassociateExpression(cast(V)); + + // If every add operand included the factor (e.g. "A*B + A*C"), then the + // entire result expression is just the multiply "A*(B+C)". + if (Ops.empty()) + return V2; + + // Otherwise, we had some input that didn't have the fact, such as + // "A*B + A*C + D" -> "A*(B+C) + D". Add the new multiply to the list of + // things being added. + Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2)); + } + return 0; } @@ -692,98 +780,11 @@ case Instruction::Add: { unsigned NumOps = Ops.size(); - if (Value *Result = OptimizeAdd(Ops)) + if (Value *Result = OptimizeAdd(I, Ops)) return Result; IterateOptimization |= Ops.size() != NumOps; } - // Scan the operand list, checking to see if there are any common factors - // between operands. Consider something like A*A+A*B*C+D. We would like to - // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies. - // To efficiently find this, we count the number of times a factor occurs - // for any ADD operands that are MULs. - DenseMap FactorOccurrences; - - // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4) - // where they are actually the same multiply. - SmallPtrSet Multiplies; - unsigned MaxOcc = 0; - Value *MaxOccVal = 0; - for (unsigned i = 0, e = Ops.size(); i != e; ++i) { - BinaryOperator *BOp = dyn_cast(Ops[i].Op); - if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty()) - continue; - - // If we've already seen this multiply, don't revisit it. - if (!Multiplies.insert(BOp)) continue; - - // Compute all of the factors of this added value. - SmallVector Factors; - FindSingleUseMultiplyFactors(BOp, Factors); - assert(Factors.size() > 1 && "Bad linearize!"); - - // Add one to FactorOccurrences for each unique factor in this op. - if (Factors.size() == 2) { - unsigned Occ = ++FactorOccurrences[Factors[0]]; - if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[0]; } - if (Factors[0] != Factors[1]) { // Don't double count A*A. - Occ = ++FactorOccurrences[Factors[1]]; - if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[1]; } - } - } else { - SmallPtrSet Duplicates; - for (unsigned i = 0, e = Factors.size(); i != e; ++i) { - if (!Duplicates.insert(Factors[i])) continue; - - unsigned Occ = ++FactorOccurrences[Factors[i]]; - if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[i]; } - } - } - } - - // If any factor occurred more than one time, we can pull it out. - if (MaxOcc > 1) { - DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << "\n"); - - // Create a new instruction that uses the MaxOccVal twice. If we don't do - // this, we could otherwise run into situations where removing a factor - // from an expression will drop a use of maxocc, and this can cause - // RemoveFactorFromExpression on successive values to behave differently. - Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal); - SmallVector NewMulOps; - for (unsigned i = 0, e = Ops.size(); i != e; ++i) { - if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) { - NewMulOps.push_back(V); - Ops.erase(Ops.begin()+i); - --i; --e; - } - } - - // No need for extra uses anymore. - delete DummyInst; - - unsigned NumAddedValues = NewMulOps.size(); - Value *V = EmitAddTreeOfValues(I, NewMulOps); - Value *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I); - - // Now that we have inserted V and its sole use, optimize it. This allows - // us to handle cases that require multiple factoring steps, such as this: - // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C)) - if (NumAddedValues > 1) - ReassociateExpression(cast(V)); - - ++NumFactor; - - if (Ops.empty()) - return V2; - - // Add the new value to the list of things being added. - Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2)); - - // Rewrite the tree so that there is now a use of V. - RewriteExprTree(I, Ops); - return OptimizeExpression(I, Ops); - } break; //case Instruction::Mul: } @@ -854,7 +855,7 @@ std::vector Ops; LinearizeExprTree(I, Ops); - DEBUG(errs() << "RAIn:\t"; PrintOps(I, Ops); errs() << "\n"); + DEBUG(errs() << "RAIn:\t"; PrintOps(I, Ops); errs() << '\n'); // Now that we have linearized the tree to a list and have gathered all of // the operands and their ranks, sort the operands by their rank. Use a @@ -869,7 +870,7 @@ if (Value *V = OptimizeExpression(I, Ops)) { // This expression tree simplified to something that isn't a tree, // eliminate it. - DEBUG(errs() << "Reassoc to scalar: " << *V << "\n"); + DEBUG(errs() << "Reassoc to scalar: " << *V << '\n'); I->replaceAllUsesWith(V); RemoveDeadBinaryOp(I); ++NumAnnihil; @@ -888,7 +889,7 @@ Ops.pop_back(); } - DEBUG(errs() << "RAOut:\t"; PrintOps(I, Ops); errs() << "\n"); + DEBUG(errs() << "RAOut:\t"; PrintOps(I, Ops); errs() << '\n'); if (Ops.size() == 1) { // This expression tree simplified to something that isn't a tree, From sabre at nondot.org Thu Dec 31 12:18:46 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 18:18:46 -0000 Subject: [llvm-commits] [llvm] r92364 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912311818.nBVIIkSG000443@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 12:18:46 2009 New Revision: 92364 URL: http://llvm.org/viewvc/llvm-project?rev=92364&view=rev Log: change an if to an assert, fix comment. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92364&r1=92363&r2=92364&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 12:18:46 2009 @@ -700,17 +700,17 @@ // Now that we have inserted V and its sole use, optimize it. This allows // us to handle cases that require multiple factoring steps, such as this: // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C)) - if (NumAddedValues > 1) - ReassociateExpression(cast(V)); + assert(NumAddedValues > 1 && "Each occurrence should contribute a value"); + ReassociateExpression(cast(V)); // If every add operand included the factor (e.g. "A*B + A*C"), then the // entire result expression is just the multiply "A*(B+C)". if (Ops.empty()) return V2; - // Otherwise, we had some input that didn't have the fact, such as + // Otherwise, we had some input that didn't have the factor, such as // "A*B + A*C + D" -> "A*(B+C) + D". Add the new multiply to the list of - // things being added. + // things being added by this operation. Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2)); } From sabre at nondot.org Thu Dec 31 12:40:32 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 18:40:32 -0000 Subject: [llvm-commits] [llvm] r92366 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912311840.nBVIeWQg001321@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 12:40:32 2009 New Revision: 92366 URL: http://llvm.org/viewvc/llvm-project?rev=92366&view=rev Log: change reassociate to use SmallVector for its key datastructures instead of std::vector. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92366&r1=92365&r2=92366&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 12:40:32 2009 @@ -59,7 +59,7 @@ #ifndef NDEBUG /// PrintOps - Print out the expression identified in the Ops list. /// -static void PrintOps(Instruction *I, const std::vector &Ops) { +static void PrintOps(Instruction *I, const SmallVectorImpl &Ops) { Module *M = I->getParent()->getParent()->getParent(); errs() << Instruction::getOpcodeName(I->getOpcode()) << " " << *Ops[0].Op->getType() << '\t'; @@ -89,11 +89,12 @@ void BuildRankMap(Function &F); unsigned getRank(Value *V); void ReassociateExpression(BinaryOperator *I); - void RewriteExprTree(BinaryOperator *I, std::vector &Ops, + void RewriteExprTree(BinaryOperator *I, SmallVectorImpl &Ops, unsigned Idx = 0); - Value *OptimizeExpression(BinaryOperator *I, std::vector &Ops); - Value *OptimizeAdd(Instruction *I, std::vector &Ops); - void LinearizeExprTree(BinaryOperator *I, std::vector &Ops); + Value *OptimizeExpression(BinaryOperator *I, + SmallVectorImpl &Ops); + Value *OptimizeAdd(Instruction *I, SmallVectorImpl &Ops); + void LinearizeExprTree(BinaryOperator *I, SmallVectorImpl &Ops); void LinearizeExpr(BinaryOperator *I); Value *RemoveFactorFromExpression(Value *V, Value *Factor); void ReassociateBB(BasicBlock *BB); @@ -253,7 +254,7 @@ /// caller MUST use something like RewriteExprTree to put the values back in. /// void Reassociate::LinearizeExprTree(BinaryOperator *I, - std::vector &Ops) { + SmallVectorImpl &Ops) { Value *LHS = I->getOperand(0), *RHS = I->getOperand(1); unsigned Opcode = I->getOpcode(); @@ -325,7 +326,7 @@ // linearized and optimized, emit them in-order. This function is written to be // tail recursive. void Reassociate::RewriteExprTree(BinaryOperator *I, - std::vector &Ops, + SmallVectorImpl &Ops, unsigned i) { if (i+2 == Ops.size()) { if (I->getOperand(0) != Ops[i].Op || @@ -478,7 +479,7 @@ // Scan backwards and forwards among values with the same rank as element i to // see if X exists. If X does not exist, return i. -static unsigned FindInOperandList(std::vector &Ops, unsigned i, +static unsigned FindInOperandList(SmallVectorImpl &Ops, unsigned i, Value *X) { unsigned XRank = Ops[i].Rank; unsigned e = Ops.size(); @@ -510,7 +511,7 @@ BinaryOperator *BO = isReassociableOp(V, Instruction::Mul); if (!BO) return 0; - std::vector Factors; + SmallVector Factors; LinearizeExprTree(BO, Factors); bool FoundFactor = false; @@ -553,7 +554,8 @@ /// instruction. This optimizes based on identities. If it can be reduced to /// a single Value, it is returned, otherwise the Ops list is mutated as /// necessary. -static Value *OptimizeAndOrXor(unsigned Opcode, std::vector &Ops) { +static Value *OptimizeAndOrXor(unsigned Opcode, + SmallVectorImpl &Ops) { // Scan the operand lists looking for X and ~X pairs, along with X,X pairs. // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1. for (unsigned i = 0, e = Ops.size(); i != e; ++i) { @@ -598,7 +600,8 @@ /// OptimizeAdd - Optimize a series of operands to an 'add' instruction. This /// optimizes based on identities. If it can be reduced to a single Value, it /// is returned, otherwise the Ops list is mutated as necessary. -Value *Reassociate::OptimizeAdd(Instruction *I, std::vector &Ops) { +Value *Reassociate::OptimizeAdd(Instruction *I, + SmallVectorImpl &Ops) { // Scan the operand lists looking for X and -X pairs. If we find any, we // can simplify the expression. X+-X == 0. for (unsigned i = 0, e = Ops.size(); i != e; ++i) { @@ -718,7 +721,7 @@ } Value *Reassociate::OptimizeExpression(BinaryOperator *I, - std::vector &Ops) { + SmallVectorImpl &Ops) { // Now that we have the linearized expression tree, try to optimize it. // Start by folding any constants that we found. bool IterateOptimization = false; @@ -852,7 +855,7 @@ void Reassociate::ReassociateExpression(BinaryOperator *I) { // First, walk the expression tree, linearizing the tree, collecting - std::vector Ops; + SmallVector Ops; LinearizeExprTree(I, Ops); DEBUG(errs() << "RAIn:\t"; PrintOps(I, Ops); errs() << '\n'); @@ -885,8 +888,8 @@ cast(I->use_back())->getOpcode() == Instruction::Add && isa(Ops.back().Op) && cast(Ops.back().Op)->isAllOnesValue()) { - Ops.insert(Ops.begin(), Ops.back()); - Ops.pop_back(); + ValueEntry Tmp = Ops.pop_back_val(); + Ops.insert(Ops.begin(), Tmp); } DEBUG(errs() << "RAOut:\t"; PrintOps(I, Ops); errs() << '\n'); From sabre at nondot.org Thu Dec 31 13:24:53 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 19:24:53 -0000 Subject: [llvm-commits] [llvm] r92368 - in /llvm/trunk: lib/Transforms/Scalar/Reassociate.cpp test/Transforms/Reassociate/basictest.ll Message-ID: <200912311924.nBVJOroo002884@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 13:24:52 2009 New Revision: 92368 URL: http://llvm.org/viewvc/llvm-project?rev=92368&view=rev Log: teach reassociate to factor x+x+x -> x*3. While I'm at it, fix RemoveDeadBinaryOp to actually do something. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp llvm/trunk/test/Transforms/Reassociate/basictest.ll Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92368&r1=92367&r2=92368&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 13:24:52 2009 @@ -88,7 +88,7 @@ private: void BuildRankMap(Function &F); unsigned getRank(Value *V); - void ReassociateExpression(BinaryOperator *I); + Value *ReassociateExpression(BinaryOperator *I); void RewriteExprTree(BinaryOperator *I, SmallVectorImpl &Ops, unsigned Idx = 0); Value *OptimizeExpression(BinaryOperator *I, @@ -111,10 +111,13 @@ void Reassociate::RemoveDeadBinaryOp(Value *V) { Instruction *Op = dyn_cast(V); - if (!Op || !isa(Op) || !isa(Op) || !Op->use_empty()) + if (!Op || !isa(Op) || !Op->use_empty()) return; Value *LHS = Op->getOperand(0), *RHS = Op->getOperand(1); + + ValueRankMap.erase(Op); + Op->eraseFromParent(); RemoveDeadBinaryOp(LHS); RemoveDeadBinaryOp(RHS); } @@ -602,15 +605,57 @@ /// is returned, otherwise the Ops list is mutated as necessary. Value *Reassociate::OptimizeAdd(Instruction *I, SmallVectorImpl &Ops) { + SmallPtrSet OperandsSeen; + +Restart: + OperandsSeen.clear(); + // Scan the operand lists looking for X and -X pairs. If we find any, we - // can simplify the expression. X+-X == 0. + // can simplify the expression. X+-X == 0. While we're at it, scan for any + // duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z. for (unsigned i = 0, e = Ops.size(); i != e; ++i) { - assert(i < Ops.size()); + Value *TheOp = Ops[i].Op; + // Check to see if we've seen this operand before. If so, we factor all + // instances of the operand together. + if (!OperandsSeen.insert(TheOp)) { + // Rescan the list, removing all instances of this operand from the expr. + unsigned NumFound = 0; + for (unsigned j = 0, je = Ops.size(); j != je; ++j) { + if (Ops[j].Op != TheOp) continue; + ++NumFound; + Ops.erase(Ops.begin()+j); + --j; --je; + } + + /*DEBUG*/(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n'); + ++NumFactor; + + + // Insert a new multiply. + Value *Mul = ConstantInt::get(cast(I->getType()), NumFound); + Mul = BinaryOperator::CreateMul(TheOp, Mul, "factor", I); + + // Now that we have inserted a multiply, optimize it. This allows us to + // handle cases that require multiple factoring steps, such as this: + // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6 + Mul = ReassociateExpression(cast(Mul)); + + // If every add operand was a duplicate, return the multiply. + if (Ops.empty()) + return Mul; + + // Otherwise, we had some input that didn't have the dupe, such as + // "A + A + B" -> "A*2 + B". Add the new multiply to the list of + // things being added by this operation. + Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul)); + goto Restart; + } + // Check for X and -X in the operand list. - if (!BinaryOperator::isNeg(Ops[i].Op)) + if (!BinaryOperator::isNeg(TheOp)) continue; - Value *X = BinaryOperator::getNegArgument(Ops[i].Op); + Value *X = BinaryOperator::getNegArgument(TheOp); unsigned FoundX = FindInOperandList(Ops, i, X); if (FoundX == i) continue; @@ -639,7 +684,6 @@ // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4) // where they are actually the same multiply. - SmallPtrSet Multiplies; unsigned MaxOcc = 0; Value *MaxOccVal = 0; for (unsigned i = 0, e = Ops.size(); i != e; ++i) { @@ -647,9 +691,6 @@ if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty()) continue; - // If we've already seen this multiply, don't revisit it. - if (!Multiplies.insert(BOp)) continue; - // Compute all of the factors of this added value. SmallVector Factors; FindSingleUseMultiplyFactors(BOp, Factors); @@ -676,7 +717,7 @@ // If any factor occurred more than one time, we can pull it out. if (MaxOcc > 1) { - DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << "\n"); + DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n'); ++NumFactor; // Create a new instruction that uses the MaxOccVal twice. If we don't do @@ -698,13 +739,17 @@ unsigned NumAddedValues = NewMulOps.size(); Value *V = EmitAddTreeOfValues(I, NewMulOps); - Value *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I); - // Now that we have inserted V and its sole use, optimize it. This allows - // us to handle cases that require multiple factoring steps, such as this: + // Now that we have inserted the add tree, optimize it. This allows us to + // handle cases that require multiple factoring steps, such as this: // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C)) assert(NumAddedValues > 1 && "Each occurrence should contribute a value"); - ReassociateExpression(cast(V)); + V = ReassociateExpression(cast(V)); + + // Create the multiply. + Value *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I); + + // FIXME: Should rerun 'ReassociateExpression' on the mul too?? // If every add operand included the factor (e.g. "A*B + A*C"), then the // entire result expression is just the multiply "A*(B+C)". @@ -852,9 +897,10 @@ } } -void Reassociate::ReassociateExpression(BinaryOperator *I) { +Value *Reassociate::ReassociateExpression(BinaryOperator *I) { - // First, walk the expression tree, linearizing the tree, collecting + // First, walk the expression tree, linearizing the tree, collecting the + // operand information. SmallVector Ops; LinearizeExprTree(I, Ops); @@ -877,7 +923,7 @@ I->replaceAllUsesWith(V); RemoveDeadBinaryOp(I); ++NumAnnihil; - return; + return V; } // We want to sink immediates as deeply as possible except in the case where @@ -899,11 +945,13 @@ // eliminate it. I->replaceAllUsesWith(Ops[0].Op); RemoveDeadBinaryOp(I); - } else { - // Now that we ordered and optimized the expressions, splat them back into - // the expression tree, removing any unneeded nodes. - RewriteExprTree(I, Ops); + return Ops[0].Op; } + + // Now that we ordered and optimized the expressions, splat them back into + // the expression tree, removing any unneeded nodes. + RewriteExprTree(I, Ops); + return I; } Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest.ll?rev=92368&r1=92367&r2=92368&view=diff ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest.ll Thu Dec 31 13:24:52 2009 @@ -88,19 +88,19 @@ } define i32 @test6() { - %tmp.0 = load i32* @a ; [#uses=2] - %tmp.1 = load i32* @b ; [#uses=2] + %tmp.0 = load i32* @a + %tmp.1 = load i32* @b ; (a+b) - %tmp.2 = add i32 %tmp.0, %tmp.1 ; [#uses=1] - %tmp.4 = load i32* @c ; [#uses=2] + %tmp.2 = add i32 %tmp.0, %tmp.1 + %tmp.4 = load i32* @c ; (a+b)+c - %tmp.5 = add i32 %tmp.2, %tmp.4 ; [#uses=1] + %tmp.5 = add i32 %tmp.2, %tmp.4 ; (a+c) - %tmp.8 = add i32 %tmp.0, %tmp.4 ; [#uses=1] + %tmp.8 = add i32 %tmp.0, %tmp.4 ; (a+c)+b - %tmp.11 = add i32 %tmp.8, %tmp.1 ; [#uses=1] + %tmp.11 = add i32 %tmp.8, %tmp.1 ; X ^ X = 0 - %RV = xor i32 %tmp.5, %tmp.11 ; [#uses=1] + %RV = xor i32 %tmp.5, %tmp.11 ret i32 %RV ; CHECK: @test6 ; CHECK: ret i32 0 @@ -108,6 +108,7 @@ ; This should be one add and two multiplies. define i32 @test7(i32 %A, i32 %B, i32 %C) { + ; A*A*B + A*C*A %aa = mul i32 %A, %A %aab = mul i32 %aa, %B %ac = mul i32 %A, %C @@ -141,6 +142,27 @@ %Z = add i32 %Y, %Y ret i32 %Z ; CHECK: @test9 -; CHECK-NEXT: %Z = mul i32 %X, 94 -; CHECK-NEXT: ret i32 %Z +; CHECK-NEXT: mul i32 %X, 94 +; CHECK-NEXT: ret i32 } + +define i32 @test10(i32 %X) { + %Y = add i32 %X ,%X + %Z = add i32 %Y, %X + ret i32 %Z +; CHECK: @test10 +; CHECK-NEXT: mul i32 %X, 3 +; CHECK-NEXT: ret i32 +} + +define i32 @test11(i32 %W) { + %X = mul i32 %W, 127 + %Y = add i32 %X ,%X + %Z = add i32 %Y, %X + ret i32 %Z +; CHECK: @test11 +; CHECK-NEXT: mul i32 %W, 381 +; CHECK-NEXT: ret i32 +} + + From sabre at nondot.org Thu Dec 31 13:25:19 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 19:25:19 -0000 Subject: [llvm-commits] [llvm] r92369 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912311925.nBVJPJQ7002907@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 13:25:19 2009 New Revision: 92369 URL: http://llvm.org/viewvc/llvm-project?rev=92369&view=rev Log: remove debug Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92369&r1=92368&r2=92369&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 13:25:19 2009 @@ -627,7 +627,7 @@ --j; --je; } - /*DEBUG*/(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n'); + DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n'); ++NumFactor; From sabre at nondot.org Thu Dec 31 13:34:45 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 19:34:45 -0000 Subject: [llvm-commits] [llvm] r92370 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912311934.nBVJYjjb003211@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 13:34:45 2009 New Revision: 92370 URL: http://llvm.org/viewvc/llvm-project?rev=92370&view=rev Log: make reassociate more careful about not leaving around dead mul's Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92370&r1=92369&r2=92370&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 13:34:45 2009 @@ -530,7 +530,13 @@ return 0; } - if (Factors.size() == 1) return Factors[0].Op; + // If this was just a single multiply, remove the multiply and return the only + // remaining operand. + if (Factors.size() == 1) { + ValueRankMap.erase(BO); + BO->eraseFromParent(); + return Factors[0].Op; + } RewriteExprTree(BO, Factors); return BO; From sabre at nondot.org Thu Dec 31 13:49:02 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 19:49:02 -0000 Subject: [llvm-commits] [llvm] r92372 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <200912311949.nBVJn2Ap003664@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 13:49:01 2009 New Revision: 92372 URL: http://llvm.org/viewvc/llvm-project?rev=92372&view=rev Log: we don't need a smallptrset to detect duplicates, the values are sorted, so we can just do a linear scan. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92372&r1=92371&r2=92372&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 13:49:01 2009 @@ -587,20 +587,22 @@ assert(i < Ops.size()); if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) { if (Opcode == Instruction::And || Opcode == Instruction::Or) { - // Drop duplicate values. + // Drop duplicate values for And and Or. Ops.erase(Ops.begin()+i); --i; --e; ++NumAnnihil; - } else { - assert(Opcode == Instruction::Xor); - if (e == 2) - return Constant::getNullValue(Ops[0].Op->getType()); - - // ... X^X -> ... - Ops.erase(Ops.begin()+i, Ops.begin()+i+2); - i -= 1; e -= 2; - ++NumAnnihil; + continue; } + + // Drop pairs of values for Xor. + assert(Opcode == Instruction::Xor); + if (e == 2) + return Constant::getNullValue(Ops[0].Op->getType()); + + // ... X^X -> ... + Ops.erase(Ops.begin()+i, Ops.begin()+i+2); + i -= 1; e -= 2; + ++NumAnnihil; } } return 0; @@ -611,31 +613,24 @@ /// is returned, otherwise the Ops list is mutated as necessary. Value *Reassociate::OptimizeAdd(Instruction *I, SmallVectorImpl &Ops) { - SmallPtrSet OperandsSeen; - -Restart: - OperandsSeen.clear(); - // Scan the operand lists looking for X and -X pairs. If we find any, we // can simplify the expression. X+-X == 0. While we're at it, scan for any // duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z. for (unsigned i = 0, e = Ops.size(); i != e; ++i) { Value *TheOp = Ops[i].Op; // Check to see if we've seen this operand before. If so, we factor all - // instances of the operand together. - if (!OperandsSeen.insert(TheOp)) { - // Rescan the list, removing all instances of this operand from the expr. + // instances of the operand together. Due to our sorting criteria, we know + // that these need to be next to each other in the vector. + if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) { + // Rescan the list, remove all instances of this operand from the expr. unsigned NumFound = 0; - for (unsigned j = 0, je = Ops.size(); j != je; ++j) { - if (Ops[j].Op != TheOp) continue; + do { + Ops.erase(Ops.begin()+i); ++NumFound; - Ops.erase(Ops.begin()+j); - --j; --je; - } - + } while (i != Ops.size() && Ops[i].Op == TheOp); + DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n'); ++NumFactor; - // Insert a new multiply. Value *Mul = ConstantInt::get(cast(I->getType()), NumFound); @@ -654,7 +649,10 @@ // "A + A + B" -> "A*2 + B". Add the new multiply to the list of // things being added by this operation. Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul)); - goto Restart; + + --i; + e = Ops.size(); + continue; } // Check for X and -X in the operand list. @@ -755,7 +753,9 @@ // Create the multiply. Value *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I); - // FIXME: Should rerun 'ReassociateExpression' on the mul too?? + // Rerun associate on the multiply in case the inner expression turned into + // a multiply. We want to make sure that we keep things in canonical form. + V2 = ReassociateExpression(cast(V2)); // If every add operand included the factor (e.g. "A*B + A*C"), then the // entire result expression is just the multiply "A*(B+C)". From sabre at nondot.org Thu Dec 31 14:34:32 2009 From: sabre at nondot.org (Chris Lattner) Date: Thu, 31 Dec 2009 20:34:32 -0000 Subject: [llvm-commits] [llvm] r92373 - in /llvm/trunk: lib/Transforms/Scalar/Reassociate.cpp test/Transforms/Reassociate/basictest.ll Message-ID: <200912312034.nBVKYWP9005016@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 14:34:32 2009 New Revision: 92373 URL: http://llvm.org/viewvc/llvm-project?rev=92373&view=rev Log: reuse negates where possible instead of always creating them from scratch. This allows us to optimize test12 into: define i32 @test12(i32 %X) { %factor = mul i32 %X, -3 ; [#uses=1] %Z = add i32 %factor, 6 ; [#uses=1] ret i32 %Z } instead of: define i32 @test12(i32 %X) { %Y = sub i32 6, %X ; [#uses=1] %C = sub i32 %Y, %X ; [#uses=1] %Z = sub i32 %C, %X ; [#uses=1] ret i32 %Z } Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp llvm/trunk/test/Transforms/Reassociate/basictest.ll Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92373&r1=92372&r2=92373&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 14:34:32 2009 @@ -376,6 +376,9 @@ // that should be processed next by the reassociation pass. // static Value *NegateValue(Value *V, Instruction *BI) { + if (Constant *C = dyn_cast(V)) + return ConstantExpr::getNeg(C); + // We are trying to expose opportunity for reassociation. One of the things // that we want to do to achieve this is to push a negation as deep into an // expression chain as possible, to expose the add instructions. In practice, @@ -400,10 +403,36 @@ I->setName(I->getName()+".neg"); return I; } + + // Okay, we need to materialize a negated version of V with an instruction. + // Scan the use lists of V to see if we have one already. + for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){ + if (!BinaryOperator::isNeg(*UI)) continue; + + // We found one! Now we have to make sure that the definition dominates + // this use. We do this by moving it to the entry block (if it is a + // non-instruction value) or right after the definition. These negates will + // be zapped by reassociate later, so we don't need much finesse here. + BinaryOperator *TheNeg = cast(*UI); + + BasicBlock::iterator InsertPt; + if (Instruction *InstInput = dyn_cast(V)) { + if (InvokeInst *II = dyn_cast(InstInput)) { + InsertPt = II->getNormalDest()->begin(); + } else { + InsertPt = InstInput; + ++InsertPt; + } + while (isa(InsertPt)) ++InsertPt; + } else { + InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin(); + } + TheNeg->moveBefore(InsertPt); + return TheNeg; + } // Insert a 'neg' instruction that subtracts the value from zero to get the // negation. - // return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI); } Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest.ll?rev=92373&r1=92372&r2=92373&view=diff ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest.ll Thu Dec 31 14:34:32 2009 @@ -165,4 +165,17 @@ ; CHECK-NEXT: ret i32 } +define i32 @test12(i32 %X) { + %A = sub i32 1, %X + %B = sub i32 2, %X + %C = sub i32 3, %X + + %Y = add i32 %A ,%B + %Z = add i32 %Y, %C + ret i32 %Z +; CHECK: @test12 +; CHECK-NEXT: mul i32 %X, -3 +; CHECK-NEXT: add i32{{.*}}, 6 +; CHECK-NEXT: ret i32 +} From kremenek at apple.com Thu Dec 31 17:40:17 2009 From: kremenek at apple.com (Ted Kremenek) Date: Thu, 31 Dec 2009 23:40:17 -0000 Subject: [llvm-commits] [llvm] r92374 - in /llvm/trunk: include/llvm/Bitcode/Serialization.h include/llvm/Bitcode/SerializationFwd.h include/llvm/Bitcode/Serialize.h lib/Bitcode/Reader/CMakeLists.txt lib/Bitcode/Reader/Deserialize.cpp lib/Bitcode/Reader/DeserializeAPFloat.cpp lib/Bitcode/Reader/DeserializeAPInt.cpp lib/Bitcode/Writer/CMakeLists.txt lib/Bitcode/Writer/Serialize.cpp lib/Bitcode/Writer/SerializeAPFloat.cpp lib/Bitcode/Writer/SerializeAPInt.cpp Message-ID: <200912312340.nBVNeI5P011149@zion.cs.uiuc.edu> Author: kremenek Date: Thu Dec 31 17:40:17 2009 New Revision: 92374 URL: http://llvm.org/viewvc/llvm-project?rev=92374&view=rev Log: Remove derelict serialization code. Removed: llvm/trunk/include/llvm/Bitcode/Serialization.h llvm/trunk/include/llvm/Bitcode/SerializationFwd.h llvm/trunk/include/llvm/Bitcode/Serialize.h llvm/trunk/lib/Bitcode/Reader/Deserialize.cpp llvm/trunk/lib/Bitcode/Reader/DeserializeAPFloat.cpp llvm/trunk/lib/Bitcode/Reader/DeserializeAPInt.cpp llvm/trunk/lib/Bitcode/Writer/Serialize.cpp llvm/trunk/lib/Bitcode/Writer/SerializeAPFloat.cpp llvm/trunk/lib/Bitcode/Writer/SerializeAPInt.cpp Modified: llvm/trunk/lib/Bitcode/Reader/CMakeLists.txt llvm/trunk/lib/Bitcode/Writer/CMakeLists.txt Removed: llvm/trunk/include/llvm/Bitcode/Serialization.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Bitcode/Serialization.h?rev=92373&view=auto ============================================================================== --- llvm/trunk/include/llvm/Bitcode/Serialization.h (original) +++ llvm/trunk/include/llvm/Bitcode/Serialization.h (removed) @@ -1,68 +0,0 @@ -//==- Serialization.h - Generic Object Serialization to Bitcode ---*- C++ -*-=// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines traits for primitive types used for both object -// serialization and deserialization. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_BITCODE_SERIALIZE -#define LLVM_BITCODE_SERIALIZE - -#include "llvm/Bitcode/SerializationFwd.h" - -namespace llvm { - -/// SerializeTrait - SerializeTrait bridges between the Serializer/Deserializer -/// and the functions that serialize objects of specific types. The default -/// behavior is to call static methods of the class for the object being -/// serialized, but this behavior can be changed by specializing this -/// template. Classes only need to implement the methods corresponding -/// to the serialization scheme they want to support. For example, "Read" -/// and "ReadVal" correspond to different deserialization schemes which make -/// sense for different types; a class need only implement one of them. -/// Serialization and deserialization of pointers are specially handled -/// by the Serializer and Deserializer using the EmitOwnedPtr, etc. methods. -/// To serialize the actual object referred to by a pointer, the class -/// of the object either must implement the methods called by the default -/// behavior of SerializeTrait, or specialize SerializeTrait. This latter -/// is useful when one cannot add methods to an existing class (for example). -template -struct SerializeTrait { - static inline void Emit(Serializer& S, const T& X) { X.Emit(S); } - static inline void Read(Deserializer& D, T& X) { X.Read(D); } - static inline T* Create(Deserializer& D) { return T::Create(D); } - - template - static inline T* Create(Deserializer& D, Arg1& arg1) { - return T::Create(D, arg1); - } -}; - -#define SERIALIZE_INT_TRAIT(TYPE)\ -template <> struct SerializeTrait {\ - static void Emit(Serializer& S, TYPE X);\ - static void Read(Deserializer& S, TYPE& X); }; - -SERIALIZE_INT_TRAIT(bool) -SERIALIZE_INT_TRAIT(unsigned char) -SERIALIZE_INT_TRAIT(unsigned short) -SERIALIZE_INT_TRAIT(unsigned int) -SERIALIZE_INT_TRAIT(unsigned long) - -SERIALIZE_INT_TRAIT(signed char) -SERIALIZE_INT_TRAIT(signed short) -SERIALIZE_INT_TRAIT(signed int) -SERIALIZE_INT_TRAIT(signed long) - -#undef SERIALIZE_INT_TRAIT - -} // end namespace llvm - -#endif Removed: llvm/trunk/include/llvm/Bitcode/SerializationFwd.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Bitcode/SerializationFwd.h?rev=92373&view=auto ============================================================================== --- llvm/trunk/include/llvm/Bitcode/SerializationFwd.h (original) +++ llvm/trunk/include/llvm/Bitcode/SerializationFwd.h (removed) @@ -1,27 +0,0 @@ -//==- SerializationFwd.h - Forward references for Serialization ---*- C++ -*-=// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file provides forward references for bitcode object serialization. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_BITCODE_SERIALIZE_FWD -#define LLVM_BITCODE_SERIALIZE_FWD - -namespace llvm { - -class Serializer; -class Deserializer; -template struct SerializeTrait; - -typedef unsigned SerializedPtrID; - -} // end namespace llvm - -#endif Removed: llvm/trunk/include/llvm/Bitcode/Serialize.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Bitcode/Serialize.h?rev=92373&view=auto ============================================================================== --- llvm/trunk/include/llvm/Bitcode/Serialize.h (original) +++ llvm/trunk/include/llvm/Bitcode/Serialize.h (removed) @@ -1,211 +0,0 @@ -//==- Serialize.h - Generic Object Serialization to Bitcode -------*- C++ -*-=// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the interface for generic object serialization to -// LLVM bitcode. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_BITCODE_SERIALIZE_OUTPUT -#define LLVM_BITCODE_SERIALIZE_OUTPUT - -#include "llvm/Bitcode/Serialization.h" -#include "llvm/Bitcode/BitstreamWriter.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/DenseMap.h" - -namespace llvm { - -class Serializer { - BitstreamWriter& Stream; - SmallVector Record; - unsigned BlockLevel; - - typedef DenseMap MapTy; - MapTy PtrMap; - -public: - explicit Serializer(BitstreamWriter& stream); - ~Serializer(); - - //==------------------------------------------------==// - // Template-based dispatch to emit arbitrary types. - //==------------------------------------------------==// - - template - inline void Emit(const T& X) { SerializeTrait::Emit(*this,X); } - - //==------------------------------------------------==// - // Methods to emit primitive types. - //==------------------------------------------------==// - - void EmitInt(uint64_t X); - void EmitSInt(int64_t X); - - inline void EmitBool(bool X) { EmitInt(X); } - void EmitCStr(const char* beg, const char* end); - void EmitCStr(const char* cstr); - - void EmitPtr(const void* ptr) { EmitInt(getPtrId(ptr)); } - - template - inline void EmitRef(const T& ref) { EmitPtr(&ref); } - - // Emit a pointer and the object pointed to. (This has no relation to the - // OwningPtr<> class.) - template - inline void EmitOwnedPtr(T* ptr) { - EmitPtr(ptr); - if (ptr) SerializeTrait::Emit(*this,*ptr); - } - - - //==------------------------------------------------==// - // Batch emission of pointers. - //==------------------------------------------------==// - - template - void BatchEmitOwnedPtrs(T1* p1, T2* p2) { - EmitPtr(p1); - EmitPtr(p2); - if (p1) SerializeTrait::Emit(*this,*p1); - if (p2) SerializeTrait::Emit(*this,*p2); - } - - template - void BatchEmitOwnedPtrs(T1* p1, T2* p2, T3* p3) { - EmitPtr(p1); - EmitPtr(p2); - EmitPtr(p3); - if (p1) SerializeTrait::Emit(*this,*p1); - if (p2) SerializeTrait::Emit(*this,*p2); - if (p3) SerializeTrait::Emit(*this,*p3); - } - - template - void BatchEmitOwnedPtrs(T1* p1, T2* p2, T3* p3, T4& p4) { - EmitPtr(p1); - EmitPtr(p2); - EmitPtr(p3); - EmitPtr(p4); - if (p1) SerializeTrait::Emit(*this,*p1); - if (p2) SerializeTrait::Emit(*this,*p2); - if (p3) SerializeTrait::Emit(*this,*p3); - if (p4) SerializeTrait::Emit(*this,*p4); - } - - template - void BatchEmitOwnedPtrs(unsigned NumPtrs, T* const * Ptrs) { - for (unsigned i = 0; i < NumPtrs; ++i) - EmitPtr(Ptrs[i]); - - for (unsigned i = 0; i < NumPtrs; ++i) - if (Ptrs[i]) SerializeTrait::Emit(*this,*Ptrs[i]); - } - - template - void BatchEmitOwnedPtrs(unsigned NumT1Ptrs, T1* const * Ptrs, T2* p2) { - - for (unsigned i = 0; i < NumT1Ptrs; ++i) - EmitPtr(Ptrs[i]); - - EmitPtr(p2); - - for (unsigned i = 0; i < NumT1Ptrs; ++i) - if (Ptrs[i]) SerializeTrait::Emit(*this,*Ptrs[i]); - - if (p2) SerializeTrait::Emit(*this,*p2); - } - - template - void BatchEmitOwnedPtrs(unsigned NumT1Ptrs, T1* const * Ptrs, - T2* p2, T3* p3) { - - for (unsigned i = 0; i < NumT1Ptrs; ++i) - EmitPtr(Ptrs[i]); - - EmitPtr(p2); - EmitPtr(p3); - - for (unsigned i = 0; i < NumT1Ptrs; ++i) - if (Ptrs[i]) SerializeTrait::Emit(*this,*Ptrs[i]); - - if (p2) SerializeTrait::Emit(*this,*p2); - if (p3) SerializeTrait::Emit(*this,*p3); - } - - //==------------------------------------------------==// - // Emitter Functors - //==------------------------------------------------==// - - template - struct Emitter0 { - Serializer& S; - Emitter0(Serializer& s) : S(s) {} - void operator()(const T& x) const { - SerializeTrait::Emit(S,x); - } - }; - - template - struct Emitter1 { - Serializer& S; - Arg1 A1; - - Emitter1(Serializer& s, Arg1 a1) : S(s), A1(a1) {} - void operator()(const T& x) const { - SerializeTrait::Emit(S,x,A1); - } - }; - - template - struct Emitter2 { - Serializer& S; - Arg1 A1; - Arg2 A2; - - Emitter2(Serializer& s, Arg1 a1, Arg2 a2) : S(s), A1(a1), A2(a2) {} - void operator()(const T& x) const { - SerializeTrait::Emit(S,x,A1,A2); - } - }; - - template - Emitter0 MakeEmitter() { - return Emitter0(*this); - } - - template - Emitter1 MakeEmitter(Arg1 a1) { - return Emitter1(*this,a1); - } - - template - Emitter2 MakeEmitter(Arg1 a1, Arg2 a2) { - return Emitter2(*this,a1,a2); - } - - //==------------------------------------------------==// - // Misc. query and block/record manipulation methods. - //==------------------------------------------------==// - - bool isRegistered(const void* p) const; - - void FlushRecord() { if (inRecord()) EmitRecord(); } - void EnterBlock(unsigned BlockID = 8, unsigned CodeLen = 3); - void ExitBlock(); - -private: - void EmitRecord(); - inline bool inRecord() { return Record.size() > 0; } - SerializedPtrID getPtrId(const void* ptr); -}; - -} // end namespace llvm -#endif Modified: llvm/trunk/lib/Bitcode/Reader/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Reader/CMakeLists.txt?rev=92374&r1=92373&r2=92374&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Reader/CMakeLists.txt (original) +++ llvm/trunk/lib/Bitcode/Reader/CMakeLists.txt Thu Dec 31 17:40:17 2009 @@ -1,7 +1,4 @@ add_llvm_library(LLVMBitReader BitReader.cpp BitcodeReader.cpp - Deserialize.cpp - DeserializeAPFloat.cpp - DeserializeAPInt.cpp - ) \ No newline at end of file + ) Removed: llvm/trunk/lib/Bitcode/Reader/Deserialize.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Reader/Deserialize.cpp?rev=92373&view=auto ============================================================================== --- llvm/trunk/lib/Bitcode/Reader/Deserialize.cpp (original) +++ llvm/trunk/lib/Bitcode/Reader/Deserialize.cpp (removed) @@ -1,450 +0,0 @@ -//==- Deserialize.cpp - Generic Object Serialization to Bitcode --*- C++ -*-==// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the internal methods used for object serialization. -// -//===----------------------------------------------------------------------===// - -#include "llvm/Bitcode/Deserialize.h" -#include "llvm/Support/raw_ostream.h" -using namespace llvm; - -Deserializer::Deserializer(BitstreamReader& stream) - : Stream(stream), RecIdx(0), FreeList(NULL), AbbrevNo(0), RecordCode(0) { - - StreamStart = Stream.GetCurrentBitNo(); -} - -Deserializer::~Deserializer() { - assert (RecIdx >= Record.size() && - "Still scanning bitcode record when deserialization completed."); - -#ifdef DEBUG_BACKPATCH - for (MapTy::iterator I=BPatchMap.begin(), E=BPatchMap.end(); I!=E; ++I) - assert (I->first.hasFinalPtr() && - "Some pointers were not backpatched."); -#endif -} - - -bool Deserializer::inRecord() { - if (Record.size() > 0) { - if (RecIdx >= Record.size()) { - RecIdx = 0; - Record.clear(); - AbbrevNo = 0; - return false; - } - else - return true; - } - - return false; -} - -bool Deserializer::AdvanceStream() { - assert (!inRecord() && - "Cannot advance stream. Still processing a record."); - - if (AbbrevNo == bitc::ENTER_SUBBLOCK || - AbbrevNo >= bitc::UNABBREV_RECORD) - return true; - - while (!Stream.AtEndOfStream()) { - - uint64_t Pos = Stream.GetCurrentBitNo(); - AbbrevNo = Stream.ReadCode(); - - switch (AbbrevNo) { - case bitc::ENTER_SUBBLOCK: { - unsigned id = Stream.ReadSubBlockID(); - - // Determine the extent of the block. This is useful for jumping around - // the stream. This is hack: we read the header of the block, save - // the length, and then revert the bitstream to a location just before - // the block is entered. - uint64_t BPos = Stream.GetCurrentBitNo(); - Stream.ReadVBR(bitc::CodeLenWidth); // Skip the code size. - Stream.SkipToWord(); - unsigned NumWords = Stream.Read(bitc::BlockSizeWidth); - Stream.JumpToBit(BPos); - - BlockStack.push_back(Location(Pos,id,NumWords)); - break; - } - - case bitc::END_BLOCK: { - bool x = Stream.ReadBlockEnd(); - assert(!x && "Error at block end."); x=x; - BlockStack.pop_back(); - continue; - } - - case bitc::DEFINE_ABBREV: - Stream.ReadAbbrevRecord(); - continue; - - default: - break; - } - - return true; - } - - return false; -} - -void Deserializer::ReadRecord() { - - while (AdvanceStream() && AbbrevNo == bitc::ENTER_SUBBLOCK) { - assert (!BlockStack.empty()); - Stream.EnterSubBlock(BlockStack.back().BlockID); - AbbrevNo = 0; - } - - if (Stream.AtEndOfStream()) - return; - - assert (Record.empty()); - assert (AbbrevNo >= bitc::UNABBREV_RECORD); - RecordCode = Stream.ReadRecord(AbbrevNo,Record); - assert (Record.size() > 0); -} - -void Deserializer::SkipBlock() { - assert (!inRecord()); - - if (AtEnd()) - return; - - AdvanceStream(); - - assert (AbbrevNo == bitc::ENTER_SUBBLOCK); - BlockStack.pop_back(); - Stream.SkipBlock(); - - AbbrevNo = 0; - AdvanceStream(); -} - -bool Deserializer::SkipToBlock(unsigned BlockID) { - assert (!inRecord()); - - AdvanceStream(); - assert (AbbrevNo == bitc::ENTER_SUBBLOCK); - - unsigned BlockLevel = BlockStack.size(); - - while (!AtEnd() && - BlockLevel == BlockStack.size() && - getCurrentBlockID() != BlockID) - SkipBlock(); - - return !(AtEnd() || BlockLevel != BlockStack.size()); -} - -Deserializer::Location Deserializer::getCurrentBlockLocation() { - if (!inRecord()) - AdvanceStream(); - - return BlockStack.back(); -} - -bool Deserializer::JumpTo(const Location& Loc) { - - assert (!inRecord()); - - AdvanceStream(); - - assert (!BlockStack.empty() || AtEnd()); - - uint64_t LastBPos = StreamStart; - - while (!BlockStack.empty()) { - - LastBPos = BlockStack.back().BitNo; - - // Determine of the current block contains the location of the block - // we are looking for. - if (BlockStack.back().contains(Loc)) { - // We found the enclosing block. We must first POP it off to - // destroy any accumulated context within the block scope. We then - // jump to the position of the block and enter it. - Stream.JumpToBit(LastBPos); - - if (BlockStack.size() == Stream.BlockScope.size()) - Stream.PopBlockScope(); - - BlockStack.pop_back(); - - AbbrevNo = 0; - AdvanceStream(); - assert (AbbrevNo == bitc::ENTER_SUBBLOCK); - - Stream.EnterSubBlock(BlockStack.back().BlockID); - break; - } - - // This block does not contain the block we are looking for. Pop it. - if (BlockStack.size() == Stream.BlockScope.size()) - Stream.PopBlockScope(); - - BlockStack.pop_back(); - - } - - // Check if we have popped our way to the outermost scope. If so, - // we need to adjust our position. - if (BlockStack.empty()) { - assert (Stream.BlockScope.empty()); - - Stream.JumpToBit(Loc.BitNo < LastBPos ? StreamStart : LastBPos); - AbbrevNo = 0; - AdvanceStream(); - } - - assert (AbbrevNo == bitc::ENTER_SUBBLOCK); - assert (!BlockStack.empty()); - - while (!AtEnd() && BlockStack.back() != Loc) { - if (BlockStack.back().contains(Loc)) { - Stream.EnterSubBlock(BlockStack.back().BlockID); - AbbrevNo = 0; - AdvanceStream(); - continue; - } - else - SkipBlock(); - } - - if (AtEnd()) - return false; - - assert (BlockStack.back() == Loc); - - return true; -} - -void Deserializer::Rewind() { - while (!Stream.BlockScope.empty()) - Stream.PopBlockScope(); - - while (!BlockStack.empty()) - BlockStack.pop_back(); - - Stream.JumpToBit(StreamStart); - AbbrevNo = 0; -} - - -unsigned Deserializer::getCurrentBlockID() { - if (!inRecord()) - AdvanceStream(); - - return BlockStack.back().BlockID; -} - -unsigned Deserializer::getRecordCode() { - if (!inRecord()) { - AdvanceStream(); - assert (AbbrevNo >= bitc::UNABBREV_RECORD); - ReadRecord(); - } - - return RecordCode; -} - -bool Deserializer::FinishedBlock(Location BlockLoc) { - if (!inRecord()) - AdvanceStream(); - - for (llvm::SmallVector::reverse_iterator - I=BlockStack.rbegin(), E=BlockStack.rend(); I!=E; ++I) - if (*I == BlockLoc) - return false; - - return true; -} - -unsigned Deserializer::getAbbrevNo() { - if (!inRecord()) - AdvanceStream(); - - return AbbrevNo; -} - -bool Deserializer::AtEnd() { - if (inRecord()) - return false; - - if (!AdvanceStream()) - return true; - - return false; -} - -uint64_t Deserializer::ReadInt() { - // FIXME: Any error recovery/handling with incomplete or bad files? - if (!inRecord()) - ReadRecord(); - - return Record[RecIdx++]; -} - -int64_t Deserializer::ReadSInt() { - uint64_t x = ReadInt(); - int64_t magnitude = x >> 1; - return x & 0x1 ? -magnitude : magnitude; -} - -char* Deserializer::ReadCStr(char* cstr, unsigned MaxLen, bool isNullTerm) { - if (cstr == NULL) - MaxLen = 0; // Zero this just in case someone does something funny. - - unsigned len = ReadInt(); - - assert (MaxLen == 0 || (len + (isNullTerm ? 1 : 0)) <= MaxLen); - - if (!cstr) - cstr = new char[len + (isNullTerm ? 1 : 0)]; - - assert (cstr != NULL); - - for (unsigned i = 0; i < len; ++i) - cstr[i] = (char) ReadInt(); - - if (isNullTerm) - cstr[len] = '\0'; - - return cstr; -} - -void Deserializer::ReadCStr(std::vector& buff, bool isNullTerm, - unsigned Idx) { - - unsigned len = ReadInt(); - - // If Idx is beyond the current before size, reduce Idx to refer to the - // element after the last element. - if (Idx > buff.size()) - Idx = buff.size(); - - buff.reserve(len+Idx); - buff.resize(Idx); - - for (unsigned i = 0; i < len; ++i) - buff.push_back((char) ReadInt()); - - if (isNullTerm) - buff.push_back('\0'); -} - -void Deserializer::RegisterPtr(const SerializedPtrID& PtrId, - const void* Ptr) { - - MapTy::value_type& E = BPatchMap.FindAndConstruct(BPKey(PtrId)); - - assert (!HasFinalPtr(E) && "Pointer already registered."); - -#ifdef DEBUG_BACKPATCH - dbgs() << "RegisterPtr: " << PtrId << " => " << Ptr << "\n"; -#endif - - SetPtr(E,Ptr); -} - -void Deserializer::ReadUIntPtr(uintptr_t& PtrRef, - const SerializedPtrID& PtrId, - bool AllowBackpatch) { - if (PtrId == 0) { - PtrRef = 0; - return; - } - - MapTy::value_type& E = BPatchMap.FindAndConstruct(BPKey(PtrId)); - - if (HasFinalPtr(E)) { - PtrRef = GetFinalPtr(E); - -#ifdef DEBUG_BACKPATCH - dbgs() << "ReadUintPtr: " << PtrId - << " <-- " << (void*) GetFinalPtr(E) << '\n'; -#endif - } - else { - assert (AllowBackpatch && - "Client forbids backpatching for this pointer."); - -#ifdef DEBUG_BACKPATCH - dbgs() << "ReadUintPtr: " << PtrId << " (NO PTR YET)\n"; -#endif - - // Register backpatch. Check the freelist for a BPNode. - BPNode* N; - - if (FreeList) { - N = FreeList; - FreeList = FreeList->Next; - } - else // No available BPNode. Allocate one. - N = (BPNode*) Allocator.Allocate(); - - new (N) BPNode(GetBPNode(E),PtrRef); - SetBPNode(E,N); - } -} - -uintptr_t Deserializer::ReadInternalRefPtr() { - SerializedPtrID PtrId = ReadPtrID(); - - assert (PtrId != 0 && "References cannot refer the NULL address."); - - MapTy::value_type& E = BPatchMap.FindAndConstruct(BPKey(PtrId)); - - assert (HasFinalPtr(E) && - "Cannot backpatch references. Object must be already deserialized."); - - return GetFinalPtr(E); -} - -void BPEntry::SetPtr(BPNode*& FreeList, void* P) { - BPNode* Last = NULL; - - for (BPNode* N = Head; N != NULL; N=N->Next) { - Last = N; - N->PtrRef |= reinterpret_cast(P); - } - - if (Last) { - Last->Next = FreeList; - FreeList = Head; - } - - Ptr = const_cast(P); -} - - -#define INT_READ(TYPE)\ -void SerializeTrait::Read(Deserializer& D, TYPE& X) {\ - X = (TYPE) D.ReadInt(); } - -INT_READ(bool) -INT_READ(unsigned char) -INT_READ(unsigned short) -INT_READ(unsigned int) -INT_READ(unsigned long) - -#define SINT_READ(TYPE)\ -void SerializeTrait::Read(Deserializer& D, TYPE& X) {\ - X = (TYPE) D.ReadSInt(); } - -INT_READ(signed char) -INT_READ(signed short) -INT_READ(signed int) -INT_READ(signed long) Removed: llvm/trunk/lib/Bitcode/Reader/DeserializeAPFloat.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Reader/DeserializeAPFloat.cpp?rev=92373&view=auto ============================================================================== --- llvm/trunk/lib/Bitcode/Reader/DeserializeAPFloat.cpp (original) +++ llvm/trunk/lib/Bitcode/Reader/DeserializeAPFloat.cpp (removed) @@ -1,24 +0,0 @@ -//===-- SerializeAPInt.cpp - Serialization for APFloat ---------*- C++ -*--===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements deserialization of APFloat. -// -//===----------------------------------------------------------------------===// - -#include "llvm/ADT/APFloat.h" -#include "llvm/Bitcode/Deserialize.h" - -using namespace llvm; - -APFloat APFloat::ReadVal(Deserializer& D) { - APInt x; - D.Read(x); - return APFloat(x); -} - Removed: llvm/trunk/lib/Bitcode/Reader/DeserializeAPInt.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Reader/DeserializeAPInt.cpp?rev=92373&view=auto ============================================================================== --- llvm/trunk/lib/Bitcode/Reader/DeserializeAPInt.cpp (original) +++ llvm/trunk/lib/Bitcode/Reader/DeserializeAPInt.cpp (removed) @@ -1,33 +0,0 @@ -//===-- DeserializeAPInt.cpp - Deserialization for APInts ------*- C++ -*--===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements deserialization of APInts. -// -//===----------------------------------------------------------------------===// - -#include "llvm/ADT/APInt.h" -#include "llvm/Bitcode/Deserialize.h" -#include - -using namespace llvm; - -void APInt::Read(Deserializer& D) { - BitWidth = D.ReadInt(); - - if (isSingleWord()) - VAL = D.ReadInt(); - else { - uint32_t NumWords = D.ReadInt(); - assert (NumWords > 1); - pVal = new uint64_t[NumWords]; - assert (pVal && "Allocation in deserialization of APInt failed."); - for (unsigned i = 0; i < NumWords; ++i) - pVal[i] = D.ReadInt(); - } -} Modified: llvm/trunk/lib/Bitcode/Writer/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/CMakeLists.txt?rev=92374&r1=92373&r2=92374&view=diff ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/CMakeLists.txt (original) +++ llvm/trunk/lib/Bitcode/Writer/CMakeLists.txt Thu Dec 31 17:40:17 2009 @@ -2,8 +2,5 @@ BitWriter.cpp BitcodeWriter.cpp BitcodeWriterPass.cpp - Serialize.cpp - SerializeAPFloat.cpp - SerializeAPInt.cpp ValueEnumerator.cpp ) Removed: llvm/trunk/lib/Bitcode/Writer/Serialize.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/Serialize.cpp?rev=92373&view=auto ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/Serialize.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/Serialize.cpp (removed) @@ -1,115 +0,0 @@ -//==- Serialize.cpp - Generic Object Serialization to Bitcode ----*- C++ -*-==// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the internal methods used for object serialization. -// -//===----------------------------------------------------------------------===// - -#include "llvm/Bitcode/Serialize.h" -#include "llvm/Support/raw_ostream.h" -#include - -using namespace llvm; - -Serializer::Serializer(BitstreamWriter& stream) - : Stream(stream), BlockLevel(0) {} - -Serializer::~Serializer() { - if (inRecord()) - EmitRecord(); - - while (BlockLevel > 0) - Stream.ExitBlock(); - - Stream.FlushToWord(); -} - -void Serializer::EmitRecord() { - assert(Record.size() > 0 && "Cannot emit empty record."); - Stream.EmitRecord(8,Record); - Record.clear(); -} - -void Serializer::EnterBlock(unsigned BlockID,unsigned CodeLen) { - FlushRecord(); - Stream.EnterSubblock(BlockID,CodeLen); - ++BlockLevel; -} - -void Serializer::ExitBlock() { - assert (BlockLevel > 0); - --BlockLevel; - FlushRecord(); - Stream.ExitBlock(); -} - -void Serializer::EmitInt(uint64_t X) { - assert (BlockLevel > 0); - Record.push_back(X); -} - -void Serializer::EmitSInt(int64_t X) { - if (X >= 0) - EmitInt(X << 1); - else - EmitInt((-X << 1) | 1); -} - -void Serializer::EmitCStr(const char* s, const char* end) { - Record.push_back(end - s); - - while(s != end) { - Record.push_back(*s); - ++s; - } -} - -void Serializer::EmitCStr(const char* s) { - EmitCStr(s,s+strlen(s)); -} - -SerializedPtrID Serializer::getPtrId(const void* ptr) { - if (!ptr) - return 0; - - MapTy::iterator I = PtrMap.find(ptr); - - if (I == PtrMap.end()) { - unsigned id = PtrMap.size()+1; -#ifdef DEBUG_BACKPATCH - dbgs() << "Registered PTR: " << ptr << " => " << id << "\n"; -#endif - PtrMap[ptr] = id; - return id; - } - else return I->second; -} - -bool Serializer::isRegistered(const void* ptr) const { - MapTy::const_iterator I = PtrMap.find(ptr); - return I != PtrMap.end(); -} - - -#define INT_EMIT(TYPE)\ -void SerializeTrait::Emit(Serializer&S, TYPE X) { S.EmitInt(X); } - -INT_EMIT(bool) -INT_EMIT(unsigned char) -INT_EMIT(unsigned short) -INT_EMIT(unsigned int) -INT_EMIT(unsigned long) - -#define SINT_EMIT(TYPE)\ -void SerializeTrait::Emit(Serializer&S, TYPE X) { S.EmitSInt(X); } - -SINT_EMIT(signed char) -SINT_EMIT(signed short) -SINT_EMIT(signed int) -SINT_EMIT(signed long) Removed: llvm/trunk/lib/Bitcode/Writer/SerializeAPFloat.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/SerializeAPFloat.cpp?rev=92373&view=auto ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/SerializeAPFloat.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/SerializeAPFloat.cpp (removed) @@ -1,21 +0,0 @@ -//===-- SerializeAPInt.cpp - Serialization for APFloat ---------*- C++ -*--===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements serialization of APFloat. -// -//===----------------------------------------------------------------------===// - -#include "llvm/ADT/APFloat.h" -#include "llvm/Bitcode/Serialize.h" - -using namespace llvm; - -void APFloat::Emit(Serializer& S) const { - S.Emit(bitcastToAPInt()); -} Removed: llvm/trunk/lib/Bitcode/Writer/SerializeAPInt.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Writer/SerializeAPInt.cpp?rev=92373&view=auto ============================================================================== --- llvm/trunk/lib/Bitcode/Writer/SerializeAPInt.cpp (original) +++ llvm/trunk/lib/Bitcode/Writer/SerializeAPInt.cpp (removed) @@ -1,31 +0,0 @@ -//===-- SerializeAPInt.cpp - Serialization for APInts ----------*- C++ -*--===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements serialization of APInts. -// -//===----------------------------------------------------------------------===// - -#include "llvm/ADT/APInt.h" -#include "llvm/Bitcode/Serialize.h" -#include - -using namespace llvm; - -void APInt::Emit(Serializer& S) const { - S.EmitInt(BitWidth); - - if (isSingleWord()) - S.EmitInt(VAL); - else { - uint32_t NumWords = getNumWords(); - S.EmitInt(NumWords); - for (unsigned i = 0; i < NumWords; ++i) - S.EmitInt(pVal[i]); - } -} From sabre at nondot.org Thu Dec 31 18:01:35 2009 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 00:01:35 -0000 Subject: [llvm-commits] [llvm] r92375 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <201001010001.o0101Z5k011878@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 18:01:34 2009 New Revision: 92375 URL: http://llvm.org/viewvc/llvm-project?rev=92375&view=rev Log: switch from std::map to DenseMap for rank data structures. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92375&r1=92374&r2=92375&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 18:01:34 2009 @@ -37,7 +37,6 @@ #include "llvm/ADT/Statistic.h" #include "llvm/ADT/DenseMap.h" #include -#include using namespace llvm; STATISTIC(NumLinear , "Number of insts linearized"); @@ -73,8 +72,8 @@ namespace { class Reassociate : public FunctionPass { - std::map RankMap; - std::map, unsigned> ValueRankMap; + DenseMap RankMap; + DenseMap, unsigned> ValueRankMap; bool MadeChange; public: static char ID; // Pass identification, replacement for typeid @@ -163,13 +162,14 @@ } unsigned Reassociate::getRank(Value *V) { - if (isa(V)) return ValueRankMap[V]; // Function argument... - Instruction *I = dyn_cast(V); - if (I == 0) return 0; // Otherwise it's a global or constant, rank 0. + if (I == 0) { + if (isa(V)) return ValueRankMap[V]; // Function argument. + return 0; // Otherwise it's a global or constant, rank 0. + } - unsigned &CachedRank = ValueRankMap[I]; - if (CachedRank) return CachedRank; // Rank already known? + if (unsigned Rank = ValueRankMap[I]) + return Rank; // Rank already known? // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that // we can reassociate expressions for code motion! Since we do not recurse @@ -189,7 +189,7 @@ //DEBUG(errs() << "Calculated Rank[" << V->getName() << "] = " // << Rank << "\n"); - return CachedRank = Rank; + return ValueRankMap[I] = Rank; } /// isReassociableOp - Return true if V is an instruction of the specified @@ -204,7 +204,7 @@ /// LowerNegateToMultiply - Replace 0-X with X*-1. /// static Instruction *LowerNegateToMultiply(Instruction *Neg, - std::map, unsigned> &ValueRankMap) { + DenseMap, unsigned> &ValueRankMap) { Constant *Cst = Constant::getAllOnesValue(Neg->getType()); Instruction *Res = BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg); @@ -463,7 +463,7 @@ /// only used by an add, transform this into (X+(0-Y)) to promote better /// reassociation. static Instruction *BreakUpSubtract(Instruction *Sub, - std::map, unsigned> &ValueRankMap) { + DenseMap, unsigned> &ValueRankMap) { // Convert a subtract into an add and a neg instruction... so that sub // instructions can be commuted with other add instructions... // @@ -488,7 +488,7 @@ /// by one, change this into a multiply by a constant to assist with further /// reassociation. static Instruction *ConvertShiftToMul(Instruction *Shl, - std::map, unsigned> &ValueRankMap) { + DenseMap, unsigned> &ValueRankMap) { // If an operand of this shift is a reassociable multiply, or if the shift // is used by a reassociable multiply or add, turn into a multiply. if (isReassociableOp(Shl->getOperand(0), Instruction::Mul) || @@ -998,7 +998,7 @@ for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) ReassociateBB(FI); - // We are done with the rank map... + // We are done with the rank map. RankMap.clear(); ValueRankMap.clear(); return MadeChange; From sabre at nondot.org Thu Dec 31 18:04:26 2009 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 00:04:26 -0000 Subject: [llvm-commits] [llvm] r92377 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <201001010004.o0104QpM011978@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 18:04:26 2009 New Revision: 92377 URL: http://llvm.org/viewvc/llvm-project?rev=92377&view=rev Log: clean up some comments. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92377&r1=92376&r2=92377&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 18:04:26 2009 @@ -8,7 +8,7 @@ //===----------------------------------------------------------------------===// // // This pass reassociates commutative expressions in an order that is designed -// to promote better constant propagation, GCSE, LICM, PRE... +// to promote better constant propagation, GCSE, LICM, PRE, etc. // // For example: 4 + (x + 5) -> x + (4 + 5) // @@ -386,7 +386,7 @@ // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate // the constants. We assume that instcombine will clean up the mess later if - // we introduce tons of unnecessary negation instructions... + // we introduce tons of unnecessary negation instructions. // if (Instruction *I = dyn_cast(V)) if (I->getOpcode() == Instruction::Add && I->hasOneUse()) { @@ -464,11 +464,11 @@ /// reassociation. static Instruction *BreakUpSubtract(Instruction *Sub, DenseMap, unsigned> &ValueRankMap) { - // Convert a subtract into an add and a neg instruction... so that sub - // instructions can be commuted with other add instructions... + // Convert a subtract into an add and a neg instruction. This allows sub + // instructions to be commuted with other add instructions. // - // Calculate the negative value of Operand 1 of the sub instruction... - // and set it as the RHS of the add instruction we just made... + // Calculate the negative value of Operand 1 of the sub instruction, + // and set it as the RHS of the add instruction we just made. // Value *NegVal = NegateValue(Sub->getOperand(1), Sub); Instruction *New = @@ -628,7 +628,7 @@ if (e == 2) return Constant::getNullValue(Ops[0].Op->getType()); - // ... X^X -> ... + // Y ^ X^X -> Y Ops.erase(Ops.begin()+i, Ops.begin()+i+2); i -= 1; e -= 2; ++NumAnnihil; @@ -821,27 +821,27 @@ switch (Opcode) { default: break; case Instruction::And: - if (CstVal->isZero()) // ... & 0 -> 0 + if (CstVal->isZero()) // X & 0 -> 0 return CstVal; - if (CstVal->isAllOnesValue()) // ... & -1 -> ... + if (CstVal->isAllOnesValue()) // X & -1 -> X Ops.pop_back(); break; case Instruction::Mul: - if (CstVal->isZero()) { // ... * 0 -> 0 + if (CstVal->isZero()) { // X * 0 -> 0 ++NumAnnihil; return CstVal; } if (cast(CstVal)->isOne()) - Ops.pop_back(); // ... * 1 -> ... + Ops.pop_back(); // X * 1 -> X break; case Instruction::Or: - if (CstVal->isAllOnesValue()) // ... | -1 -> -1 + if (CstVal->isAllOnesValue()) // X | -1 -> -1 return CstVal; // FALLTHROUGH! case Instruction::Add: case Instruction::Xor: - if (CstVal->isZero()) // ... [|^+] 0 -> ... + if (CstVal->isZero()) // X [|^+] 0 -> X Ops.pop_back(); break; } From kremenek at apple.com Thu Dec 31 18:04:49 2009 From: kremenek at apple.com (Ted Kremenek) Date: Fri, 01 Jan 2010 00:04:49 -0000 Subject: [llvm-commits] [llvm] r92378 - /llvm/trunk/include/llvm/Bitcode/Deserialize.h Message-ID: <201001010004.o0104nm8012021@zion.cs.uiuc.edu> Author: kremenek Date: Thu Dec 31 18:04:49 2009 New Revision: 92378 URL: http://llvm.org/viewvc/llvm-project?rev=92378&view=rev Log: Remove old header. Removed: llvm/trunk/include/llvm/Bitcode/Deserialize.h Removed: llvm/trunk/include/llvm/Bitcode/Deserialize.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Bitcode/Deserialize.h?rev=92377&view=auto ============================================================================== --- llvm/trunk/include/llvm/Bitcode/Deserialize.h (original) +++ llvm/trunk/include/llvm/Bitcode/Deserialize.h (removed) @@ -1,516 +0,0 @@ -//=- Deserialize.h - Generic Object Deserialization from Bitcode --*- C++ -*-=// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the interface for generic object deserialization from -// LLVM bitcode. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_BITCODE_SERIALIZE_INPUT -#define LLVM_BITCODE_SERIALIZE_INPUT - -#include "llvm/Bitcode/BitstreamReader.h" -#include "llvm/Bitcode/Serialization.h" -#include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/Support/Allocator.h" -#include "llvm/System/DataTypes.h" -#include - -namespace llvm { - -struct BPNode { - BPNode* Next; - uintptr_t& PtrRef; - - BPNode(BPNode* n, uintptr_t& pref) - : Next(n), PtrRef(pref) { - PtrRef = 0; - } -}; - -struct BPEntry { - union { BPNode* Head; void* Ptr; }; - BPEntry() : Head(NULL) {} - void SetPtr(BPNode*& FreeList, void* P); -}; - -class BPKey { - unsigned Raw; -public: - BPKey(SerializedPtrID PtrId) : Raw(PtrId << 1) { assert (PtrId > 0); } - BPKey(unsigned code, unsigned) : Raw(code) {} - - void MarkFinal() { Raw |= 0x1; } - bool hasFinalPtr() const { return Raw & 0x1 ? true : false; } - SerializedPtrID getID() const { return Raw >> 1; } - - static inline BPKey getEmptyKey() { return BPKey(0,0); } - static inline BPKey getTombstoneKey() { return BPKey(1,0); } - static inline unsigned getHashValue(const BPKey& K) { return K.Raw & ~0x1; } - - static bool isEqual(const BPKey& K1, const BPKey& K2) { - return (K1.Raw ^ K2.Raw) & ~0x1 ? false : true; - } -}; - -template <> -struct isPodLike { static const bool value = true; }; -template <> -struct isPodLike { static const bool value = true; }; - -class Deserializer { - - //===----------------------------------------------------------===// - // Internal type definitions. - //===----------------------------------------------------------===// - - - typedef llvm::DenseMap MapTy; - - //===----------------------------------------------------------===// - // Publicly visible types. - //===----------------------------------------------------------===// - -public: - struct Location { - uint64_t BitNo; - unsigned BlockID; - unsigned NumWords; - - Location(uint64_t bit, unsigned bid, unsigned words) - : BitNo(bit), BlockID(bid), NumWords(words) {} - - Location() : BitNo(0), BlockID(0), NumWords(0) {} - - Location& operator=(Location& RHS) { - BitNo = RHS.BitNo; - BlockID = RHS.BlockID; - NumWords = RHS.NumWords; - return *this; - } - - bool operator==(const Location& RHS) const { return BitNo == RHS.BitNo; } - bool operator!=(const Location& RHS) const { return BitNo != RHS.BitNo; } - - bool contains(const Location& RHS) const { - if (RHS.BitNo < BitNo) - return false; - - if ((RHS.BitNo - BitNo) >> 5 < NumWords) - return true; - - return false; - } - }; - - //===----------------------------------------------------------===// - // Internal data members. - //===----------------------------------------------------------===// - -private: - BitstreamCursor Stream; - SmallVector Record; - unsigned RecIdx; - BumpPtrAllocator Allocator; - BPNode* FreeList; - MapTy BPatchMap; - llvm::SmallVector BlockStack; - unsigned AbbrevNo; - unsigned RecordCode; - uint64_t StreamStart; - - //===----------------------------------------------------------===// - // Public Interface. - //===----------------------------------------------------------===// - -public: - Deserializer(BitstreamReader& stream); - ~Deserializer(); - - uint64_t ReadInt(); - int64_t ReadSInt(); - SerializedPtrID ReadPtrID() { return (SerializedPtrID) ReadInt(); } - - - bool ReadBool() { - return ReadInt() ? true : false; - } - - template - inline T& Read(T& X) { - SerializeTrait::Read(*this,X); - return X; - } - - template - inline T* Create() { - return SerializeTrait::Create(*this); - } - - char* ReadCStr(char* cstr = NULL, unsigned MaxLen=0, bool isNullTerm=true); - void ReadCStr(std::vector& buff, bool isNullTerm=false, unsigned Idx=0); - - template - inline T* ReadOwnedPtr(bool AutoRegister = true) { - SerializedPtrID PtrID = ReadPtrID(); - - if (!PtrID) - return NULL; - - T* x = SerializeTrait::Create(*this); - - if (AutoRegister) - RegisterPtr(PtrID,x); - - return x; - } - - template - inline T* ReadOwnedPtr(Arg1& arg1, bool AutoRegister = true) { - SerializedPtrID PtrID = ReadPtrID(); - - if (!PtrID) - return NULL; - - T* x = SerializeTrait::Create(*this, arg1); - - if (AutoRegister) - RegisterPtr(PtrID,x); - - return x; - } - - template - inline void ReadOwnedPtr(T*& Ptr, bool AutoRegister = true) { - Ptr = ReadOwnedPtr(AutoRegister); - } - - template - void BatchReadOwnedPtrs(T1*& P1, T2*& P2, - bool A1=true, bool A2=true) { - - SerializedPtrID ID1 = ReadPtrID(); - SerializedPtrID ID2 = ReadPtrID(); - - P1 = (ID1) ? SerializeTrait::Create(*this) : NULL; - if (ID1 && A1) RegisterPtr(ID1,P1); - - P2 = (ID2) ? SerializeTrait::Create(*this) : NULL; - if (ID2 && A2) RegisterPtr(ID2,P2); - } - - template - void BatchReadOwnedPtrs(T1*& P1, T2*& P2, Arg1& arg1, - bool A1=true, bool A2=true) { - - SerializedPtrID ID1 = ReadPtrID(); - SerializedPtrID ID2 = ReadPtrID(); - - P1 = (ID1) ? SerializeTrait::Create(*this, arg1) : NULL; - if (ID1 && A1) RegisterPtr(ID1,P1); - - P2 = (ID2) ? SerializeTrait::Create(*this, arg1) : NULL; - if (ID2 && A2) RegisterPtr(ID2,P2); - } - - template - void BatchReadOwnedPtrs(T1*& P1, T2*& P2, T3*& P3, - bool A1=true, bool A2=true, bool A3=true) { - - SerializedPtrID ID1 = ReadPtrID(); - SerializedPtrID ID2 = ReadPtrID(); - SerializedPtrID ID3 = ReadPtrID(); - - P1 = (ID1) ? SerializeTrait::Create(*this) : NULL; - if (ID1 && A1) RegisterPtr(ID1,P1); - - P2 = (ID2) ? SerializeTrait::Create(*this) : NULL; - if (ID2 && A2) RegisterPtr(ID2,P2); - - P3 = (ID3) ? SerializeTrait::Create(*this) : NULL; - if (ID3 && A3) RegisterPtr(ID3,P3); - } - - template - void BatchReadOwnedPtrs(T1*& P1, T2*& P2, T3*& P3, Arg1& arg1, - bool A1=true, bool A2=true, bool A3=true) { - - SerializedPtrID ID1 = ReadPtrID(); - SerializedPtrID ID2 = ReadPtrID(); - SerializedPtrID ID3 = ReadPtrID(); - - P1 = (ID1) ? SerializeTrait::Create(*this, arg1) : NULL; - if (ID1 && A1) RegisterPtr(ID1,P1); - - P2 = (ID2) ? SerializeTrait::Create(*this, arg1) : NULL; - if (ID2 && A2) RegisterPtr(ID2,P2); - - P3 = (ID3) ? SerializeTrait::Create(*this, arg1) : NULL; - if (ID3 && A3) RegisterPtr(ID3,P3); - } - - template - void BatchReadOwnedPtrs(unsigned NumPtrs, T** Ptrs, bool AutoRegister=true) { - llvm::SmallVector BatchIDVec; - - for (unsigned i = 0; i < NumPtrs; ++i) - BatchIDVec.push_back(ReadPtrID()); - - for (unsigned i = 0; i < NumPtrs; ++i) { - SerializedPtrID& PtrID = BatchIDVec[i]; - - T* p = PtrID ? SerializeTrait::Create(*this) : NULL; - - if (PtrID && AutoRegister) - RegisterPtr(PtrID,p); - - Ptrs[i] = p; - } - } - - template - void BatchReadOwnedPtrs(unsigned NumPtrs, T** Ptrs, Arg1& arg1, - bool AutoRegister=true) { - - llvm::SmallVector BatchIDVec; - - for (unsigned i = 0; i < NumPtrs; ++i) - BatchIDVec.push_back(ReadPtrID()); - - for (unsigned i = 0; i < NumPtrs; ++i) { - SerializedPtrID& PtrID = BatchIDVec[i]; - - T* p = PtrID ? SerializeTrait::Create(*this, arg1) : NULL; - - if (PtrID && AutoRegister) - RegisterPtr(PtrID,p); - - Ptrs[i] = p; - } - } - - template - void BatchReadOwnedPtrs(unsigned NumT1Ptrs, T1** Ptrs, T2*& P2, - bool A1=true, bool A2=true) { - - llvm::SmallVector BatchIDVec; - - for (unsigned i = 0; i < NumT1Ptrs; ++i) - BatchIDVec.push_back(ReadPtrID()); - - SerializedPtrID ID2 = ReadPtrID(); - - for (unsigned i = 0; i < NumT1Ptrs; ++i) { - SerializedPtrID& PtrID = BatchIDVec[i]; - - T1* p = PtrID ? SerializeTrait::Create(*this) : NULL; - - if (PtrID && A1) - RegisterPtr(PtrID,p); - - Ptrs[i] = p; - } - - P2 = (ID2) ? SerializeTrait::Create(*this) : NULL; - if (ID2 && A2) RegisterPtr(ID2,P2); - } - - template - void BatchReadOwnedPtrs(unsigned NumT1Ptrs, T1** Ptrs, T2*& P2, Arg1& arg1, - bool A1=true, bool A2=true) { - - llvm::SmallVector BatchIDVec; - - for (unsigned i = 0; i < NumT1Ptrs; ++i) - BatchIDVec.push_back(ReadPtrID()); - - SerializedPtrID ID2 = ReadPtrID(); - - for (unsigned i = 0; i < NumT1Ptrs; ++i) { - SerializedPtrID& PtrID = BatchIDVec[i]; - - T1* p = PtrID ? SerializeTrait::Create(*this, arg1) : NULL; - - if (PtrID && A1) - RegisterPtr(PtrID,p); - - Ptrs[i] = p; - } - - P2 = (ID2) ? SerializeTrait::Create(*this, arg1) : NULL; - if (ID2 && A2) RegisterPtr(ID2,P2); - } - - template - void BatchReadOwnedPtrs(unsigned NumT1Ptrs, T1** Ptrs, - T2*& P2, T3*& P3, - bool A1=true, bool A2=true, bool A3=true) { - - llvm::SmallVector BatchIDVec; - - for (unsigned i = 0; i < NumT1Ptrs; ++i) - BatchIDVec.push_back(ReadPtrID()); - - SerializedPtrID ID2 = ReadPtrID(); - SerializedPtrID ID3 = ReadPtrID(); - - for (unsigned i = 0; i < NumT1Ptrs; ++i) { - SerializedPtrID& PtrID = BatchIDVec[i]; - - T1* p = PtrID ? SerializeTrait::Create(*this) : NULL; - - if (PtrID && A1) - RegisterPtr(PtrID,p); - - Ptrs[i] = p; - } - - P2 = (ID2) ? SerializeTrait::Create(*this) : NULL; - if (ID2 && A2) RegisterPtr(ID2,P2); - - P3 = (ID3) ? SerializeTrait::Create(*this) : NULL; - if (ID3 && A3) RegisterPtr(ID3,P3); - } - - template - void BatchReadOwnedPtrs(unsigned NumT1Ptrs, T1** Ptrs, - T2*& P2, T3*& P3, Arg1& arg1, - bool A1=true, bool A2=true, bool A3=true) { - - llvm::SmallVector BatchIDVec; - - for (unsigned i = 0; i < NumT1Ptrs; ++i) - BatchIDVec.push_back(ReadPtrID()); - - SerializedPtrID ID2 = ReadPtrID(); - SerializedPtrID ID3 = ReadPtrID(); - - for (unsigned i = 0; i < NumT1Ptrs; ++i) { - SerializedPtrID& PtrID = BatchIDVec[i]; - - T1* p = PtrID ? SerializeTrait::Create(*this, arg1) : NULL; - - if (PtrID && A1) - RegisterPtr(PtrID,p); - - Ptrs[i] = p; - } - - P2 = (ID2) ? SerializeTrait::Create(*this, arg1) : NULL; - if (ID2 && A2) RegisterPtr(ID2,P2); - - P3 = (ID3) ? SerializeTrait::Create(*this, arg1) : NULL; - if (ID3 && A3) RegisterPtr(ID3,P3); - } - - template - void ReadPtr(T*& PtrRef, bool AllowBackpatch = true) { - ReadUIntPtr(reinterpret_cast(PtrRef), AllowBackpatch); - } - - template - void ReadPtr(const T*& PtrRef, bool AllowBackpatch = true) { - ReadPtr(const_cast(PtrRef), AllowBackpatch); - } - - - template - void ReadPtr(T*& PtrRef, const SerializedPtrID& PtrID, - bool AllowBackpatch = true) { - ReadUIntPtr(reinterpret_cast(PtrRef), PtrID, AllowBackpatch); - } - - template - void ReadPtr(const T*& PtrRef, const SerializedPtrID& PtrID, - bool AllowBackpatch = true) { - - ReadPtr(const_cast(PtrRef), PtrID, AllowBackpatch); - } - - template - T* ReadPtr() { T* x = 0; ReadPtr(x,false); return x; } - - void ReadUIntPtr(uintptr_t& PtrRef, const SerializedPtrID& PtrID, - bool AllowBackpatch = true); - - void ReadUIntPtr(uintptr_t& PtrRef, bool AllowBackpatch = true) { - ReadUIntPtr(PtrRef,ReadPtrID(),AllowBackpatch); - } - - template - T& ReadRef() { - T* p = reinterpret_cast(ReadInternalRefPtr()); - return *p; - } - - void RegisterPtr(const SerializedPtrID& PtrID, const void* Ptr); - - void RegisterPtr(const void* Ptr) { - RegisterPtr(ReadPtrID(),Ptr); - } - - template - void RegisterRef(const T& x) { - RegisterPtr(&x); - } - - template - void RegisterRef(const SerializedPtrID& PtrID, const T& x) { - RegisterPtr(PtrID,&x); - } - - Location getCurrentBlockLocation(); - unsigned getCurrentBlockID(); - unsigned getAbbrevNo(); - - bool FinishedBlock(Location BlockLoc); - bool JumpTo(const Location& BlockLoc); - void Rewind(); - - bool AtEnd(); - bool inRecord(); - void SkipBlock(); - bool SkipToBlock(unsigned BlockID); - - unsigned getRecordCode(); - - BitstreamCursor &getStream() { return Stream; } - -private: - bool AdvanceStream(); - void ReadRecord(); - - uintptr_t ReadInternalRefPtr(); - - static inline bool HasFinalPtr(MapTy::value_type& V) { - return V.first.hasFinalPtr(); - } - - static inline uintptr_t GetFinalPtr(MapTy::value_type& V) { - return reinterpret_cast(V.second.Ptr); - } - - static inline BPNode* GetBPNode(MapTy::value_type& V) { - return V.second.Head; - } - - static inline void SetBPNode(MapTy::value_type& V, BPNode* N) { - V.second.Head = N; - } - - void SetPtr(MapTy::value_type& V, const void* P) { - V.first.MarkFinal(); - V.second.SetPtr(FreeList,const_cast(P)); - } -}; - -} // end namespace llvm - -#endif From sabre at nondot.org Thu Dec 31 18:50:00 2009 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 00:50:00 -0000 Subject: [llvm-commits] [llvm] r92380 - /llvm/trunk/test/Transforms/Reassociate/basictest.ll Message-ID: <201001010050.o010o1ff013424@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 18:50:00 2009 New Revision: 92380 URL: http://llvm.org/viewvc/llvm-project?rev=92380&view=rev Log: test case we alredy get right. Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest.ll?rev=92380&r1=92379&r2=92380&view=diff ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest.ll Thu Dec 31 18:50:00 2009 @@ -179,3 +179,15 @@ ; CHECK-NEXT: ret i32 } +define i32 @test13(i32 %X1, i32 %X2, i32 %X3) { + %A = sub i32 0, %X1 + %B = mul i32 %A, %X2 ; -X1*X2 + %C = mul i32 %X1, %X3 ; X1*X3 + %D = add i32 %B, %C ; -X1*X2 + X1*X3 -> X1*(X3-X2) + ret i32 %D +; CHECK: @test13 +; CHECK-NEXT: sub i32 %X3, %X2 +; CHECK-NEXT: mul i32 {{.*}}, %X1 +; CHECK-NEXT: ret i32 +} + From sabre at nondot.org Thu Dec 31 19:13:15 2009 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 01:13:15 -0000 Subject: [llvm-commits] [llvm] r92381 - in /llvm/trunk: lib/Transforms/Scalar/Reassociate.cpp test/Transforms/Reassociate/basictest.ll Message-ID: <201001010113.o011DFd9014151@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 19:13:15 2009 New Revision: 92381 URL: http://llvm.org/viewvc/llvm-project?rev=92381&view=rev Log: When factoring multiply expressions across adds, factor both positive and negative forms of constants together. This allows us to compile: int foo(int x, int y) { return (x-y) + (x-y) + (x-y); } into: _foo: ## @foo subl %esi, %edi leal (%rdi,%rdi,2), %eax ret instead of (where the 3 and -3 were not factored): _foo: imull $-3, 8(%esp), %ecx imull $3, 4(%esp), %eax addl %ecx, %eax ret this started out as: movl 12(%ebp), %ecx imull $3, 8(%ebp), %eax subl %ecx, %eax subl %ecx, %eax subl %ecx, %eax ret This comes from PR5359. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp llvm/trunk/test/Transforms/Reassociate/basictest.ll Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92381&r1=92380&r2=92381&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Thu Dec 31 19:13:15 2009 @@ -510,7 +510,8 @@ } // Scan backwards and forwards among values with the same rank as element i to -// see if X exists. If X does not exist, return i. +// see if X exists. If X does not exist, return i. This is useful when +// scanning for 'x' when we see '-x' because they both get the same rank. static unsigned FindInOperandList(SmallVectorImpl &Ops, unsigned i, Value *X) { unsigned XRank = Ops[i].Rank; @@ -518,7 +519,7 @@ for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) if (Ops[j].Op == X) return j; - // Scan backwards + // Scan backwards. for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) if (Ops[j].Op == X) return j; @@ -547,28 +548,47 @@ LinearizeExprTree(BO, Factors); bool FoundFactor = false; - for (unsigned i = 0, e = Factors.size(); i != e; ++i) + bool NeedsNegate = false; + for (unsigned i = 0, e = Factors.size(); i != e; ++i) { if (Factors[i].Op == Factor) { FoundFactor = true; Factors.erase(Factors.begin()+i); break; } + + // If this is a negative version of this factor, remove it. + if (ConstantInt *FC1 = dyn_cast(Factor)) + if (ConstantInt *FC2 = dyn_cast(Factors[i].Op)) + if (FC1->getValue() == -FC2->getValue()) { + FoundFactor = NeedsNegate = true; + Factors.erase(Factors.begin()+i); + break; + } + } + if (!FoundFactor) { // Make sure to restore the operands to the expression tree. RewriteExprTree(BO, Factors); return 0; } + BasicBlock::iterator InsertPt = BO; ++InsertPt; + // If this was just a single multiply, remove the multiply and return the only // remaining operand. if (Factors.size() == 1) { ValueRankMap.erase(BO); BO->eraseFromParent(); - return Factors[0].Op; + V = Factors[0].Op; + } else { + RewriteExprTree(BO, Factors); + V = BO; } - RewriteExprTree(BO, Factors); - return BO; + if (NeedsNegate) + V = BinaryOperator::CreateNeg(V, "neg", InsertPt); + + return V; } /// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively @@ -645,6 +665,9 @@ // Scan the operand lists looking for X and -X pairs. If we find any, we // can simplify the expression. X+-X == 0. While we're at it, scan for any // duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z. + // + // TODO: We could handle "X + ~X" -> "-1" if we wanted, since "-X = ~X+1". + // for (unsigned i = 0, e = Ops.size(); i != e; ++i) { Value *TheOp = Ops[i].Op; // Check to see if we've seen this operand before. If so, we factor all @@ -730,21 +753,26 @@ assert(Factors.size() > 1 && "Bad linearize!"); // Add one to FactorOccurrences for each unique factor in this op. - if (Factors.size() == 2) { - unsigned Occ = ++FactorOccurrences[Factors[0]]; - if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[0]; } - if (Factors[0] != Factors[1]) { // Don't double count A*A. - Occ = ++FactorOccurrences[Factors[1]]; - if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[1]; } - } - } else { - SmallPtrSet Duplicates; - for (unsigned i = 0, e = Factors.size(); i != e; ++i) { - if (!Duplicates.insert(Factors[i])) continue; - - unsigned Occ = ++FactorOccurrences[Factors[i]]; - if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[i]; } - } + SmallPtrSet Duplicates; + for (unsigned i = 0, e = Factors.size(); i != e; ++i) { + Value *Factor = Factors[i]; + if (!Duplicates.insert(Factor)) continue; + + unsigned Occ = ++FactorOccurrences[Factor]; + if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; } + + // If Factor is a negative constant, add the negated value as a factor + // because we can percolate the negate out. Watch for minint, which + // cannot be positivified. + if (ConstantInt *CI = dyn_cast(Factor)) + if (CI->getValue().isNegative() && !CI->getValue().isMinSignedValue()) { + Factor = ConstantInt::get(CI->getContext(), -CI->getValue()); + assert(!Duplicates.count(Factor) && + "Shouldn't have two constant factors, missed a canonicalize"); + + unsigned Occ = ++FactorOccurrences[Factor]; + if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; } + } } } Modified: llvm/trunk/test/Transforms/Reassociate/basictest.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/Reassociate/basictest.ll?rev=92381&r1=92380&r2=92381&view=diff ============================================================================== --- llvm/trunk/test/Transforms/Reassociate/basictest.ll (original) +++ llvm/trunk/test/Transforms/Reassociate/basictest.ll Thu Dec 31 19:13:15 2009 @@ -191,3 +191,16 @@ ; CHECK-NEXT: ret i32 } +; PR5359 +define i32 @test14(i32 %X1, i32 %X2) { + %B = mul i32 %X1, 47 ; X1*47 + %C = mul i32 %X2, -47 ; X2*-47 + %D = add i32 %B, %C ; X1*47 + X2*-47 -> 47*(X1-X2) + ret i32 %D +; CHECK: @test14 +; CHECK-NEXT: sub i32 %X1, %X2 +; CHECK-NEXT: mul i32 {{.*}}, 47 +; CHECK-NEXT: ret i32 +} + + From sabre at nondot.org Thu Dec 31 19:29:26 2009 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 01:29:26 -0000 Subject: [llvm-commits] [llvm] r92382 - /llvm/trunk/lib/Target/README.txt Message-ID: <201001010129.o011TQQt014628@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 19:29:26 2009 New Revision: 92382 URL: http://llvm.org/viewvc/llvm-project?rev=92382&view=rev Log: update this. To take the next step, llvm.powi should be generalized to work on integers as well and codegen should lower them to branch trees. Modified: llvm/trunk/lib/Target/README.txt Modified: llvm/trunk/lib/Target/README.txt URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/README.txt?rev=92382&r1=92381&r2=92382&view=diff ============================================================================== --- llvm/trunk/lib/Target/README.txt (original) +++ llvm/trunk/lib/Target/README.txt Thu Dec 31 19:29:26 2009 @@ -106,7 +106,17 @@ //===---------------------------------------------------------------------===// -Reassociate should turn: X*X*X*X -> t=(X*X) (t*t) to eliminate a multiply. +Reassociate should turn things like: + +int factorial(int X) { + return X*X*X*X*X*X*X*X; +} + +into llvm.powi calls, allowing the code generator to produce balanced +multiplication trees. + +First, the intrinsic needs to be extended to support integers, and second the +code generator needs to be enhanced to lower these to multiplication trees. //===---------------------------------------------------------------------===// @@ -119,7 +129,32 @@ return bar(z, n) + bar(2*z, 2*n); } -Reassociate should handle the example in GCC PR16157. +This is blocked on not handling X*X*X -> powi(X, 3) (see note above). The issue +is that we end up getting t = 2*X s = t*t and don't turn this into 4*X*X, +which is the same number of multiplies and is canonical, because the 2*X has +multiple uses. Here's a simple example: + +define i32 @test15(i32 %X1) { + %B = mul i32 %X1, 47 ; X1*47 + %C = mul i32 %B, %B + ret i32 %C +} + + +//===---------------------------------------------------------------------===// + +Reassociate should handle the example in GCC PR16157: + +extern int a0, a1, a2, a3, a4; extern int b0, b1, b2, b3, b4; +void f () { /* this can be optimized to four additions... */ + b4 = a4 + a3 + a2 + a1 + a0; + b3 = a3 + a2 + a1 + a0; + b2 = a2 + a1 + a0; + b1 = a1 + a0; +} + +This requires reassociating to forms of expressions that are already available, +something that reassoc doesn't think about yet. //===---------------------------------------------------------------------===// @@ -721,17 +756,6 @@ //===---------------------------------------------------------------------===// -Reassociate should turn things like: - -int factorial(int X) { - return X*X*X*X*X*X*X*X; -} - -into llvm.powi calls, allowing the code generator to produce balanced -multiplication trees. - -//===---------------------------------------------------------------------===// - We generate a horrible libcall for llvm.powi. For example, we compile: #include From sabre at nondot.org Thu Dec 31 19:52:15 2009 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 01:52:15 -0000 Subject: [llvm-commits] [llvm] r92383 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/intrinsics.ll Message-ID: <201001010152.o011qFA4015282@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 19:52:15 2009 New Revision: 92383 URL: http://llvm.org/viewvc/llvm-project?rev=92383&view=rev Log: add a few trivial instcombines for llvm.powi. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/intrinsics.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92383&r1=92382&r2=92383&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Thu Dec 31 19:52:15 2009 @@ -10140,6 +10140,20 @@ if (Operand->getIntrinsicID() == Intrinsic::bswap) return ReplaceInstUsesWith(CI, Operand->getOperand(1)); break; + case Intrinsic::powi: + if (ConstantInt *Power = dyn_cast(II->getOperand(2))) { + // powi(x, 0) -> 1.0 + if (Power->isZero()) + return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0)); + // powi(x, 1) -> x + if (Power->isOne()) + return ReplaceInstUsesWith(CI, II->getOperand(1)); + // powi(x, -1) -> 1/x + return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0), + II->getOperand(1)); + } + break; + case Intrinsic::uadd_with_overflow: { Value *LHS = II->getOperand(1), *RHS = II->getOperand(2); const IntegerType *IT = cast(II->getOperand(1)->getType()); Modified: llvm/trunk/test/Transforms/InstCombine/intrinsics.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/intrinsics.ll?rev=92383&r1=92382&r2=92383&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/intrinsics.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/intrinsics.ll Thu Dec 31 19:52:15 2009 @@ -4,6 +4,7 @@ declare %overflow.result @llvm.uadd.with.overflow.i8(i8, i8) declare %overflow.result @llvm.umul.with.overflow.i8(i8, i8) +declare double @llvm.powi.f64(double, i32) nounwind readonly define i8 @test1(i8 %A, i8 %B) { %x = call %overflow.result @llvm.uadd.with.overflow.i8(i8 %A, i8 %B) @@ -77,3 +78,24 @@ ; CHECK-NEXT: store i1 false, i1* %overflowPtr ; CHECK-NEXT: ret i8 %A } + + +define void @powi(double %V, double *%P) { +entry: + %A = tail call double @llvm.powi.f64(double %V, i32 -1) nounwind + volatile store double %A, double* %P + + %B = tail call double @llvm.powi.f64(double %V, i32 0) nounwind + volatile store double %B, double* %P + + %C = tail call double @llvm.powi.f64(double %V, i32 1) nounwind + volatile store double %C, double* %P + ret void +; CHECK: @powi +; CHECK: %A = fdiv double 1.0{{.*}}, %V +; CHECK: volatile store double %A, +; CHECK: volatile store double 1.0 +; CHECK: volatile store double %V +} + + From sabre at nondot.org Thu Dec 31 19:54:08 2009 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 01:54:08 -0000 Subject: [llvm-commits] [llvm] r92384 - /llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Message-ID: <201001010154.o011s8EZ015358@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 19:54:08 2009 New Revision: 92384 URL: http://llvm.org/viewvc/llvm-project?rev=92384&view=rev Log: add missing line. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92384&r1=92383&r2=92384&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Thu Dec 31 19:54:08 2009 @@ -10149,8 +10149,9 @@ if (Power->isOne()) return ReplaceInstUsesWith(CI, II->getOperand(1)); // powi(x, -1) -> 1/x - return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0), - II->getOperand(1)); + if (Power->isAllOnesValue()) + return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0), + II->getOperand(1)); } break; From sabre at nondot.org Thu Dec 31 21:26:52 2009 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 03:26:52 -0000 Subject: [llvm-commits] [llvm] r92387 - /llvm/trunk/test/CodeGen/ARM/fpowi.ll Message-ID: <201001010326.o013Qqul017862@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 21:26:51 2009 New Revision: 92387 URL: http://llvm.org/viewvc/llvm-project?rev=92387&view=rev Log: Make this more likely to generate a libcall. Modified: llvm/trunk/test/CodeGen/ARM/fpowi.ll Modified: llvm/trunk/test/CodeGen/ARM/fpowi.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/ARM/fpowi.ll?rev=92387&r1=92386&r2=92387&view=diff ============================================================================== --- llvm/trunk/test/CodeGen/ARM/fpowi.ll (original) +++ llvm/trunk/test/CodeGen/ARM/fpowi.ll Thu Dec 31 21:26:51 2009 @@ -7,9 +7,8 @@ define double @_ZSt3powdi(double %__x, i32 %__i) { entry: - %tmp3 = call double @llvm.powi.f64( double 0.000000e+00, i32 0 ) ; [#uses=1] - store double %tmp3, double* null, align 8 - unreachable + %tmp3 = call double @llvm.powi.f64( double %__x, i32 %__i ) + ret double %tmp3 } declare double @llvm.powi.f64(double, i32) From sabre at nondot.org Thu Dec 31 21:32:17 2009 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 03:32:17 -0000 Subject: [llvm-commits] [llvm] r92388 - in /llvm/trunk: lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp lib/Target/README.txt test/CodeGen/X86/2007-09-27-LDIntrinsics.ll test/CodeGen/X86/powi.ll Message-ID: <201001010332.o013WHnE018023@zion.cs.uiuc.edu> Author: lattner Date: Thu Dec 31 21:32:16 2009 New Revision: 92388 URL: http://llvm.org/viewvc/llvm-project?rev=92388&view=rev Log: Teach codegen to lower llvm.powi to an efficient (but not optimal) multiply sequence when the power is a constant integer. Before, our codegen for std::pow(.., int) always turned into a libcall, which was really inefficient. This should also make many gfortran programs happier I'd imagine. Added: llvm/trunk/test/CodeGen/X86/powi.ll Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp llvm/trunk/lib/Target/README.txt llvm/trunk/test/CodeGen/X86/2007-09-27-LDIntrinsics.ll Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp?rev=92388&r1=92387&r2=92388&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Thu Dec 31 21:32:16 2009 @@ -462,7 +462,8 @@ // The number of parts is a power of 2. Repeatedly bisect the value using // EXTRACT_ELEMENT. Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl, - EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()), + EVT::getIntegerVT(*DAG.getContext(), + ValueVT.getSizeInBits()), Val); if (DisableScheduling) @@ -4261,6 +4262,59 @@ setValue(&I, result); } + +/// ExpandPowI - Expand a llvm.powi intrinsic. +static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS, + SelectionDAG &DAG) { + // If RHS is a constant, we can expand this out to a multiplication tree, + // otherwise we end up lowering to a call to __powidf2 (for example). When + // optimizing for size, we only want to do this if the expansion would produce + // a small number of multiplies, otherwise we do the full expansion. + if (ConstantSDNode *RHSC = dyn_cast(RHS)) { + // Get the exponent as a positive value. + unsigned Val = RHSC->getSExtValue(); + if ((int)Val < 0) Val = -Val; + + // powi(x, 0) -> 1.0 + if (Val == 0) + return DAG.getConstantFP(1.0, LHS.getValueType()); + + Function *F = DAG.getMachineFunction().getFunction(); + if (!F->hasFnAttr(Attribute::OptimizeForSize) || + // If optimizing for size, don't insert too many multiplies. This + // inserts up to 5 multiplies. + CountPopulation_32(Val)+Log2_32(Val) < 7) { + // We use the simple binary decomposition method to generate the multiply + // sequence. There are more optimal ways to do this (for example, + // powi(x,15) generates one more multiply than it should), but this has + // the benefit of being both really simple and much better than a libcall. + SDValue Res; // Logically starts equal to 1.0 + SDValue CurSquare = LHS; + while (Val) { + if (Val & 1) + if (Res.getNode()) + Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); + else + Res = CurSquare; // 1.0*CurSquare. + + CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), + CurSquare, CurSquare); + Val >>= 1; + } + + // If the original was negative, invert the result, producing 1/(x*x*x). + if (RHSC->getSExtValue() < 0) + Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), + DAG.getConstantFP(1.0, LHS.getValueType()), Res); + return Res; + } + } + + // Otherwise, expand to a libcall. + return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); +} + + /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If /// we want to emit this as a call to a named external function, return the name /// otherwise lower it and return null. @@ -4536,10 +4590,8 @@ DAG.AssignOrdering(Res.getNode(), SDNodeOrder); return 0; case Intrinsic::powi: - Res = DAG.getNode(ISD::FPOWI, dl, - getValue(I.getOperand(1)).getValueType(), - getValue(I.getOperand(1)), - getValue(I.getOperand(2))); + Res = ExpandPowI(dl, getValue(I.getOperand(1)), getValue(I.getOperand(2)), + DAG); setValue(&I, Res); if (DisableScheduling) DAG.AssignOrdering(Res.getNode(), SDNodeOrder); Modified: llvm/trunk/lib/Target/README.txt URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Target/README.txt?rev=92388&r1=92387&r2=92388&view=diff ============================================================================== --- llvm/trunk/lib/Target/README.txt (original) +++ llvm/trunk/lib/Target/README.txt Thu Dec 31 21:32:16 2009 @@ -756,36 +756,6 @@ //===---------------------------------------------------------------------===// -We generate a horrible libcall for llvm.powi. For example, we compile: - -#include -double f(double a) { return std::pow(a, 4); } - -into: - -__Z1fd: - subl $12, %esp - movsd 16(%esp), %xmm0 - movsd %xmm0, (%esp) - movl $4, 8(%esp) - call L___powidf2$stub - addl $12, %esp - ret - -GCC produces: - -__Z1fd: - subl $12, %esp - movsd 16(%esp), %xmm0 - mulsd %xmm0, %xmm0 - mulsd %xmm0, %xmm0 - movsd %xmm0, (%esp) - fldl (%esp) - addl $12, %esp - ret - -//===---------------------------------------------------------------------===// - We compile this program: (from GCC PR11680) http://gcc.gnu.org/bugzilla/attachment.cgi?id=4487 Modified: llvm/trunk/test/CodeGen/X86/2007-09-27-LDIntrinsics.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/X86/2007-09-27-LDIntrinsics.ll?rev=92388&r1=92387&r2=92388&view=diff ============================================================================== --- llvm/trunk/test/CodeGen/X86/2007-09-27-LDIntrinsics.ll (original) +++ llvm/trunk/test/CodeGen/X86/2007-09-27-LDIntrinsics.ll Thu Dec 31 21:32:16 2009 @@ -1,47 +1,30 @@ -; RUN: llc < %s | grep powixf2 -; RUN: llc < %s | grep fsqrt -; ModuleID = 'yyy.c' +; RUN: llc < %s | FileCheck %s target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:128:128" target triple = "i686-apple-darwin8" -define x86_fp80 @foo(x86_fp80 %x) { +define x86_fp80 @foo(x86_fp80 %x) nounwind{ entry: - %x_addr = alloca x86_fp80 ; [#uses=2] - %retval = alloca x86_fp80 ; [#uses=2] - %tmp = alloca x86_fp80 ; [#uses=2] - %"alloca point" = bitcast i32 0 to i32 ; [#uses=0] - store x86_fp80 %x, x86_fp80* %x_addr - %tmp1 = load x86_fp80* %x_addr, align 16 ; [#uses=1] - %tmp2 = call x86_fp80 @llvm.sqrt.f80( x86_fp80 %tmp1 ) ; [#uses=1] - store x86_fp80 %tmp2, x86_fp80* %tmp, align 16 - %tmp3 = load x86_fp80* %tmp, align 16 ; [#uses=1] - store x86_fp80 %tmp3, x86_fp80* %retval, align 16 - br label %return - -return: ; preds = %entry - %retval4 = load x86_fp80* %retval ; [#uses=1] - ret x86_fp80 %retval4 + %tmp2 = call x86_fp80 @llvm.sqrt.f80( x86_fp80 %x ) + ret x86_fp80 %tmp2 + +; CHECK: foo: +; CHECK: fldt 4(%esp) +; CHECK-NEXT: fsqrt +; CHECK-NEXT: ret } declare x86_fp80 @llvm.sqrt.f80(x86_fp80) -define x86_fp80 @bar(x86_fp80 %x) { +define x86_fp80 @bar(x86_fp80 %x) nounwind { entry: - %x_addr = alloca x86_fp80 ; [#uses=2] - %retval = alloca x86_fp80 ; [#uses=2] - %tmp = alloca x86_fp80 ; [#uses=2] - %"alloca point" = bitcast i32 0 to i32 ; [#uses=0] - store x86_fp80 %x, x86_fp80* %x_addr - %tmp1 = load x86_fp80* %x_addr, align 16 ; [#uses=1] - %tmp2 = call x86_fp80 @llvm.powi.f80( x86_fp80 %tmp1, i32 3 ) ; [#uses=1] - store x86_fp80 %tmp2, x86_fp80* %tmp, align 16 - %tmp3 = load x86_fp80* %tmp, align 16 ; [#uses=1] - store x86_fp80 %tmp3, x86_fp80* %retval, align 16 - br label %return - -return: ; preds = %entry - %retval4 = load x86_fp80* %retval ; [#uses=1] - ret x86_fp80 %retval4 + %tmp2 = call x86_fp80 @llvm.powi.f80( x86_fp80 %x, i32 3 ) + ret x86_fp80 %tmp2 +; CHECK: bar: +; CHECK: fldt 4(%esp) +; CHECK-NEXT: fld %st(0) +; CHECK-NEXT: fmul %st(1) +; CHECK-NEXT: fmulp %st(1) +; CHECK-NEXT: ret } declare x86_fp80 @llvm.powi.f80(x86_fp80, i32) Added: llvm/trunk/test/CodeGen/X86/powi.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/X86/powi.ll?rev=92388&view=auto ============================================================================== --- llvm/trunk/test/CodeGen/X86/powi.ll (added) +++ llvm/trunk/test/CodeGen/X86/powi.ll Thu Dec 31 21:32:16 2009 @@ -0,0 +1,11 @@ +; RUN: llc %s -march=x86 -mcpu=yonah -o - | grep mulsd | count 6 +; Ideally this would compile to 5 multiplies. + +define double @_Z3f10d(double %a) nounwind readonly ssp noredzone { +entry: + %0 = tail call double @llvm.powi.f64(double %a, i32 15) nounwind ; [#uses=1] + ret double %0 +} + +declare double @llvm.powi.f64(double, i32) nounwind readonly + From foldr at codedgers.com Thu Dec 31 21:50:35 2009 From: foldr at codedgers.com (Mikhail Glushenkov) Date: Fri, 01 Jan 2010 03:50:35 -0000 Subject: [llvm-commits] [llvm] r92389 - /llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Message-ID: <201001010350.o013oZWT018601@zion.cs.uiuc.edu> Author: foldr Date: Thu Dec 31 21:50:34 2009 New Revision: 92389 URL: http://llvm.org/viewvc/llvm-project?rev=92389&view=rev Log: Better error message. Modified: llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Modified: llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp?rev=92389&r1=92388&r2=92389&view=diff ============================================================================== --- llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp (original) +++ llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Thu Dec 31 21:50:34 2009 @@ -1397,7 +1397,7 @@ else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O)) return; else - throw TestName + ": unknown edge property!"; + throw "Unknown test '" + TestName + "' used in the 'case' construct!"; } From foldr at codedgers.com Thu Dec 31 21:50:51 2009 From: foldr at codedgers.com (Mikhail Glushenkov) Date: Fri, 01 Jan 2010 03:50:51 -0000 Subject: [llvm-commits] [llvm] r92390 - in /llvm/trunk: tools/llvmc/plugins/Base/Base.td.in utils/TableGen/LLVMCConfigurationEmitter.cpp Message-ID: <201001010350.o013oqwD018619@zion.cs.uiuc.edu> Author: foldr Date: Thu Dec 31 21:50:51 2009 New Revision: 92390 URL: http://llvm.org/viewvc/llvm-project?rev=92390&view=rev Log: Minor simplifications. Modified: llvm/trunk/tools/llvmc/plugins/Base/Base.td.in llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Modified: llvm/trunk/tools/llvmc/plugins/Base/Base.td.in URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/tools/llvmc/plugins/Base/Base.td.in?rev=92390&r1=92389&r2=92390&view=diff ============================================================================== --- llvm/trunk/tools/llvmc/plugins/Base/Base.td.in (original) +++ llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Thu Dec 31 21:50:51 2009 @@ -97,11 +97,10 @@ (unset_option ["O0", "O1", "O2"]), (and (switch_on "O2"), (any_switch_on ["O0", "O1"])), (unset_option ["O0", "O1"]), - (and (switch_on "O1"), (switch_on "O0")), + (switch_on ["O1", "O0"]), (unset_option "O0")) >; - // Tools class llvm_gcc_based : Tool< Modified: llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp?rev=92390&r1=92389&r2=92390&view=diff ============================================================================== --- llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp (original) +++ llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Thu Dec 31 21:50:51 2009 @@ -1240,7 +1240,7 @@ const DagInit& d, const OptionDescriptions& OptDescs, raw_ostream& O) { - const ListInit& L = *static_cast(d.getArg(0)); + const ListInit& L = InitPtrToList(d.getArg(0)); if (TestName == "any_switch_on") { EmitListTest(L, "||", EmitSwitchOn(OptDescs), O); From foldr at codedgers.com Thu Dec 31 21:51:02 2009 From: foldr at codedgers.com (Mikhail Glushenkov) Date: Fri, 01 Jan 2010 03:51:02 -0000 Subject: [llvm-commits] [llvm] r92391 - /llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Message-ID: <201001010351.o013p2iD018635@zion.cs.uiuc.edu> Author: foldr Date: Thu Dec 31 21:51:02 2009 New Revision: 92391 URL: http://llvm.org/viewvc/llvm-project?rev=92391&view=rev Log: Make CheckForSuperfluousOptions handle list form of 'switch_on' correctly. Modified: llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Modified: llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp?rev=92391&r1=92390&r2=92391&view=diff ============================================================================== --- llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp (original) +++ llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Thu Dec 31 21:51:02 2009 @@ -1086,14 +1086,28 @@ if (ActionName == "forward" || ActionName == "forward_as" || ActionName == "forward_value" || ActionName == "forward_transformed_value" || - ActionName == "switch_on" || ActionName == "parameter_equals" || + ActionName == "switch_on" || ActionName == "any_switch_on" || + ActionName == "parameter_equals" || ActionName == "element_in_list" || ActionName == "not_empty" || ActionName == "empty") { CheckNumberOfArguments(Stmt, 1); - const std::string& Name = InitPtrToString(Stmt.getArg(0)); - OptionNames_.insert(Name); + + Init* Arg = Stmt.getArg(0); + if (typeid(*Arg) == typeid(StringInit)) { + const std::string& Name = InitPtrToString(Arg); + OptionNames_.insert(Name); + } + else { + // It's a list. + const ListInit& List = InitPtrToList(Arg); + for (ListInit::const_iterator B = List.begin(), E = List.end(); + B != E; ++B) { + const std::string& Name = InitPtrToString(*B); + OptionNames_.insert(Name); + } + } } - else if (ActionName == "and" || ActionName == "or") { + else if (ActionName == "and" || ActionName == "or" || ActionName == "not") { for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) { this->processDag(Stmt.getArg(i)); } @@ -2895,7 +2909,6 @@ // Check that there are no options without side effects (specified // only in the OptionList). CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs); - } void EmitPluginCode(const PluginData& Data, raw_ostream& O) { From foldr at codedgers.com Thu Dec 31 22:40:55 2009 From: foldr at codedgers.com (Mikhail Glushenkov) Date: Fri, 01 Jan 2010 04:40:55 -0000 Subject: [llvm-commits] [llvm] r92392 - /llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Message-ID: <201001010440.o014et91020219@zion.cs.uiuc.edu> Author: foldr Date: Thu Dec 31 22:40:54 2009 New Revision: 92392 URL: http://llvm.org/viewvc/llvm-project?rev=92392&view=rev Log: Typo. Modified: llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Modified: llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp?rev=92392&r1=92391&r2=92392&view=diff ============================================================================== --- llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp (original) +++ llvm/trunk/utils/TableGen/LLVMCConfigurationEmitter.cpp Thu Dec 31 22:40:54 2009 @@ -1206,7 +1206,7 @@ if (isFirst) isFirst = false; else - O << " || "; + O << ' ' << LogicOp << ' '; Callback(InitPtrToString(*B), O); } } From foldr at codedgers.com Thu Dec 31 22:41:10 2009 From: foldr at codedgers.com (Mikhail Glushenkov) Date: Fri, 01 Jan 2010 04:41:10 -0000 Subject: [llvm-commits] [llvm] r92393 - /llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Message-ID: <201001010441.o014fAd3020236@zion.cs.uiuc.edu> Author: foldr Date: Thu Dec 31 22:41:10 2009 New Revision: 92393 URL: http://llvm.org/viewvc/llvm-project?rev=92393&view=rev Log: Minor simplifactions. Modified: llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Modified: llvm/trunk/tools/llvmc/plugins/Base/Base.td.in URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/tools/llvmc/plugins/Base/Base.td.in?rev=92393&r1=92392&r2=92393&view=diff ============================================================================== --- llvm/trunk/tools/llvmc/plugins/Base/Base.td.in (original) +++ llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Thu Dec 31 22:41:10 2009 @@ -124,9 +124,9 @@ (and (multiple_input_files), (or (switch_on "S"), (switch_on "c"))), (error "cannot specify -o with -c or -S with multiple files"), (switch_on "E"), [(stop_compilation), (output_suffix E_ext)], - (and (switch_on "emit-llvm"), (switch_on "S")), + (switch_on ["emit-llvm", "S"]), [(output_suffix "ll"), (stop_compilation)], - (and (switch_on "emit-llvm"), (switch_on "c")), (stop_compilation), + (switch_on ["emit-llvm", "c"]), (stop_compilation), (switch_on "fsyntax-only"), (stop_compilation), (not_empty "include"), (forward "include"), (not_empty "save-temps"), (append_cmd "-save-temps"), From foldr at codedgers.com Thu Dec 31 22:41:23 2009 From: foldr at codedgers.com (Mikhail Glushenkov) Date: Fri, 01 Jan 2010 04:41:23 -0000 Subject: [llvm-commits] [llvm] r92394 - /llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Message-ID: <201001010441.o014fNBF020253@zion.cs.uiuc.edu> Author: foldr Date: Thu Dec 31 22:41:22 2009 New Revision: 92394 URL: http://llvm.org/viewvc/llvm-project?rev=92394&view=rev Log: Trailing whitespace, 80-col violations. Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp?rev=92394&r1=92393&r2=92394&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Thu Dec 31 22:41:22 2009 @@ -70,13 +70,13 @@ namespace { /// RegsForValue - This struct represents the registers (physical or virtual) - /// that a particular set of values is assigned, and the type information about - /// the value. The most common situation is to represent one value at a time, - /// but struct or array values are handled element-wise as multiple values. - /// The splitting of aggregates is performed recursively, so that we never - /// have aggregate-typed registers. The values at this point do not necessarily - /// have legal types, so each value may require one or more registers of some - /// legal type. + /// that a particular set of values is assigned, and the type information + /// about the value. The most common situation is to represent one value at a + /// time, but struct or array values are handled element-wise as multiple + /// values. The splitting of aggregates is performed recursively, so that we + /// never have aggregate-typed registers. The values at this point do not + /// necessarily have legal types, so each value may require one or more + /// registers of some legal type. /// struct RegsForValue { /// TLI - The TargetLowering object. @@ -243,11 +243,13 @@ EVT IntermediateVT, RegisterVT; unsigned NumIntermediates; unsigned NumRegs = - TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, + TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates, RegisterVT); - assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); + assert(NumRegs == NumParts + && "Part count doesn't match vector breakdown!"); NumParts = NumRegs; // Silence a compiler warning. - assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); + assert(RegisterVT == PartVT + && "Part type doesn't match vector breakdown!"); assert(RegisterVT == Parts[0].getValueType() && "Part type doesn't match part!"); @@ -260,8 +262,8 @@ Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i], 1, PartVT, IntermediateVT); } else if (NumParts > 0) { - // If the intermediate type was expanded, build the intermediate operands - // from the parts. + // If the intermediate type was expanded, build the intermediate + // operands from the parts. assert(NumParts % NumIntermediates == 0 && "Must expand into a divisible number of parts!"); unsigned Factor = NumParts / NumIntermediates; @@ -270,8 +272,8 @@ PartVT, IntermediateVT); } - // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate - // operands. + // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the + // intermediate operands. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl, ValueVT, &Ops[0], NumIntermediates); @@ -854,7 +856,7 @@ SDValue Chain = getControlRoot(); SmallVector Outs; FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo(); - + if (!FLI.CanLowerReturn) { unsigned DemoteReg = FLI.DemoteRegister; const Function *F = I.getParent()->getParent(); @@ -863,12 +865,12 @@ // Leave Outs empty so that LowerReturn won't try to load return // registers the usual way. SmallVector PtrValueVTs; - ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()), + ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()), PtrValueVTs); SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]); SDValue RetOp = getValue(I.getOperand(0)); - + SmallVector ValueVTs; SmallVector Offsets; ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets); @@ -901,7 +903,7 @@ ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs); unsigned NumValues = ValueVTs.size(); if (NumValues == 0) continue; - + SDValue RetOp = getValue(I.getOperand(i)); for (unsigned j = 0, f = NumValues; j != f; ++j) { EVT VT = ValueVTs[j]; @@ -914,8 +916,8 @@ else if (F->paramHasAttr(0, Attribute::ZExt)) ExtendKind = ISD::ZERO_EXTEND; - // FIXME: C calling convention requires the return type to be promoted to - // at least 32-bit. But this is not necessary for non-C calling + // FIXME: C calling convention requires the return type to be promoted + // to at least 32-bit. But this is not necessary for non-C calling // conventions. The frontend should mark functions whose return values // require promoting with signext or zeroext attributes. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) { @@ -1845,7 +1847,7 @@ APInt Range = ComputeRange(LEnd, RBegin); assert((Range - 2ULL).isNonNegative() && "Invalid case distance"); - double LDensity = (double)LSize.roundToDouble() / + double LDensity = (double)LSize.roundToDouble() / (LEnd - First + 1ULL).roundToDouble(); double RDensity = (double)RSize.roundToDouble() / (Last - RBegin + 1ULL).roundToDouble(); @@ -1963,8 +1965,9 @@ // Don't bother the code below, if there are too much unique destinations return false; } - DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n' - << "Total number of comparisons: " << numCmps << '\n'); + DEBUG(errs() << "Total number of unique destinations: " + << Dests.size() << '\n' + << "Total number of comparisons: " << numCmps << '\n'); // Compute span of values. const APInt& minValue = cast(FrontCase.Low)->getValue(); @@ -2197,7 +2200,7 @@ if (CV == CNZ) { SDValue Op2 = getValue(I.getOperand(1)); SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(), - Op2.getValueType(), Op2); + Op2.getValueType(), Op2); setValue(&I, Res); if (DisableScheduling) @@ -2285,7 +2288,7 @@ SDValue Op1 = getValue(I.getOperand(0)); SDValue Op2 = getValue(I.getOperand(1)); ISD::CondCode Opcode = getICmpCondCode(predicate); - + EVT DestVT = TLI.getValueType(I.getType()); SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode); setValue(&I, Res); @@ -2540,7 +2543,7 @@ // Convert the ConstantVector mask operand into an array of ints, with -1 // representing undef values. SmallVector MaskElts; - cast(I.getOperand(2))->getVectorElements(*DAG.getContext(), + cast(I.getOperand(2))->getVectorElements(*DAG.getContext(), MaskElts); unsigned MaskNumElts = MaskElts.size(); for (unsigned i = 0; i != MaskNumElts; ++i) { @@ -2549,7 +2552,7 @@ else Mask.push_back(cast(MaskElts[i])->getSExtValue()); } - + EVT VT = TLI.getValueType(I.getType()); EVT SrcVT = Src1.getValueType(); unsigned SrcNumElts = SrcVT.getVectorNumElements(); @@ -2592,12 +2595,12 @@ SmallVector MOps2(NumConcat, UndefVal); MOps1[0] = Src1; MOps2[0] = Src2; - - Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, - getCurDebugLoc(), VT, + + Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, + getCurDebugLoc(), VT, &MOps1[0], NumConcat); Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, - getCurDebugLoc(), VT, + getCurDebugLoc(), VT, &MOps2[0], NumConcat); // Readjust mask for new input vector length. @@ -2610,7 +2613,7 @@ MappedOps.push_back(Idx + MaskNumElts - SrcNumElts); } - SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, + SDValue Res = DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, &MappedOps[0]); setValue(&I, Res); @@ -2635,7 +2638,7 @@ int Input = 0; if (Idx < 0) continue; - + if (Idx >= (int)SrcNumElts) { Input = 1; Idx -= SrcNumElts; @@ -2648,7 +2651,8 @@ // Check if the access is smaller than the vector size and can we find // a reasonable extract index. - int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract. + int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not + // Extract. int StartIdx[2]; // StartIdx to extract from for (int Input=0; Input < 2; ++Input) { if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) { @@ -2928,20 +2932,20 @@ I.getAlignment()); SDValue AllocSize = getValue(I.getArraySize()); - + AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(), AllocSize, DAG.getConstant(TySize, AllocSize.getValueType())); - + if (DisableScheduling) DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder); - + EVT IntPtr = TLI.getPointerTy(); AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr); if (DisableScheduling) DAG.AssignOrdering(AllocSize.getNode(), SDNodeOrder); - + // Handle alignment. If the requested alignment is less than or equal to // the stack alignment, ignore it. If the size is greater than or equal to // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. @@ -4274,7 +4278,7 @@ // Get the exponent as a positive value. unsigned Val = RHSC->getSExtValue(); if ((int)Val < 0) Val = -Val; - + // powi(x, 0) -> 1.0 if (Val == 0) return DAG.getConstantFP(1.0, LHS.getValueType()); @@ -4285,7 +4289,7 @@ // inserts up to 5 multiplies. CountPopulation_32(Val)+Log2_32(Val) < 7) { // We use the simple binary decomposition method to generate the multiply - // sequence. There are more optimal ways to do this (for example, + // sequence. There are more optimal ways to do this (for example, // powi(x,15) generates one more multiply than it should), but this has // the benefit of being both really simple and much better than a libcall. SDValue Res; // Logically starts equal to 1.0 @@ -4296,12 +4300,12 @@ Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); else Res = CurSquare; // 1.0*CurSquare. - + CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), CurSquare, CurSquare); Val >>= 1; } - + // If the original was negative, invert the result, producing 1/(x*x*x). if (RHSC->getSExtValue() < 0) Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), @@ -4401,14 +4405,14 @@ DAG.AssignOrdering(Res.getNode(), SDNodeOrder); return 0; } - case Intrinsic::dbg_stoppoint: + case Intrinsic::dbg_stoppoint: case Intrinsic::dbg_region_start: case Intrinsic::dbg_region_end: case Intrinsic::dbg_func_start: // FIXME - Remove this instructions once the dust settles. return 0; case Intrinsic::dbg_declare: { - if (OptLevel != CodeGenOpt::None) + if (OptLevel != CodeGenOpt::None) // FIXME: Variable debug info is not supported here. return 0; DwarfWriter *DW = DAG.getDwarfWriter(); @@ -4428,7 +4432,7 @@ return 0; DenseMap::iterator SI = FuncInfo.StaticAllocaMap.find(AI); - if (SI == FuncInfo.StaticAllocaMap.end()) + if (SI == FuncInfo.StaticAllocaMap.end()) return 0; // VLAs. int FI = SI->second; @@ -4977,10 +4981,10 @@ SmallVector OutVTs; SmallVector OutsFlags; SmallVector Offsets; - getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(), + getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(), OutVTs, OutsFlags, TLI, &Offsets); - bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(), + bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(), FTy->isVarArg(), OutVTs, OutsFlags, DAG); SDValue DemoteStackSlot; @@ -5140,23 +5144,23 @@ static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy, SelectionDAGBuilder &Builder) { - + // Check to see if this load can be trivially constant folded, e.g. if the // input is from a string literal. if (Constant *LoadInput = dyn_cast(PtrVal)) { // Cast pointer to the type we really want to load. LoadInput = ConstantExpr::getBitCast(LoadInput, PointerType::getUnqual(LoadTy)); - + if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD)) return Builder.getValue(LoadCst); } - + // Otherwise, we have to emit the load. If the pointer is to unfoldable but // still constant memory, the input chain can be the entry node. SDValue Root; bool ConstantMemory = false; - + // Do not serialize (non-volatile) loads of constant memory with anything. if (Builder.AA->pointsToConstantMemory(PtrVal)) { Root = Builder.DAG.getEntryNode(); @@ -5165,12 +5169,12 @@ // Do not serialize non-volatile loads against each other. Root = Builder.DAG.getRoot(); } - + SDValue Ptr = Builder.getValue(PtrVal); SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root, Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/, false /*volatile*/, 1 /* align=1 */); - + if (!ConstantMemory) Builder.PendingLoads.push_back(LoadVal.getValue(1)); return LoadVal; @@ -5184,15 +5188,15 @@ // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) if (I.getNumOperands() != 4) return false; - + Value *LHS = I.getOperand(1), *RHS = I.getOperand(2); if (!isa(LHS->getType()) || !isa(RHS->getType()) || !isa(I.getOperand(3)->getType()) || !isa(I.getType())) - return false; - + return false; + ConstantInt *Size = dyn_cast(I.getOperand(3)); - + // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) { @@ -5211,25 +5215,25 @@ break; case 4: LoadVT = MVT::i32; - LoadTy = Type::getInt32Ty(Size->getContext()); + LoadTy = Type::getInt32Ty(Size->getContext()); break; case 8: LoadVT = MVT::i64; - LoadTy = Type::getInt64Ty(Size->getContext()); + LoadTy = Type::getInt64Ty(Size->getContext()); break; /* case 16: LoadVT = MVT::v4i32; - LoadTy = Type::getInt32Ty(Size->getContext()); + LoadTy = Type::getInt32Ty(Size->getContext()); LoadTy = VectorType::get(LoadTy, 4); break; */ } - + // This turns into unaligned loads. We only do this if the target natively // supports the MVT we'll be loading or if it is small enough (<= 4) that // we'll only produce a small number of byte loads. - + // Require that we can find a legal MVT, and only do this if the target // supports unaligned loads of that type. Expanding into byte loads would // bloat the code. @@ -5239,11 +5243,11 @@ if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT)) ActuallyDoIt = false; } - + if (ActuallyDoIt) { SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); - + SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal, ISD::SETNE); EVT CallVT = TLI.getValueType(I.getType(), true); @@ -5251,8 +5255,8 @@ return true; } } - - + + return false; } @@ -5622,7 +5626,7 @@ /// getCallOperandValEVT - Return the EVT of the Value* that this operand /// corresponds to. If there is no Value* for this operand, it returns /// MVT::Other. - EVT getCallOperandValEVT(LLVMContext &Context, + EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, const TargetData *TD) const { if (CallOperandVal == 0) return MVT::Other; @@ -5743,7 +5747,7 @@ // bitcast to the corresponding integer type. This turns an f64 value // into i64, which can be passed with two i32 values on a 32-bit // machine. - RegVT = EVT::getIntegerVT(Context, + RegVT = EVT::getIntegerVT(Context, OpInfo.ConstraintVT.getSizeInBits()); OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), RegVT, OpInfo.CallOperand); @@ -5810,7 +5814,7 @@ OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT); return; } - + // This is a reference to a register class that doesn't directly correspond // to an LLVM register class. Allocate NumRegs consecutive, available, // registers from the class. @@ -5872,7 +5876,7 @@ if (CType == TargetLowering::C_Memory) return true; } - + // Indirect operand accesses access memory. if (CI.isIndirect) return true; @@ -5897,9 +5901,9 @@ ConstraintInfos = IA->ParseConstraints(); bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI); - + SDValue Chain, Flag; - + // We won't need to flush pending loads if this asm doesn't touch // memory and is nonvolatile. if (hasMemory || IA->hasSideEffects()) @@ -6151,8 +6155,8 @@ MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); i != e; ++i) - MatchedRegs.Regs. - push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT))); + MatchedRegs.Regs.push_back + (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT))); // Use the produced MatchedRegs object to MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), @@ -6561,11 +6565,11 @@ // Check whether the function can return without sret-demotion. SmallVector OutVTs; SmallVector OutsFlags; - getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(), + getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(), OutVTs, OutsFlags, TLI); FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo(); - FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(), + FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(), OutVTs, OutsFlags, DAG); if (!FLI.CanLowerReturn) { // Put in an sret pointer parameter before all the other parameters. @@ -6676,7 +6680,8 @@ MachineRegisterInfo& RegInfo = MF.getRegInfo(); unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)); FLI.DemoteRegister = SRetReg; - NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), SRetReg, ArgValue); + NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), + SRetReg, ArgValue); DAG.setRoot(NewRoot); // i indexes lowered arguments. Bump it past the hidden sret argument. From foldr at codedgers.com Thu Dec 31 22:41:36 2009 From: foldr at codedgers.com (Mikhail Glushenkov) Date: Fri, 01 Jan 2010 04:41:36 -0000 Subject: [llvm-commits] [llvm] r92395 - /llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Message-ID: <201001010441.o014fb97020274@zion.cs.uiuc.edu> Author: foldr Date: Thu Dec 31 22:41:36 2009 New Revision: 92395 URL: http://llvm.org/viewvc/llvm-project?rev=92395&view=rev Log: Fix a warning on gcc 4.4. SelectionDAGBuilder.cpp:4294: warning: suggest explicit braces to avoid ambiguous ?else? Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp?rev=92395&r1=92394&r2=92395&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Thu Dec 31 22:41:36 2009 @@ -4295,11 +4295,12 @@ SDValue Res; // Logically starts equal to 1.0 SDValue CurSquare = LHS; while (Val) { - if (Val & 1) + if (Val & 1) { if (Res.getNode()) Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); else Res = CurSquare; // 1.0*CurSquare. + } CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), CurSquare, CurSquare); From sabre at nondot.org Fri Jan 1 12:34:40 2010 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 18:34:40 -0000 Subject: [llvm-commits] [llvm] r92398 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/bswap-fold.ll Message-ID: <201001011834.o01IYe5F027214@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 12:34:40 2010 New Revision: 92398 URL: http://llvm.org/viewvc/llvm-project?rev=92398&view=rev Log: implement the transform requested in PR5284 Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/bswap-fold.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92398&r1=92397&r2=92398&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Fri Jan 1 12:34:40 2010 @@ -10139,6 +10139,19 @@ if (IntrinsicInst *Operand = dyn_cast(II->getOperand(1))) if (Operand->getIntrinsicID() == Intrinsic::bswap) return ReplaceInstUsesWith(CI, Operand->getOperand(1)); + + // bswap(trunc(bswap(x))) -> trunc(lshr(x, c)) + if (TruncInst *TI = dyn_cast(II->getOperand(1))) { + if (IntrinsicInst *Operand = dyn_cast(TI->getOperand(0))) + if (Operand->getIntrinsicID() == Intrinsic::bswap) { + unsigned C = Operand->getType()->getPrimitiveSizeInBits() - + TI->getType()->getPrimitiveSizeInBits(); + Value *CV = ConstantInt::get(Operand->getType(), C); + Value *V = Builder->CreateLShr(Operand->getOperand(1), CV); + return new TruncInst(V, TI->getType()); + } + } + break; case Intrinsic::powi: if (ConstantInt *Power = dyn_cast(II->getOperand(2))) { Modified: llvm/trunk/test/Transforms/InstCombine/bswap-fold.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/bswap-fold.ll?rev=92398&r1=92397&r2=92398&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/bswap-fold.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/bswap-fold.ll Fri Jan 1 12:34:40 2010 @@ -1,23 +1,22 @@ -; RUN: opt < %s -instcombine -S | grep ret | count 6 ; RUN: opt < %s -instcombine -S | not grep call.*bswap define i1 @test1(i16 %tmp2) { - %tmp10 = call i16 @llvm.bswap.i16( i16 %tmp2 ) ; [#uses=1] - %tmp = icmp eq i16 %tmp10, 1 ; [#uses=1] + %tmp10 = call i16 @llvm.bswap.i16( i16 %tmp2 ) + %tmp = icmp eq i16 %tmp10, 1 ret i1 %tmp } define i1 @test2(i32 %tmp) { - %tmp34 = tail call i32 @llvm.bswap.i32( i32 %tmp ) ; [#uses=1] - %tmp.upgrd.1 = icmp eq i32 %tmp34, 1 ; [#uses=1] + %tmp34 = tail call i32 @llvm.bswap.i32( i32 %tmp ) + %tmp.upgrd.1 = icmp eq i32 %tmp34, 1 ret i1 %tmp.upgrd.1 } declare i32 @llvm.bswap.i32(i32) define i1 @test3(i64 %tmp) { - %tmp34 = tail call i64 @llvm.bswap.i64( i64 %tmp ) ; [#uses=1] - %tmp.upgrd.2 = icmp eq i64 %tmp34, 1 ; [#uses=1] + %tmp34 = tail call i64 @llvm.bswap.i64( i64 %tmp ) + %tmp.upgrd.2 = icmp eq i64 %tmp34, 1 ret i1 %tmp.upgrd.2 } @@ -50,3 +49,21 @@ ret i32 %tmp4 } +; PR5284 +declare i64 @llvm.bswap.i64(i64) +declare i32 @llvm.bswap.i32(i32) +declare i16 @llvm.bswap.i16(i16) + +define i16 @test7(i32 %A) { + %B = tail call i32 @llvm.bswap.i32(i32 %A) nounwind + %C = trunc i32 %B to i16 + %D = tail call i16 @llvm.bswap.i16(i16 %C) nounwind + ret i16 %D +} + +define i16 @test8(i64 %A) { + %B = tail call i64 @llvm.bswap.i64(i64 %A) nounwind + %C = trunc i64 %B to i16 + %D = tail call i16 @llvm.bswap.i16(i16 %C) nounwind + ret i16 %D +} From sabre at nondot.org Fri Jan 1 16:12:04 2010 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 22:12:04 -0000 Subject: [llvm-commits] [llvm] r92400 - /llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Message-ID: <201001012212.o01MC43I003083@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 16:12:03 2010 New Revision: 92400 URL: http://llvm.org/viewvc/llvm-project?rev=92400&view=rev Log: use 'match' to simplify some code. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92400&r1=92399&r2=92400&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Fri Jan 1 16:12:03 2010 @@ -2949,12 +2949,11 @@ // Optimize pointer differences into the same array into a size. Consider: // &A[10] - &A[0]: we should compile this to "10". if (TD) { - if (PtrToIntInst *LHS = dyn_cast(Op0)) - if (PtrToIntInst *RHS = dyn_cast(Op1)) - if (Value *Res = OptimizePointerDifference(LHS->getOperand(0), - RHS->getOperand(0), - I.getType())) - return ReplaceInstUsesWith(I, Res); + Value *LHSOp, *RHSOp; + if (match(Op0, m_Cast(m_Value(LHSOp))) && + match(Op1, m_Cast(m_Value(RHSOp)))) + if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType())) + return ReplaceInstUsesWith(I, Res); // trunc(p)-trunc(q) -> trunc(p-q) if (TruncInst *LHST = dyn_cast(Op0)) From sabre at nondot.org Fri Jan 1 16:29:12 2010 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 22:29:12 -0000 Subject: [llvm-commits] [llvm] r92401 - in /llvm/trunk: include/llvm/Support/PatternMatch.h lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/sub.ll Message-ID: <201001012229.o01MTC2E003674@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 16:29:12 2010 New Revision: 92401 URL: http://llvm.org/viewvc/llvm-project?rev=92401&view=rev Log: teach instcombine to optimize pointer difference idioms involving constant expressions. This is a step towards comment #4 in PR3351. Modified: llvm/trunk/include/llvm/Support/PatternMatch.h llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/sub.ll Modified: llvm/trunk/include/llvm/Support/PatternMatch.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/PatternMatch.h?rev=92401&r1=92400&r2=92401&view=diff ============================================================================== --- llvm/trunk/include/llvm/Support/PatternMatch.h (original) +++ llvm/trunk/include/llvm/Support/PatternMatch.h Fri Jan 1 16:29:12 2010 @@ -437,7 +437,7 @@ // Matchers for CastInst classes // -template +template struct CastClass_match { Op_t Op; @@ -445,17 +445,28 @@ template bool match(OpTy *V) { - if (Class *I = dyn_cast(V)) - return Op.match(I->getOperand(0)); + if (CastInst *I = dyn_cast(V)) + return I->getOpcode() == Opcode && Op.match(I->getOperand(0)); + if (ConstantExpr *CE = dyn_cast(V)) + return CE->getOpcode() == Opcode && Op.match(CE->getOperand(0)); return false; } }; -template -inline CastClass_match m_Cast(const OpTy &Op) { - return CastClass_match(Op); +/// m_PtrToInt +template +inline CastClass_match +m_PtrToInt(const OpTy &Op) { + return CastClass_match(Op); } +/// m_Trunc +template +inline CastClass_match +m_Trunc(const OpTy &Op) { + return CastClass_match(Op); +} + //===----------------------------------------------------------------------===// // Matchers for unary operators Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92401&r1=92400&r2=92401&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Fri Jan 1 16:29:12 2010 @@ -2950,20 +2950,16 @@ // &A[10] - &A[0]: we should compile this to "10". if (TD) { Value *LHSOp, *RHSOp; - if (match(Op0, m_Cast(m_Value(LHSOp))) && - match(Op1, m_Cast(m_Value(RHSOp)))) + if (match(Op0, m_PtrToInt(m_Value(LHSOp))) && + match(Op1, m_PtrToInt(m_Value(RHSOp)))) if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType())) return ReplaceInstUsesWith(I, Res); // trunc(p)-trunc(q) -> trunc(p-q) - if (TruncInst *LHST = dyn_cast(Op0)) - if (TruncInst *RHST = dyn_cast(Op1)) - if (PtrToIntInst *LHS = dyn_cast(LHST->getOperand(0))) - if (PtrToIntInst *RHS = dyn_cast(RHST->getOperand(0))) - if (Value *Res = OptimizePointerDifference(LHS->getOperand(0), - RHS->getOperand(0), - I.getType())) - return ReplaceInstUsesWith(I, Res); + if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) && + match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp))))) + if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType())) + return ReplaceInstUsesWith(I, Res); } return 0; Modified: llvm/trunk/test/Transforms/InstCombine/sub.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/sub.ll?rev=92401&r1=92400&r2=92401&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/sub.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/sub.ll Fri Jan 1 16:29:12 2010 @@ -248,3 +248,15 @@ ; CHECK-NEXT: ret i64 } + at Arr = external global [42 x i16] + +define i64 @test24b(i8* %P, i64 %A){ + %B = getelementptr inbounds [42 x i16]* @Arr, i64 0, i64 %A + %C = ptrtoint i16* %B to i64 + %G = sub i64 %C, ptrtoint ([42 x i16]* @Arr to i64) + ret i64 %G +; CHECK: @test24b +; CHECK-NEXT: shl i64 %A, 1 +; CHECK-NEXT: ret i64 +} + From sabre at nondot.org Fri Jan 1 16:42:29 2010 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 22:42:29 -0000 Subject: [llvm-commits] [llvm] r92402 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/sub.ll Message-ID: <201001012242.o01MgTYZ004078@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 16:42:29 2010 New Revision: 92402 URL: http://llvm.org/viewvc/llvm-project?rev=92402&view=rev Log: generalize the pointer difference optimization to handle a constantexpr gep on the 'base' side of the expression. This completes comment #4 in PR3351, which comes from 483.xalancbmk. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/sub.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92402&r1=92401&r2=92402&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Fri Jan 1 16:42:29 2010 @@ -2770,21 +2770,57 @@ // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize // this. bool Swapped; - GetElementPtrInst *GEP; + GetElementPtrInst *GEP = 0; + ConstantExpr *CstGEP = 0; - if ((GEP = dyn_cast(LHS)) && - GEP->getOperand(0) == RHS) - Swapped = false; - else if ((GEP = dyn_cast(RHS)) && - GEP->getOperand(0) == LHS) - Swapped = true; - else - return 0; + // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo". + // For now we require one side to be the base pointer "A" or a constant + // expression derived from it. + if (GetElementPtrInst *LHSGEP = dyn_cast(LHS)) { + // (gep X, ...) - X + if (LHSGEP->getOperand(0) == RHS) { + GEP = LHSGEP; + Swapped = false; + } else if (ConstantExpr *CE = dyn_cast(RHS)) { + // (gep X, ...) - (ce_gep X, ...) + if (CE->getOpcode() == Instruction::GetElementPtr && + LHSGEP->getOperand(0) == CE->getOperand(0)) { + CstGEP = CE; + GEP = LHSGEP; + Swapped = false; + } + } + } - // TODO: Could also optimize &A[i] - &A[j] -> "i-j". + if (GetElementPtrInst *RHSGEP = dyn_cast(RHS)) { + // X - (gep X, ...) + if (RHSGEP->getOperand(0) == LHS) { + GEP = RHSGEP; + Swapped = true; + } else if (ConstantExpr *CE = dyn_cast(LHS)) { + // (ce_gep X, ...) - (gep X, ...) + if (CE->getOpcode() == Instruction::GetElementPtr && + RHSGEP->getOperand(0) == CE->getOperand(0)) { + CstGEP = CE; + GEP = RHSGEP; + Swapped = true; + } + } + } + + if (GEP == 0) + return 0; // Emit the offset of the GEP and an intptr_t. Value *Result = EmitGEPOffset(GEP, *this); + + // If we had a constant expression GEP on the other side offsetting the + // pointer, subtract it from the offset we have. + if (CstGEP) { + Value *CstOffset = EmitGEPOffset(CstGEP, *this); + Result = Builder->CreateSub(Result, CstOffset); + } + // If we have p - gep(p, ...) then we have to negate the result. if (Swapped) Modified: llvm/trunk/test/Transforms/InstCombine/sub.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/sub.ll?rev=92402&r1=92401&r2=92402&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/sub.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/sub.ll Fri Jan 1 16:42:29 2010 @@ -260,3 +260,16 @@ ; CHECK-NEXT: ret i64 } + +define i64 @test25(i8* %P, i64 %A){ + %B = getelementptr inbounds [42 x i16]* @Arr, i64 0, i64 %A + %C = ptrtoint i16* %B to i64 + %G = sub i64 %C, ptrtoint (i16* getelementptr ([42 x i16]* @Arr, i64 1, i64 0) to i64) + ret i64 %G +; CHECK: @test25 +; CHECK-NEXT: shl i64 %A, 1 +; CHECK-NEXT: add i64 {{.*}}, -84 +; CHECK-NEXT: ret i64 +} + + From sabre at nondot.org Fri Jan 1 17:09:09 2010 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 23:09:09 -0000 Subject: [llvm-commits] [llvm] r92403 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/cast_ptr.ll Message-ID: <201001012309.o01N99Ln004952@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 17:09:08 2010 New Revision: 92403 URL: http://llvm.org/viewvc/llvm-project?rev=92403&view=rev Log: add a simple instcombine xform, simplify another one to use hasAllZeroIndices() instead of hand rolling a loop. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/cast_ptr.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92403&r1=92402&r2=92403&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Fri Jan 1 17:09:08 2010 @@ -6427,21 +6427,12 @@ if (Instruction *LHSI = dyn_cast(Op0)) switch (LHSI->getOpcode()) { case Instruction::GetElementPtr: - if (RHSC->isNullValue()) { // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null - bool isAllZeros = true; - for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i) - if (!isa(LHSI->getOperand(i)) || - !cast(LHSI->getOperand(i))->isNullValue()) { - isAllZeros = false; - break; - } - if (isAllZeros) - return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), - Constant::getNullValue(LHSI->getOperand(0)->getType())); - } + if (RHSC->isNullValue() && + cast(LHSI)->hasAllZeroIndices()) + return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), + Constant::getNullValue(LHSI->getOperand(0)->getType())); break; - case Instruction::PHI: // Only fold icmp into the PHI if the phi and icmp are in the same // block. If in the same block, we're encouraging jump threading. If @@ -6506,6 +6497,14 @@ } } break; + case Instruction::IntToPtr: + // icmp pred inttoptr(X), null -> icmp pred X, 0 + if (RHSC->isNullValue() && TD && + TD->getIntPtrType(RHSC->getContext()) == + LHSI->getOperand(0)->getType()) + return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), + Constant::getNullValue(LHSI->getOperand(0)->getType())); + break; } } Modified: llvm/trunk/test/Transforms/InstCombine/cast_ptr.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/cast_ptr.ll?rev=92403&r1=92402&r2=92403&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/cast_ptr.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/cast_ptr.ll Fri Jan 1 17:09:08 2010 @@ -36,3 +36,12 @@ %r = icmp eq i32 %tmpa, ptrtoint (i8* @global to i32) ret i1 %r } + +define i1 @test4(i32 %A) { + %B = inttoptr i32 %A to i8* + %C = icmp eq i8* %B, null + ret i1 %C +; CHECK: @test4 +; CHECK-NEXT: %C = icmp eq i32 %A, 0 +; CHECK-NEXT: ret i1 %C +} From sabre at nondot.org Fri Jan 1 17:37:34 2010 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 23:37:34 -0000 Subject: [llvm-commits] [llvm] r92404 - /llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h Message-ID: <201001012337.o01NbY3Q005880@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 17:37:34 2010 New Revision: 92404 URL: http://llvm.org/viewvc/llvm-project?rev=92404&view=rev Log: whitespace cleanup Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h?rev=92404&r1=92403&r2=92404&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h Fri Jan 1 17:37:34 2010 @@ -163,7 +163,7 @@ /// The comparison function for sorting the switch case values in the vector. /// WARNING: Case ranges should be disjoint! struct CaseCmp { - bool operator () (const Case& C1, const Case& C2) { + bool operator()(const Case &C1, const Case &C2) { assert(isa(C1.Low) && isa(C2.High)); const ConstantInt* CI1 = cast(C1.Low); const ConstantInt* CI2 = cast(C2.High); @@ -172,12 +172,12 @@ }; struct CaseBitsCmp { - bool operator () (const CaseBits& C1, const CaseBits& C2) { + bool operator()(const CaseBits &C1, const CaseBits &C2) { return C1.Bits > C2.Bits; } }; - size_t Clusterify(CaseVector& Cases, const SwitchInst &SI); + size_t Clusterify(CaseVector &Cases, const SwitchInst &SI); /// CaseBlock - This structure is used to communicate between /// SelectionDAGBuilder and SDISel for the code generation of additional basic @@ -215,7 +215,7 @@ MachineBasicBlock *Default; }; struct JumpTableHeader { - JumpTableHeader(APInt F, APInt L, Value* SV, MachineBasicBlock* H, + JumpTableHeader(APInt F, APInt L, Value *SV, MachineBasicBlock *H, bool E = false): First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {} APInt First; @@ -230,8 +230,8 @@ BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr): Mask(M), ThisBB(T), TargetBB(Tr) { } uint64_t Mask; - MachineBasicBlock* ThisBB; - MachineBasicBlock* TargetBB; + MachineBasicBlock *ThisBB; + MachineBasicBlock *TargetBB; }; typedef SmallVector BitTestInfo; From sabre at nondot.org Fri Jan 1 17:55:05 2010 From: sabre at nondot.org (Chris Lattner) Date: Fri, 01 Jan 2010 23:55:05 -0000 Subject: [llvm-commits] [llvm] r92405 - in /llvm/trunk/test/CodeGen/X86: brcond-srl.ll brcond.ll Message-ID: <201001012355.o01Nt5ds006450@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 17:55:04 2010 New Revision: 92405 URL: http://llvm.org/viewvc/llvm-project?rev=92405&view=rev Log: rename file. Added: llvm/trunk/test/CodeGen/X86/brcond.ll - copied unchanged from r92397, llvm/trunk/test/CodeGen/X86/brcond-srl.ll Removed: llvm/trunk/test/CodeGen/X86/brcond-srl.ll Removed: llvm/trunk/test/CodeGen/X86/brcond-srl.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/X86/brcond-srl.ll?rev=92404&view=auto ============================================================================== --- llvm/trunk/test/CodeGen/X86/brcond-srl.ll (original) +++ llvm/trunk/test/CodeGen/X86/brcond-srl.ll (removed) @@ -1,29 +0,0 @@ -; RUN: llc < %s -march=x86 | FileCheck %s -; rdar://7475489 - -define i32 @t(i32 %a, i32 %b) nounwind ssp { -entry: -; CHECK: t: -; CHECK: xorb -; CHECK-NOT: andb -; CHECK-NOT: shrb -; CHECK: testb $64 - %0 = and i32 %a, 16384 - %1 = icmp ne i32 %0, 0 - %2 = and i32 %b, 16384 - %3 = icmp ne i32 %2, 0 - %4 = xor i1 %1, %3 - br i1 %4, label %bb1, label %bb - -bb: ; preds = %entry - %5 = tail call i32 (...)* @foo() nounwind ; [#uses=1] - ret i32 %5 - -bb1: ; preds = %entry - %6 = tail call i32 (...)* @bar() nounwind ; [#uses=1] - ret i32 %6 -} - -declare i32 @foo(...) - -declare i32 @bar(...) From sabre at nondot.org Fri Jan 1 18:00:03 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 00:00:03 -0000 Subject: [llvm-commits] [llvm] r92406 - in /llvm/trunk: lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp test/CodeGen/X86/brcond.ll Message-ID: <201001020000.o020032H006621@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 18:00:03 2010 New Revision: 92406 URL: http://llvm.org/viewvc/llvm-project?rev=92406&view=rev Log: Teach codegen to handle: (X != null) | (Y != null) --> (X|Y) != 0 (X == null) & (Y == null) --> (X|Y) == 0 so that instcombine can stop doing this for pointers. This is part of PR3351, which is a case where instcombine doing this for pointers (inserting ptrtoint) is pessimizing code. Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp llvm/trunk/test/CodeGen/X86/brcond.ll Modified: llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp?rev=92406&r1=92405&r2=92406&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (original) +++ llvm/trunk/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp Fri Jan 1 18:00:03 2010 @@ -1195,6 +1195,18 @@ return false; } + // Handle: (X != null) | (Y != null) --> (X|Y) != 0 + // Handle: (X == null) & (Y == null) --> (X|Y) == 0 + if (Cases[0].CmpRHS == Cases[1].CmpRHS && + Cases[0].CC == Cases[1].CC && + isa(Cases[0].CmpRHS) && + cast(Cases[0].CmpRHS)->isNullValue()) { + if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) + return false; + if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) + return false; + } + return true; } Modified: llvm/trunk/test/CodeGen/X86/brcond.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/X86/brcond.ll?rev=92406&r1=92405&r2=92406&view=diff ============================================================================== --- llvm/trunk/test/CodeGen/X86/brcond.ll (original) +++ llvm/trunk/test/CodeGen/X86/brcond.ll Fri Jan 1 18:00:03 2010 @@ -1,9 +1,9 @@ ; RUN: llc < %s -march=x86 | FileCheck %s ; rdar://7475489 -define i32 @t(i32 %a, i32 %b) nounwind ssp { +define i32 @test1(i32 %a, i32 %b) nounwind ssp { entry: -; CHECK: t: +; CHECK: test1: ; CHECK: xorb ; CHECK-NOT: andb ; CHECK-NOT: shrb @@ -27,3 +27,43 @@ declare i32 @foo(...) declare i32 @bar(...) + + + +; PR3351 - (P == 0) & (Q == 0) -> (P|Q) == 0 +define i32 @test2(i32* %P, i32* %Q) nounwind ssp { +entry: + %a = icmp eq i32* %P, null ; [#uses=1] + %b = icmp eq i32* %Q, null ; [#uses=1] + %c = and i1 %a, %b + br i1 %c, label %bb1, label %return + +bb1: ; preds = %entry + ret i32 4 + +return: ; preds = %entry + ret i32 192 +; CHECK: test2: +; CHECK: movl 4(%esp), %eax +; CHECK-NEXT: orl 8(%esp), %eax +; CHECK-NEXT: jne LBB2_2 +} + +; PR3351 - (P != 0) | (Q != 0) -> (P|Q) != 0 +define i32 @test3(i32* %P, i32* %Q) nounwind ssp { +entry: + %a = icmp ne i32* %P, null ; [#uses=1] + %b = icmp ne i32* %Q, null ; [#uses=1] + %c = or i1 %a, %b + br i1 %c, label %bb1, label %return + +bb1: ; preds = %entry + ret i32 4 + +return: ; preds = %entry + ret i32 192 +; CHECK: test3: +; CHECK: movl 4(%esp), %eax +; CHECK-NEXT: orl 8(%esp), %eax +; CHECK-NEXT: je LBB3_2 +} From sabre at nondot.org Fri Jan 1 18:22:15 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 00:22:15 -0000 Subject: [llvm-commits] [llvm] r92407 - /llvm/trunk/test/CodeGen/X86/brcond.ll Message-ID: <201001020022.o020MFc1007334@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 18:22:15 2010 New Revision: 92407 URL: http://llvm.org/viewvc/llvm-project?rev=92407&view=rev Log: allow this to work on linux hosts. Modified: llvm/trunk/test/CodeGen/X86/brcond.ll Modified: llvm/trunk/test/CodeGen/X86/brcond.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/X86/brcond.ll?rev=92407&r1=92406&r2=92407&view=diff ============================================================================== --- llvm/trunk/test/CodeGen/X86/brcond.ll (original) +++ llvm/trunk/test/CodeGen/X86/brcond.ll Fri Jan 1 18:22:15 2010 @@ -1,4 +1,4 @@ -; RUN: llc < %s -march=x86 | FileCheck %s +; RUN: llc < %s -mtriple=i386-apple-darwin10 | FileCheck %s ; rdar://7475489 define i32 @test1(i32 %a, i32 %b) nounwind ssp { From sabre at nondot.org Fri Jan 1 18:31:05 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 00:31:05 -0000 Subject: [llvm-commits] [llvm] r92408 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/or.ll Message-ID: <201001020031.o020V5j9007607@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 18:31:05 2010 New Revision: 92408 URL: http://llvm.org/viewvc/llvm-project?rev=92408&view=rev Log: remove the instcombine transformations that are inserting nasty pointer to int casts that confuse later optimizations. See PR3351 for details. This improves but doesn't complete fix 483.xalancbmk because llvm-gcc does this xform in GCC's "fold" routine as well. Clang++ will do better I guess. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/or.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92408&r1=92407&r2=92408&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Fri Jan 1 18:31:05 2010 @@ -4166,21 +4166,6 @@ /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible. Instruction *InstCombiner::FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS) { - // (icmp eq A, null) & (icmp eq B, null) --> - // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0) - if (TD && - LHS->getPredicate() == ICmpInst::ICMP_EQ && - RHS->getPredicate() == ICmpInst::ICMP_EQ && - isa(LHS->getOperand(1)) && - isa(RHS->getOperand(1))) { - const Type *IntPtrTy = TD->getIntPtrType(I.getContext()); - Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy); - Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy); - Value *NewOr = Builder->CreateOr(A, B); - return new ICmpInst(ICmpInst::ICMP_EQ, NewOr, - Constant::getNullValue(IntPtrTy)); - } - Value *Val, *Val2; ConstantInt *LHSCst, *RHSCst; ICmpInst::Predicate LHSCC, RHSCC; @@ -4861,21 +4846,6 @@ /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible. Instruction *InstCombiner::FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS) { - // (icmp ne A, null) | (icmp ne B, null) --> - // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0) - if (TD && - LHS->getPredicate() == ICmpInst::ICMP_NE && - RHS->getPredicate() == ICmpInst::ICMP_NE && - isa(LHS->getOperand(1)) && - isa(RHS->getOperand(1))) { - const Type *IntPtrTy = TD->getIntPtrType(I.getContext()); - Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy); - Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy); - Value *NewOr = Builder->CreateOr(A, B); - return new ICmpInst(ICmpInst::ICMP_NE, NewOr, - Constant::getNullValue(IntPtrTy)); - } - Value *Val, *Val2; ConstantInt *LHSCst, *RHSCst; ICmpInst::Predicate LHSCC, RHSCC; Modified: llvm/trunk/test/Transforms/InstCombine/or.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/or.ll?rev=92408&r1=92407&r2=92408&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/or.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/or.ll Fri Jan 1 18:31:05 2010 @@ -269,21 +269,6 @@ } ; PR5634 -define i1 @test27(i32* %A, i32* %B) { - %C1 = icmp eq i32* %A, null - %C2 = icmp eq i32* %B, null - ; (A == 0) & (A == 0) --> (A|B) == 0 - %D = and i1 %C1, %C2 - ret i1 %D -; CHECK: @test27 -; CHECK: ptrtoint i32* %A -; CHECK: ptrtoint i32* %B -; CHECK: or i32 -; CHECK: icmp eq i32 {{.*}}, 0 -; CHECK: ret i1 -} - -; PR5634 define i1 @test28(i32 %A, i32 %B) { %C1 = icmp ne i32 %A, 0 %C2 = icmp ne i32 %B, 0 From sabre at nondot.org Fri Jan 1 19:22:23 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 01:22:23 -0000 Subject: [llvm-commits] [llvm] r92410 - /llvm/trunk/lib/Analysis/ConstantFolding.cpp Message-ID: <201001020122.o021MNT5009308@zion.cs.uiuc.edu> Author: lattner Date: Fri Jan 1 19:22:23 2010 New Revision: 92410 URL: http://llvm.org/viewvc/llvm-project?rev=92410&view=rev Log: constant fold nasty constant expressions formed by llvm-gcc, wrapping up PR3351. Modified: llvm/trunk/lib/Analysis/ConstantFolding.cpp Modified: llvm/trunk/lib/Analysis/ConstantFolding.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/ConstantFolding.cpp?rev=92410&r1=92409&r2=92410&view=diff ============================================================================== --- llvm/trunk/lib/Analysis/ConstantFolding.cpp (original) +++ llvm/trunk/lib/Analysis/ConstantFolding.cpp Fri Jan 1 19:22:23 2010 @@ -718,14 +718,13 @@ switch (Opcode) { default: return 0; + case Instruction::ICmp: + case Instruction::FCmp: assert(0 && "Invalid for compares"); case Instruction::Call: if (Function *F = dyn_cast(Ops[0])) if (canConstantFoldCallTo(F)) return ConstantFoldCall(F, Ops+1, NumOps-1); return 0; - case Instruction::ICmp: - case Instruction::FCmp: - llvm_unreachable("This function is invalid for compares: no predicate specified"); case Instruction::PtrToInt: // If the input is a inttoptr, eliminate the pair. This requires knowing // the width of a pointer, so it can't be done in ConstantExpr::getCast. @@ -877,6 +876,20 @@ CE1->getOperand(0), TD); } } + + // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0) + // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0) + if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) && + CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) { + Constant *LHS = + ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,TD); + Constant *RHS = + ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,TD); + unsigned OpC = + Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; + Constant *Ops[] = { LHS, RHS }; + return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, 2, TD); + } } return ConstantExpr::getCompare(Predicate, Ops0, Ops1); From nicholas at mxc.ca Fri Jan 1 20:56:27 2010 From: nicholas at mxc.ca (Nick Lewycky) Date: Fri, 01 Jan 2010 21:56:27 -0500 Subject: [llvm-commits] [llvm] r92408 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/or.ll In-Reply-To: <201001020031.o020V5j9007607@zion.cs.uiuc.edu> References: <201001020031.o020V5j9007607@zion.cs.uiuc.edu> Message-ID: <4B3EB5DB.2070900@mxc.ca> Chris Lattner wrote: > Author: lattner > Date: Fri Jan 1 18:31:05 2010 > New Revision: 92408 > > URL: http://llvm.org/viewvc/llvm-project?rev=92408&view=rev > Log: > remove the instcombine transformations that are inserting nasty > pointer to int casts that confuse later optimizations. See PR3351 > for details. > > This improves but doesn't complete fix 483.xalancbmk because llvm-gcc > does this xform in GCC's "fold" routine as well. Clang++ will do > better I guess. > So do we want instcombine to turn '((ptrtoint P) or (ptrtoint Q)) == null' into '(P == null) and (Q == null)'? Operating under the assumption that we do, I've prepared a patch, attached. Nick > Modified: > llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp > llvm/trunk/test/Transforms/InstCombine/or.ll > > Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92408&r1=92407&r2=92408&view=diff > > ============================================================================== > --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) > +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Fri Jan 1 18:31:05 2010 > @@ -4166,21 +4166,6 @@ > /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible. > Instruction *InstCombiner::FoldAndOfICmps(Instruction &I, > ICmpInst *LHS, ICmpInst *RHS) { > - // (icmp eq A, null) & (icmp eq B, null) --> > - // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0) > - if (TD && > - LHS->getPredicate() == ICmpInst::ICMP_EQ && > - RHS->getPredicate() == ICmpInst::ICMP_EQ && > - isa(LHS->getOperand(1)) && > - isa(RHS->getOperand(1))) { > - const Type *IntPtrTy = TD->getIntPtrType(I.getContext()); > - Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy); > - Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy); > - Value *NewOr = Builder->CreateOr(A, B); > - return new ICmpInst(ICmpInst::ICMP_EQ, NewOr, > - Constant::getNullValue(IntPtrTy)); > - } > - > Value *Val, *Val2; > ConstantInt *LHSCst, *RHSCst; > ICmpInst::Predicate LHSCC, RHSCC; > @@ -4861,21 +4846,6 @@ > /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible. > Instruction *InstCombiner::FoldOrOfICmps(Instruction &I, > ICmpInst *LHS, ICmpInst *RHS) { > - // (icmp ne A, null) | (icmp ne B, null) --> > - // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0) > - if (TD && > - LHS->getPredicate() == ICmpInst::ICMP_NE && > - RHS->getPredicate() == ICmpInst::ICMP_NE && > - isa(LHS->getOperand(1)) && > - isa(RHS->getOperand(1))) { > - const Type *IntPtrTy = TD->getIntPtrType(I.getContext()); > - Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy); > - Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy); > - Value *NewOr = Builder->CreateOr(A, B); > - return new ICmpInst(ICmpInst::ICMP_NE, NewOr, > - Constant::getNullValue(IntPtrTy)); > - } > - > Value *Val, *Val2; > ConstantInt *LHSCst, *RHSCst; > ICmpInst::Predicate LHSCC, RHSCC; > > Modified: llvm/trunk/test/Transforms/InstCombine/or.ll > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/or.ll?rev=92408&r1=92407&r2=92408&view=diff > > ============================================================================== > --- llvm/trunk/test/Transforms/InstCombine/or.ll (original) > +++ llvm/trunk/test/Transforms/InstCombine/or.ll Fri Jan 1 18:31:05 2010 > @@ -269,21 +269,6 @@ > } > > ; PR5634 > -define i1 @test27(i32* %A, i32* %B) { > - %C1 = icmp eq i32* %A, null > - %C2 = icmp eq i32* %B, null > - ; (A == 0) & (A == 0) --> (A|B) == 0 > - %D = and i1 %C1, %C2 > - ret i1 %D > -; CHECK: @test27 > -; CHECK: ptrtoint i32* %A > -; CHECK: ptrtoint i32* %B > -; CHECK: or i32 > -; CHECK: icmp eq i32 {{.*}}, 0 > -; CHECK: ret i1 > -} > - > -; PR5634 > define i1 @test28(i32 %A, i32 %B) { > %C1 = icmp ne i32 %A, 0 > %C2 = icmp ne i32 %B, 0 > > > _______________________________________________ > llvm-commits mailing list > llvm-commits at cs.uiuc.edu > http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits > -------------- next part -------------- A non-text attachment was scrubbed... Name: fold-or.patch Type: text/x-patch Size: 2373 bytes Desc: not available Url : http://lists.cs.uiuc.edu/pipermail/llvm-commits/attachments/20100101/4a47c290/attachment.bin From sabre at nondot.org Sat Jan 2 00:42:36 2010 From: sabre at nondot.org (Chris Lattner) Date: Fri, 1 Jan 2010 22:42:36 -0800 Subject: [llvm-commits] [llvm] r92408 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/or.ll In-Reply-To: <4B3EB5DB.2070900@mxc.ca> References: <201001020031.o020V5j9007607@zion.cs.uiuc.edu> <4B3EB5DB.2070900@mxc.ca> Message-ID: On Jan 1, 2010, at 6:56 PM, Nick Lewycky wrote: > Chris Lattner wrote: >> Author: lattner >> Date: Fri Jan 1 18:31:05 2010 >> New Revision: 92408 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=92408&view=rev >> Log: >> remove the instcombine transformations that are inserting nasty >> pointer to int casts that confuse later optimizations. See PR3351 >> for details. >> >> This improves but doesn't complete fix 483.xalancbmk because llvm-gcc >> does this xform in GCC's "fold" routine as well. Clang++ will do >> better I guess. >> > So do we want instcombine to turn '((ptrtoint P) or (ptrtoint Q)) == null' into '(P == null) and (Q == null)'? Sure, can't hurt. > Operating under the assumption that we do, I've prepared a patch, attached. Please use match() to simplify the matching logic. -Chris From sabre at nondot.org Sat Jan 2 02:12:07 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 08:12:07 -0000 Subject: [llvm-commits] [llvm] r92411 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/load-cmp.ll Message-ID: <201001020812.o028C8QU021555@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 02:12:04 2010 New Revision: 92411 URL: http://llvm.org/viewvc/llvm-project?rev=92411&view=rev Log: Teach instcombine to fold compares of loads from constant arrays with variable indices into a comparison of the index with a constant. The most common occurrence of this that I see by far is stuff like: if ("foobar"[i] == '\0') ... which we compile into: if (i == 6), saving a load and materialization of the global address. This also exposes loop trip count information to later passes in many cases. This triggers hundreds of times in xalancbmk, which is where I first noticed it, but it also triggers in many other apps. Here are a few interesting ones from various apps: @must_be_connected_without = internal constant [8 x i8*] [i8* getelementptr inbounds ([3 x i8]* @.str64320, i64 0, i64 0), i8* getelementptr inbounds ([3 x i8]* @.str27283, i64 0, i64 0), i8* getelementptr inbounds ([4 x i8]* @.str71327, i64 0, i64 0), i8* getelementptr inbounds ([4 x i8]* @.str72328, i64 0, i64 0), i8* getelementptr inbounds ([3 x i8]* @.str18274, i64 0, i64 0), i8* getelementptr inbounds ([6 x i8]* @.str11267, i64 0, i64 0), i8* getelementptr inbounds ([3 x i8]* @.str32288, i64 0, i64 0), i8* null], align 32 ; <[8 x i8*]*> [#uses=2] %scevgep.i = getelementptr [8 x i8*]* @must_be_connected_without, i64 0, i64 %indvar.i ; [#uses=1] %17 = load ... %18 = icmp eq i8* %17, null ; [#uses=1] -> icmp eq i64 %indvar.i, 7 @yytable1095 = internal constant [84 x i8] c"\12\01(\05\06\07\08\09\0A\0B\0C\0D\0E1\0F\10\11266\1D: \10\11,-,0\03'\10\11B6\04\17&\18\1945\05\06\07\08\09\0A\0B\0C\0D\0E\1E\0F\10\11*\1A\1B\1C$3+>#%; [#uses=2] %57 = getelementptr inbounds [84 x i8]* @yytable1095, i64 0, i64 %56 ; [#uses=1] %mode.0.in = getelementptr inbounds [9 x i32]* @mb_mode_table, i64 0, i64 %.pn ; [#uses=1] load ... %64 = icmp eq i8 %58, 4 ; [#uses=1] -> icmp eq i64 %.pn, 35 ; [#uses=0] @gsm_DLB = internal constant [4 x i16] [i16 6554, i16 16384, i16 26214, i16 32767] %scevgep.i = getelementptr [4 x i16]* @gsm_DLB, i64 0, i64 %indvar.i ; [#uses=1] %425 = load %scevgep.i %426 = icmp eq i16 %425, -32768 ; [#uses=0] -> false Added: llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92411&r1=92410&r2=92411&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 02:12:04 2010 @@ -258,6 +258,8 @@ Instruction *commonShiftTransforms(BinaryOperator &I); Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI, Constant *RHSC); + Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, + GlobalVariable *GV, CmpInst &ICI); Instruction *visitFCmpInst(FCmpInst &I); Instruction *visitICmpInst(ICmpInst &I); Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI); @@ -6015,6 +6017,112 @@ return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); } + +/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern: +/// cmp pred (load (gep GV, ...)), cmpcst +/// where GV is a global variable with a constant initializer. Try to simplify +/// this into one or two simpler comparisons that do not need the load. For +/// example, we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into +/// "icmp eq i, 3". We assume that eliminating a load is always goodness. +Instruction *InstCombiner:: +FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV, + CmpInst &ICI) { + + // There are many forms of this optimization we can handle, for now, just do + // the simple index into a single-dimensional array. + // + // Require: GEP GV, 0, i + if (GEP->getNumOperands() != 3 || + !isa(GEP->getOperand(1)) || + !cast(GEP->getOperand(1))->isZero()) + return 0; + + ConstantArray *Init = dyn_cast(GV->getInitializer()); + if (Init == 0 || Init->getNumOperands() > 1024) return 0; + + + // Variables for our state machines. + + // OnlyTrueElement - Used to emit a comparison of "i == 47", where 47 is the + // only index the condition is true for. The values are -1 -> undef, + // -2 -> overdef, >= 0 -> that index is true. + int OnlyTrueElement = -1; + + // OnlyFalseElement - Used to emit a comparison of "i != 47", where 47 is the + // only index the condition is false for. The values are -1 -> undef, + // -2 -> overdef, >= 0 -> that index is false. + int OnlyFalseElement = -1; + + // Scan the array and see if one of our patterns matches. + Constant *CompareRHS = cast(ICI.getOperand(1)); + for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { + // Find out if the comparison would be true or false for the i'th element. + Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), + Init->getOperand(i), + CompareRHS, TD); + // If the result is undef for this element, ignore it. + if (isa(C)) continue; + + // If we can't compute the result for any of the elements, we have to give + // up evaluating the entire conditional. + if (!isa(C)) return 0; + + // Otherwise, we know if the comparison is true or false for this element, + // update our state machines. + bool IsTrueForElt = !cast(C)->isZero(); + + // State machine for single index comparison. + if (IsTrueForElt) { + // If undefined -> defined. Otherwise -> overdefined. + OnlyTrueElement = OnlyTrueElement == -1 ? i : -2; + } else { + // If undefined -> defined. Otherwise -> overdefined. + OnlyFalseElement = OnlyFalseElement == -1 ? i : -2; + } + + // If all of our states become overdefined, bail out early. + if (OnlyTrueElement == -2 && OnlyFalseElement == -2) + return 0; + } + + // Now that we've scanned the entire array, emit our new comparison(s). We + // order the state machines in complexity of the generated code. + if (OnlyTrueElement != -2) { + // None true -> false. + if (OnlyTrueElement == -1) + return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context)); + + // True for one element -> 'i == 47'. + return new ICmpInst(ICmpInst::ICMP_EQ, GEP->getOperand(2), + ConstantInt::get(GEP->getOperand(2)->getType(), + OnlyTrueElement)); + } + + if (OnlyFalseElement != -2) { + // None false -> true. + if (OnlyFalseElement == -1) + return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context)); + + return new ICmpInst(ICmpInst::ICMP_NE, GEP->getOperand(2), + ConstantInt::get(GEP->getOperand(2)->getType(), + OnlyFalseElement)); + } + + assert(0 && "Should have bailed out early"); + + // TODO: FCMP. + + // TODO: Range check. + + // TODO: If the global array has 32 (or 64 if native!) or less entries, we + // can turn this into something like: + // ((magicbitconstant >> i) & 1) != 0) + // where we populate magicbitconstant with 0101010 based on the comparison + // results. + return 0; +} + + Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) { bool Changed = false; @@ -6175,7 +6283,7 @@ Value *A = 0, *B = 0; // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B) - if (I.isEquality() && CI->isNullValue() && + if (I.isEquality() && CI->isZero() && match(Op0, m_Sub(m_Value(A), m_Value(B)))) { // (icmp cond A B) if cond is equality return new ICmpInst(I.getPredicate(), A, B); @@ -6475,6 +6583,17 @@ return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), Constant::getNullValue(LHSI->getOperand(0)->getType())); break; + + case Instruction::Load: + if (GetElementPtrInst *GEP = + dyn_cast(LHSI->getOperand(0))) + if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) + if (GV->isConstant() && GV->hasDefinitiveInitializer() && + !cast(LHSI)->isVolatile()) { + if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) + return Res; + } + break; } } Added: llvm/trunk/test/Transforms/InstCombine/load-cmp.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/load-cmp.ll?rev=92411&view=auto ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/load-cmp.ll (added) +++ llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Sat Jan 2 02:12:04 2010 @@ -0,0 +1,25 @@ +; RUN: opt < %s -instcombine -S | FileCheck %s + + at G16 = internal constant [10 x i16] [i16 35, i16 82, i16 69, i16 81, i16 85, + i16 73, i16 82, i16 69, i16 68, i16 0] + +define i1 @test1(i32 %X) { + %P = getelementptr [10 x i16]* @G16, i32 0, i32 %X + %Q = load i16* %P + %R = icmp eq i16 %Q, 0 + ret i1 %R +; CHECK: @test1 +; CHECK-NEXT: %R = icmp eq i32 %X, 9 +; CHECK-NEXT: ret i1 %R +} + +define i1 @test2(i32 %X) { + %P = getelementptr [10 x i16]* @G16, i32 0, i32 %X + %Q = load i16* %P + %R = icmp slt i16 %Q, 85 + ret i1 %R +; CHECK: @test2 +; CHECK-NEXT: %R = icmp ne i32 %X, 4 +; CHECK-NEXT: ret i1 %R +} + From sabre at nondot.org Sat Jan 2 02:20:51 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 08:20:51 -0000 Subject: [llvm-commits] [llvm] r92412 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/load-cmp.ll Message-ID: <201001020820.o028KpYA021861@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 02:20:51 2010 New Revision: 92412 URL: http://llvm.org/viewvc/llvm-project?rev=92412&view=rev Log: enhance the previous optimization to work with fcmp in addition to icmp. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92412&r1=92411&r2=92412&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 02:20:51 2010 @@ -6180,7 +6180,7 @@ if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC)) return NV; break; - case Instruction::Select: + case Instruction::Select: { // If either operand of the select is a constant, we can fold the // comparison into the select arms, which will cause one to be // constant folded and the select turned into a bitwise or. @@ -6205,6 +6205,20 @@ return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); break; } + case Instruction::Load: + if (GetElementPtrInst *GEP = + dyn_cast(LHSI->getOperand(0))) { + if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) + if (GV->isConstant() && GV->hasDefinitiveInitializer() && + !cast(LHSI)->isVolatile()) + if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) + return Res; + //errs() << "NOT HANDLED: " << *GV << "\n"; + //errs() << "\t" << *GEP << "\n"; + //errs() << "\t " << I << "\n\n\n"; + } + break; + } } return Changed ? &I : 0; @@ -6586,13 +6600,16 @@ case Instruction::Load: if (GetElementPtrInst *GEP = - dyn_cast(LHSI->getOperand(0))) + dyn_cast(LHSI->getOperand(0))) { if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) if (GV->isConstant() && GV->hasDefinitiveInitializer() && - !cast(LHSI)->isVolatile()) { + !cast(LHSI)->isVolatile()) if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) return Res; - } + //errs() << "NOT HANDLED: " << *GV << "\n"; + //errs() << "\t" << *GEP << "\n"; + //errs() << "\t " << I << "\n\n\n"; + } break; } } Modified: llvm/trunk/test/Transforms/InstCombine/load-cmp.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/load-cmp.ll?rev=92412&r1=92411&r2=92412&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/load-cmp.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Sat Jan 2 02:20:51 2010 @@ -2,6 +2,7 @@ @G16 = internal constant [10 x i16] [i16 35, i16 82, i16 69, i16 81, i16 85, i16 73, i16 82, i16 69, i16 68, i16 0] + at GD = internal constant [3 x double] [double 1.0, double 4.0, double -20.0] define i1 @test1(i32 %X) { %P = getelementptr [10 x i16]* @G16, i32 0, i32 %X @@ -23,3 +24,13 @@ ; CHECK-NEXT: ret i1 %R } +define i1 @test3(i32 %X) { + %P = getelementptr [3 x double]* @GD, i32 0, i32 %X + %Q = load double* %P + %R = fcmp oeq double %Q, 1.0 + ret i1 %R +; CHECK: @test3 +; CHECK-NEXT: %R = icmp eq i32 %X, 0 +; CHECK-NEXT: ret i1 %R +} + From foldr at codedgers.com Sat Jan 2 02:27:10 2010 From: foldr at codedgers.com (Mikhail Glushenkov) Date: Sat, 02 Jan 2010 08:27:10 -0000 Subject: [llvm-commits] [llvm] r92413 - /llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Message-ID: <201001020827.o028RALG022031@zion.cs.uiuc.edu> Author: foldr Date: Sat Jan 2 02:27:10 2010 New Revision: 92413 URL: http://llvm.org/viewvc/llvm-project?rev=92413&view=rev Log: Apparently, it is OK for -MT to be specified several times. Modified: llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Modified: llvm/trunk/tools/llvmc/plugins/Base/Base.td.in URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/tools/llvmc/plugins/Base/Base.td.in?rev=92413&r1=92412&r2=92413&view=diff ============================================================================== --- llvm/trunk/tools/llvmc/plugins/Base/Base.td.in (original) +++ llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Sat Jan 2 02:27:10 2010 @@ -56,7 +56,7 @@ (help "A deprecated synonym for -mtune"), (hidden)), (parameter_option "MF", (help "Specify a file to write dependencies to"), (hidden)), - (parameter_option "MT", + (parameter_list_option "MT", (help "Change the name of the rule emitted by dependency generation"), (hidden)), (parameter_list_option "include", From foldr at codedgers.com Sat Jan 2 02:27:23 2010 From: foldr at codedgers.com (Mikhail Glushenkov) Date: Sat, 02 Jan 2010 08:27:23 -0000 Subject: [llvm-commits] [llvm] r92414 - /llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Message-ID: <201001020827.o028RN70022051@zion.cs.uiuc.edu> Author: foldr Date: Sat Jan 2 02:27:23 2010 New Revision: 92414 URL: http://llvm.org/viewvc/llvm-project?rev=92414&view=rev Log: Forward -O0 to llvm-gcc. Modified: llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Modified: llvm/trunk/tools/llvmc/plugins/Base/Base.td.in URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/tools/llvmc/plugins/Base/Base.td.in?rev=92414&r1=92413&r2=92414&view=diff ============================================================================== --- llvm/trunk/tools/llvmc/plugins/Base/Base.td.in (original) +++ llvm/trunk/tools/llvmc/plugins/Base/Base.td.in Sat Jan 2 02:27:23 2010 @@ -139,6 +139,7 @@ (not_empty "m"), (forward "m"), (switch_on "m32"), (forward "m32"), (switch_on "m64"), (forward "m64"), + (switch_on "O0"), (forward "O0"), (switch_on "O1"), (forward "O1"), (switch_on "O2"), (forward "O2"), (switch_on "O3"), (forward "O3"), From eli.friedman at gmail.com Sat Jan 2 02:36:18 2010 From: eli.friedman at gmail.com (Eli Friedman) Date: Sat, 2 Jan 2010 00:36:18 -0800 Subject: [llvm-commits] [llvm] r92412 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/load-cmp.ll In-Reply-To: <201001020820.o028KpYA021861@zion.cs.uiuc.edu> References: <201001020820.o028KpYA021861@zion.cs.uiuc.edu> Message-ID: On Sat, Jan 2, 2010 at 12:20 AM, Chris Lattner wrote: > Author: lattner > Date: Sat Jan ?2 02:20:51 2010 > New Revision: 92412 > > URL: http://llvm.org/viewvc/llvm-project?rev=92412&view=rev > Log: > enhance the previous optimization to work with fcmp in addition > to icmp. > > Modified: > ? ?llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp > ? ?llvm/trunk/test/Transforms/InstCombine/load-cmp.ll > > Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92412&r1=92411&r2=92412&view=diff > > ============================================================================== > --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) > +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan ?2 02:20:51 2010 > @@ -6180,7 +6180,7 @@ > ? ? ? ? if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC)) > ? ? ? ? ? return NV; > ? ? ? ? break; > - ? ? ?case Instruction::Select: > + ? ? ?case Instruction::Select: { > ? ? ? ? // If either operand of the select is a constant, we can fold the > ? ? ? ? // comparison into the select arms, which will cause one to be > ? ? ? ? // constant folded and the select turned into a bitwise or. > @@ -6205,6 +6205,20 @@ > ? ? ? ? ? return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); > ? ? ? ? break; > ? ? ? } > + ? ?case Instruction::Load: > + ? ? ?if (GetElementPtrInst *GEP = > + ? ? ? ? ?dyn_cast(LHSI->getOperand(0))) { > + ? ? ? ?if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) > + ? ? ? ? ?if (GV->isConstant() && GV->hasDefinitiveInitializer() && > + ? ? ? ? ? ? ?!cast(LHSI)->isVolatile()) > + ? ? ? ? ? ?if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) > + ? ? ? ? ? ? ?return Res; > + ? ? ? ? ? ?//errs() << "NOT HANDLED: " << *GV << "\n"; > + ? ? ? ? ? ?//errs() << "\t" << *GEP << "\n"; > + ? ? ? ? ? ?//errs() << "\t " << I << "\n\n\n"; I assume you didn't mean to add the debugging output? -Eli From sabre at nondot.org Sat Jan 2 02:40:13 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 2 Jan 2010 00:40:13 -0800 Subject: [llvm-commits] [llvm] r92412 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/load-cmp.ll In-Reply-To: References: <201001020820.o028KpYA021861@zion.cs.uiuc.edu> Message-ID: On Jan 2, 2010, at 12:36 AM, Eli Friedman wrote: >> + case Instruction::Load: >> + if (GetElementPtrInst *GEP = >> + dyn_cast(LHSI->getOperand(0))) { >> + if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) >> + if (GV->isConstant() && GV->hasDefinitiveInitializer() && >> + !cast(LHSI)->isVolatile()) >> + if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) >> + return Res; >> + //errs() << "NOT HANDLED: " << *GV << "\n"; >> + //errs() << "\t" << *GEP << "\n"; >> + //errs() << "\t " << I << "\n\n\n"; > > I assume you didn't mean to add the debugging output? I actually did, I'll remove it when I'm done generalizing the xform. -Chris From sabre at nondot.org Sat Jan 2 02:56:53 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 08:56:53 -0000 Subject: [llvm-commits] [llvm] r92415 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/load-cmp.ll Message-ID: <201001020856.o028urFt031505@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 02:56:52 2010 New Revision: 92415 URL: http://llvm.org/viewvc/llvm-project?rev=92415&view=rev Log: enhance the compare/load/index optimization to work on *any* load from a global with 32/64 elements or less (depending on whether i64 is native on the target), generating a bitshift idiom to determine the result. For example, on test4 we produce: define i1 @test4(i32 %X) { %1 = lshr i32 933, %X ; [#uses=1] %2 = and i32 %1, 1 ; [#uses=1] %R = icmp ne i32 %2, 0 ; [#uses=1] ret i1 %R } This triggers in a number of interesting cases, for example, here's an fp case: @A.3255 = internal constant [4 x double] [double 4.100000e+00, double -3.900000e+00, double -1.000000e+00, double 1.000000e+00], align 32 ; <[4 x double]*> [#uses=7] .. %7 = fcmp olt double %3, 0.000000e+00 In this case we make the slen2_tab global dead, which is nice: @slen2_tab = internal constant [16 x i32] [i32 0, i32 1, i32 2, i32 3, i32 0, i32 1, i32 2, i32 3, i32 1, i32 2, i32 3, i32 1, i32 2, i32 3, i32 2, i32 3], align 32 ; <[16 x i32]*> [#uses=1] .. %204 = icmp eq i32 %46, 0 Perl has a bunch of these, also on the 'Perl_regkind' array: @Perl_yygindex = internal constant [51 x i16] [i16 0, i16 0, i16 0, i16 0, i16 374, i16 351, i16 0, i16 -12, i16 0, i16 946, i16 413, i16 -83, i16 0, i16 0, i16 0, i16 -311, i16 -13, i16 4007, i16 2893, i16 0, i16 0, i16 0, i16 0, i16 0, i16 372, i16 -8, i16 0, i16 0, i16 246, i16 -131, i16 43, i16 86, i16 208, i16 -45, i16 -169, i16 987, i16 0, i16 0, i16 0, i16 0, i16 308, i16 0, i16 -271, i16 0, i16 0, i16 0, i16 0, i16 0, i16 0, i16 0, i16 0], align 32 ; <[51 x i16]*> [#uses=1] .. %1364 = icmp eq i16 %1361, 0 186.crafty really likes this on 64-bit machines, because it triggers on a bunch of globals like this: @white_outpost = internal constant [64 x i8] c"\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\02\02\00\00\00\00\00\04\05\05\04\00\00\00\00\03\06\06\03\00\00\00\00\00\01\01\00\00\00\00\00\00\00\00\00\00\00", align 32 ; <[64 x i8]*> [#uses=2] However the big winner is 403.gcc, which triggers hundreds of times, eliminating all the accesses to the 57-element arrays 'mode_class', mode_unit_size, mode_bitsize, regclass_map, etc. go 64-bit machines :) Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92415&r1=92414&r2=92415&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 02:56:52 2010 @@ -6053,6 +6053,12 @@ // -2 -> overdef, >= 0 -> that index is false. int OnlyFalseElement = -1; + // MagicBitvector - This is a magic bitvector where we set a bit if the + // comparison is true for element 'i'. If there are 64 elements or less in + // the array, this will fully represent all the comparison results. + uint64_t MagicBitvector = 0; + + // Scan the array and see if one of our patterns matches. Constant *CompareRHS = cast(ICI.getOperand(1)); for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { @@ -6080,8 +6086,12 @@ OnlyFalseElement = OnlyFalseElement == -1 ? i : -2; } + // If this element is in range, update our magic bitvector. + if (i < 64 && IsTrueForElt) + MagicBitvector |= 1 << i; + // If all of our states become overdefined, bail out early. - if (OnlyTrueElement == -2 && OnlyFalseElement == -2) + if (i >= 64 && OnlyTrueElement == -2 && OnlyFalseElement == -2) return 0; } @@ -6108,17 +6118,24 @@ OnlyFalseElement)); } - assert(0 && "Should have bailed out early"); - - // TODO: FCMP. - - // TODO: Range check. + // If a 32-bit or 64-bit magic bitvector captures the entire comparison state + // of this load, replace it with computation that does: + // ((magic_cst >> i) & 1) != 0 + if (Init->getNumOperands() <= 32 || + (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) { + const Type *Ty; + if (Init->getNumOperands() <= 32) + Ty = Type::getInt32Ty(Init->getContext()); + else + Ty = Type::getInt64Ty(Init->getContext()); + Value *V = Builder->CreateIntCast(GEP->getOperand(2), Ty, false); + V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); + V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V); + return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); + } - // TODO: If the global array has 32 (or 64 if native!) or less entries, we - // can turn this into something like: - // ((magicbitconstant >> i) & 1) != 0) - // where we populate magicbitconstant with 0101010 based on the comparison - // results. + // TODO: Range check, two compares. + return 0; } Modified: llvm/trunk/test/Transforms/InstCombine/load-cmp.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/load-cmp.ll?rev=92415&r1=92414&r2=92415&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/load-cmp.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Sat Jan 2 02:56:52 2010 @@ -34,3 +34,14 @@ ; CHECK-NEXT: ret i1 %R } +define i1 @test4(i32 %X) { + %P = getelementptr [10 x i16]* @G16, i32 0, i32 %X + %Q = load i16* %P + %R = icmp sle i16 %Q, 73 + ret i1 %R +; CHECK: @test4 +; CHECK-NEXT: lshr i32 933, %X +; CHECK-NEXT: and i32 {{.*}}, 1 +; CHECK-NEXT: %R = icmp ne i32 {{.*}}, 0 +; CHECK-NEXT: ret i1 %R +} From sabre at nondot.org Sat Jan 2 03:22:14 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 09:22:14 -0000 Subject: [llvm-commits] [llvm] r92416 - /llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Message-ID: <201001020922.o029MF0o005993@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 03:22:13 2010 New Revision: 92416 URL: http://llvm.org/viewvc/llvm-project?rev=92416&view=rev Log: fix a miscompilation I introduced of cdecl with a late change. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92416&r1=92415&r2=92416&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 03:22:13 2010 @@ -6088,7 +6088,7 @@ // If this element is in range, update our magic bitvector. if (i < 64 && IsTrueForElt) - MagicBitvector |= 1 << i; + MagicBitvector |= 1ULL << i; // If all of our states become overdefined, bail out early. if (i >= 64 && OnlyTrueElement == -2 && OnlyFalseElement == -2) From sabre at nondot.org Sat Jan 2 03:35:17 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 09:35:17 -0000 Subject: [llvm-commits] [llvm] r92417 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/load-cmp.ll Message-ID: <201001020935.o029ZIrt006358@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 03:35:17 2010 New Revision: 92417 URL: http://llvm.org/viewvc/llvm-project?rev=92417&view=rev Log: Generalize the previous xform to handle cases where exactly two elements match or don't match with two comparisons. For example, the testcase compiles into: define i1 @test5(i32 %X) { %1 = icmp eq i32 %X, 2 ; [#uses=1] %2 = icmp eq i32 %X, 7 ; [#uses=1] %R = or i1 %1, %2 ; [#uses=1] ret i1 %R } This generalizes the previous xforms when the array is larger than 64 elements (and this case matches) and generates better code for cases where it overlaps with the magic bitshift case. This generalizes more cases than you might expect. For example, 400.perlbmk has: @PL_utf8skip = constant [256 x i8] c"\01\01\01\... %15 = icmp ult i8 %7, 7 403.gcc has: @rid_to_yy = internal constant [114 x i16] [i16 259, i16 260, ... %18 = icmp eq i16 %16, 295 and xalancbmk has a bunch of examples, such as _ZN11xercesc_2_5L15gCombiningCharsE and _ZN11xercesc_2_5L10gBaseCharsE. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92417&r1=92416&r2=92417&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 03:35:17 2010 @@ -6043,15 +6043,16 @@ // Variables for our state machines. - // OnlyTrueElement - Used to emit a comparison of "i == 47", where 47 is the - // only index the condition is true for. The values are -1 -> undef, - // -2 -> overdef, >= 0 -> that index is true. - int OnlyTrueElement = -1; - - // OnlyFalseElement - Used to emit a comparison of "i != 47", where 47 is the - // only index the condition is false for. The values are -1 -> undef, - // -2 -> overdef, >= 0 -> that index is false. - int OnlyFalseElement = -1; + // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form + // "i == 47 | i == 87", where 47 is the first index the condition is true for, + // and 87 is the second (and last) index. FirstTrueElement is -1 when + // undefined, otherwise set to the first true element. SecondTrueElement is + // -1 when undefined, -2 when overdefined and >= 0 when that index is true. + int FirstTrueElement = -1, SecondTrueElement = -1; + + // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the + // form "i != 47 & i != 87". Same state transitions as for true elements. + int FirstFalseElement = -1, SecondFalseElement = -1; // MagicBitvector - This is a magic bitvector where we set a bit if the // comparison is true for element 'i'. If there are 64 elements or less in @@ -6079,11 +6080,21 @@ // State machine for single index comparison. if (IsTrueForElt) { - // If undefined -> defined. Otherwise -> overdefined. - OnlyTrueElement = OnlyTrueElement == -1 ? i : -2; + // Update the TrueElement state machine. + if (FirstTrueElement == -1) + FirstTrueElement = i; + else if (SecondTrueElement == -1) + SecondTrueElement = i; + else + SecondTrueElement = -2; } else { - // If undefined -> defined. Otherwise -> overdefined. - OnlyFalseElement = OnlyFalseElement == -1 ? i : -2; + // Update the FalseElement state machine. + if (FirstFalseElement == -1) + FirstFalseElement = i; + else if (SecondFalseElement == -1) + SecondFalseElement = i; + else + SecondFalseElement = -2; } // If this element is in range, update our magic bitvector. @@ -6091,31 +6102,52 @@ MagicBitvector |= 1ULL << i; // If all of our states become overdefined, bail out early. - if (i >= 64 && OnlyTrueElement == -2 && OnlyFalseElement == -2) + if (i >= 64 && SecondTrueElement == -2 && SecondFalseElement == -2) return 0; } // Now that we've scanned the entire array, emit our new comparison(s). We // order the state machines in complexity of the generated code. - if (OnlyTrueElement != -2) { + Value *Idx = GEP->getOperand(2); + + // If the comparison is only true for one or two elements, emit direct + // comparisons. + if (SecondTrueElement != -2) { // None true -> false. - if (OnlyTrueElement == -1) + if (FirstTrueElement == -1) return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context)); + Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); + // True for one element -> 'i == 47'. - return new ICmpInst(ICmpInst::ICMP_EQ, GEP->getOperand(2), - ConstantInt::get(GEP->getOperand(2)->getType(), - OnlyTrueElement)); + if (SecondTrueElement == -1) + return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); + + // True for two elements -> 'i == 47 | i == 72'. + Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx); + Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); + Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx); + return BinaryOperator::CreateOr(C1, C2); } - if (OnlyFalseElement != -2) { + // If the comparison is only false for one or two elements, emit direct + // comparisons. + if (SecondFalseElement != -2) { // None false -> true. - if (OnlyFalseElement == -1) + if (FirstFalseElement == -1) return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context)); - return new ICmpInst(ICmpInst::ICMP_NE, GEP->getOperand(2), - ConstantInt::get(GEP->getOperand(2)->getType(), - OnlyFalseElement)); + Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); + + // False for one element -> 'i != 47'. + if (SecondFalseElement == -1) + return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); + + // False for two elements -> 'i != 47 & i != 72'. + Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx); + Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); + Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx); + return BinaryOperator::CreateAnd(C1, C2); } // If a 32-bit or 64-bit magic bitvector captures the entire comparison state @@ -6128,14 +6160,14 @@ Ty = Type::getInt32Ty(Init->getContext()); else Ty = Type::getInt64Ty(Init->getContext()); - Value *V = Builder->CreateIntCast(GEP->getOperand(2), Ty, false); + Value *V = Builder->CreateIntCast(Idx, Ty, false); V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V); return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); } - // TODO: Range check, two compares. - + // TODO: Range check + // TODO: GEP 0, i, 4 return 0; } Modified: llvm/trunk/test/Transforms/InstCombine/load-cmp.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/load-cmp.ll?rev=92417&r1=92416&r2=92417&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/load-cmp.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Sat Jan 2 03:35:17 2010 @@ -45,3 +45,15 @@ ; CHECK-NEXT: %R = icmp ne i32 {{.*}}, 0 ; CHECK-NEXT: ret i1 %R } + +define i1 @test5(i32 %X) { + %P = getelementptr [10 x i16]* @G16, i32 0, i32 %X + %Q = load i16* %P + %R = icmp eq i16 %Q, 69 + ret i1 %R +; CHECK: @test5 +; CHECK-NEXT: icmp eq i32 %X, 2 +; CHECK-NEXT: icmp eq i32 %X, 7 +; CHECK-NEXT: %R = or i1 +; CHECK-NEXT: ret i1 %R +} From nicholas at mxc.ca Sat Jan 2 09:25:45 2010 From: nicholas at mxc.ca (Nick Lewycky) Date: Sat, 02 Jan 2010 15:25:45 -0000 Subject: [llvm-commits] [llvm] r92418 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/or.ll Message-ID: <201001021525.o02FPjmB019445@zion.cs.uiuc.edu> Author: nicholas Date: Sat Jan 2 09:25:44 2010 New Revision: 92418 URL: http://llvm.org/viewvc/llvm-project?rev=92418&view=rev Log: Optimize pointer comparison into the typesafe form, now that the backends will handle them efficiently. This is the opposite direction of the transformation we used to have here. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/or.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92418&r1=92417&r2=92418&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 09:25:44 2010 @@ -4432,8 +4432,7 @@ // See if we can simplify any instructions used by the instruction whose sole // purpose is to compute bits we don't care about. if (SimplifyDemandedInstructionBits(I)) - return &I; - + return &I; if (ConstantInt *AndRHS = dyn_cast(Op1)) { const APInt &AndRHSMask = AndRHS->getValue(); @@ -7312,6 +7311,25 @@ } } break; + + case Instruction::Or: { + if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse()) + break; + Value *P, *Q; + if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { + // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 + // -> and (icmp eq P, null), (icmp eq Q, null). + + Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P, + Constant::getNullValue(P->getType())); + Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q, + Constant::getNullValue(Q->getType())); + Instruction *And = BinaryOperator::CreateAnd(ICIP, ICIQ, ""); + And->takeName(&ICI); + return And; + } + break; + } case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI) ConstantInt *ShAmt = dyn_cast(LHSI->getOperand(1)); Modified: llvm/trunk/test/Transforms/InstCombine/or.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/or.ll?rev=92418&r1=92417&r2=92418&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/or.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/or.ll Sat Jan 2 09:25:44 2010 @@ -268,6 +268,19 @@ ; CHECK: ret i1 } +define i1 @test27(i32* %A, i32* %B) { + %C1 = ptrtoint i32* %A to i32 + %C2 = ptrtoint i32* %B to i32 + %D = or i32 %C1, %C2 + %E = icmp eq i32 %D, 0 + ret i1 %E +; CHECK: @test27 +; CHECK: icmp eq i32* %A, null +; CHECK: icmp eq i32* %B, null +; CHECK: and i1 +; CHECK: ret i1 +} + ; PR5634 define i1 @test28(i32 %A, i32 %B) { %C1 = icmp ne i32 %A, 0 From nicholas at mxc.ca Sat Jan 2 10:14:56 2010 From: nicholas at mxc.ca (Nick Lewycky) Date: Sat, 02 Jan 2010 16:14:56 -0000 Subject: [llvm-commits] [llvm] r92419 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/or.ll Message-ID: <201001021614.o02GEvVl021074@zion.cs.uiuc.edu> Author: nicholas Date: Sat Jan 2 10:14:56 2010 New Revision: 92419 URL: http://llvm.org/viewvc/llvm-project?rev=92419&view=rev Log: Fix logic error in previous commit. The != case needs to become an or, not an and. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/or.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92419&r1=92418&r2=92419&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 10:14:56 2010 @@ -7324,9 +7324,13 @@ Constant::getNullValue(P->getType())); Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q, Constant::getNullValue(Q->getType())); - Instruction *And = BinaryOperator::CreateAnd(ICIP, ICIQ, ""); - And->takeName(&ICI); - return And; + Instruction *Op; + if (ICI.getPredicate() == ICmpInst::ICMP_EQ) + Op = BinaryOperator::CreateAnd(ICIP, ICIQ, ""); + else + Op = BinaryOperator::CreateOr(ICIP, ICIQ, ""); + Op->takeName(&ICI); + return Op; } break; } Modified: llvm/trunk/test/Transforms/InstCombine/or.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/or.ll?rev=92419&r1=92418&r2=92419&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/or.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/or.ll Sat Jan 2 10:14:56 2010 @@ -293,3 +293,17 @@ ; CHECK: icmp ne i32 {{.*}}, 0 ; CHECK: ret i1 } + +define i1 @test29(i32* %A, i32* %B) { + %C1 = ptrtoint i32* %A to i32 + %C2 = ptrtoint i32* %B to i32 + %D = or i32 %C1, %C2 + %E = icmp ne i32 %D, 0 + ret i1 %E +; CHECK: @test29 +; CHECK: icmp ne i32* %A, null +; CHECK: icmp ne i32* %B, null +; CHECK: or i1 +; CHECK: ret i1 +} + From clattner at apple.com Sat Jan 2 13:49:47 2010 From: clattner at apple.com (Chris Lattner) Date: Sat, 2 Jan 2010 11:49:47 -0800 Subject: [llvm-commits] [llvm] r92419 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/or.ll In-Reply-To: <201001021614.o02GEvVl021074@zion.cs.uiuc.edu> References: <201001021614.o02GEvVl021074@zion.cs.uiuc.edu> Message-ID: <9BB0512E-494F-40BF-9804-85F47EADA1F1@apple.com> On Jan 2, 2010, at 8:14 AM, Nick Lewycky wrote: Author: nicholas > Date: Sat Jan 2 10:14:56 2010 > New Revision: 92419 > > URL: http://llvm.org/viewvc/llvm-project?rev=92419&view=rev > Log: > Fix logic error in previous commit. The != case needs to become an or, not an > and. Looks good, one minor thing: > + Instruction *Op; > + if (ICI.getPredicate() == ICmpInst::ICMP_EQ) > + Op = BinaryOperator::CreateAnd(ICIP, ICIQ, ""); > + else > + Op = BinaryOperator::CreateOr(ICIP, ICIQ, ""); > + Op->takeName(&ICI); > + return Op; The preferred idiom is to just return the new instruction with no name (and you don't need to pass ""), the caller fills in the name from the instruction it is replacing. -Chris From sabre at nondot.org Sat Jan 2 14:07:04 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 20:07:04 -0000 Subject: [llvm-commits] [llvm] r92422 - in /llvm/trunk: include/llvm/LinkAllPasses.h include/llvm/Transforms/Instrumentation.h lib/Transforms/Instrumentation/BlockProfiling.cpp lib/Transforms/Instrumentation/CMakeLists.txt lib/Transforms/Instrumentation/RSProfiling.cpp lib/Transforms/Instrumentation/RSProfiling.h lib/Transforms/Scalar/InstructionCombining.cpp runtime/libprofile/BlockProfiling.c runtime/libprofile/FunctionProfiling.c runtime/libprofile/exported_symbols.lst Message-ID: <201001022007.o02K74Sh028628@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 14:07:03 2010 New Revision: 92422 URL: http://llvm.org/viewvc/llvm-project?rev=92422&view=rev Log: remove the random sampling framework, which is not maintained anymore. If there is interest, it can be resurrected from SVN. PR4912. Removed: llvm/trunk/lib/Transforms/Instrumentation/BlockProfiling.cpp llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.cpp llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.h llvm/trunk/runtime/libprofile/BlockProfiling.c llvm/trunk/runtime/libprofile/FunctionProfiling.c Modified: llvm/trunk/include/llvm/LinkAllPasses.h llvm/trunk/include/llvm/Transforms/Instrumentation.h llvm/trunk/lib/Transforms/Instrumentation/CMakeLists.txt llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/runtime/libprofile/exported_symbols.lst Modified: llvm/trunk/include/llvm/LinkAllPasses.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/LinkAllPasses.h?rev=92422&r1=92421&r2=92422&view=diff ============================================================================== --- llvm/trunk/include/llvm/LinkAllPasses.h (original) +++ llvm/trunk/include/llvm/LinkAllPasses.h Sat Jan 2 14:07:03 2010 @@ -53,7 +53,6 @@ (void) llvm::createLibCallAliasAnalysisPass(0); (void) llvm::createScalarEvolutionAliasAnalysisPass(); (void) llvm::createBlockPlacementPass(); - (void) llvm::createBlockProfilerPass(); (void) llvm::createBreakCriticalEdgesPass(); (void) llvm::createCFGSimplificationPass(); (void) llvm::createConstantMergePass(); @@ -71,7 +70,6 @@ (void) llvm::createOptimalEdgeProfilerPass(); (void) llvm::createFunctionInliningPass(); (void) llvm::createAlwaysInlinerPass(); - (void) llvm::createFunctionProfilerPass(); (void) llvm::createGlobalDCEPass(); (void) llvm::createGlobalOptimizerPass(); (void) llvm::createGlobalsModRefPass(); @@ -120,8 +118,6 @@ (void) llvm::createTailDuplicationPass(); (void) llvm::createJumpThreadingPass(); (void) llvm::createUnifyFunctionExitNodesPass(); - (void) llvm::createNullProfilerRSPass(); - (void) llvm::createRSProfilingPass(); (void) llvm::createInstCountPass(); (void) llvm::createCodeGenPreparePass(); (void) llvm::createGVNPass(); Modified: llvm/trunk/include/llvm/Transforms/Instrumentation.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Transforms/Instrumentation.h?rev=92422&r1=92421&r2=92422&view=diff ============================================================================== --- llvm/trunk/include/llvm/Transforms/Instrumentation.h (original) +++ llvm/trunk/include/llvm/Transforms/Instrumentation.h Sat Jan 2 14:07:03 2010 @@ -19,22 +19,12 @@ class ModulePass; class FunctionPass; -// Insert function profiling instrumentation -ModulePass *createFunctionProfilerPass(); - -// Insert block profiling instrumentation -ModulePass *createBlockProfilerPass(); - // Insert edge profiling instrumentation ModulePass *createEdgeProfilerPass(); // Insert optimal edge profiling instrumentation ModulePass *createOptimalEdgeProfilerPass(); -// Random Sampling Profiling Framework -ModulePass* createNullProfilerRSPass(); -FunctionPass* createRSProfilingPass(); - } // End llvm namespace #endif Removed: llvm/trunk/lib/Transforms/Instrumentation/BlockProfiling.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Instrumentation/BlockProfiling.cpp?rev=92421&view=auto ============================================================================== --- llvm/trunk/lib/Transforms/Instrumentation/BlockProfiling.cpp (original) +++ llvm/trunk/lib/Transforms/Instrumentation/BlockProfiling.cpp (removed) @@ -1,128 +0,0 @@ -//===- BlockProfiling.cpp - Insert counters for block profiling -----------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This pass instruments the specified program with counters for basic block or -// function profiling. This is the most basic form of profiling, which can tell -// which blocks are hot, but cannot reliably detect hot paths through the CFG. -// Block profiling counts the number of times each basic block executes, and -// function profiling counts the number of times each function is called. -// -// Note that this implementation is very naive. Control equivalent regions of -// the CFG should not require duplicate counters, but we do put duplicate -// counters in. -// -//===----------------------------------------------------------------------===// - -#include "llvm/DerivedTypes.h" -#include "llvm/Module.h" -#include "llvm/Pass.h" -#include "llvm/Support/raw_ostream.h" -#include "llvm/Transforms/Instrumentation.h" -#include "RSProfiling.h" -#include "ProfilingUtils.h" -using namespace llvm; - -namespace { - class FunctionProfiler : public RSProfilers_std { - public: - static char ID; - bool runOnModule(Module &M); - }; -} - -char FunctionProfiler::ID = 0; - -static RegisterPass -X("insert-function-profiling", - "Insert instrumentation for function profiling"); -static RegisterAnalysisGroup XG(X); - -ModulePass *llvm::createFunctionProfilerPass() { - return new FunctionProfiler(); -} - -bool FunctionProfiler::runOnModule(Module &M) { - Function *Main = M.getFunction("main"); - if (Main == 0) { - errs() << "WARNING: cannot insert function profiling into a module" - << " with no main function!\n"; - return false; // No main, no instrumentation! - } - - unsigned NumFunctions = 0; - for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) - if (!I->isDeclaration()) - ++NumFunctions; - - const Type *ATy = ArrayType::get(Type::getInt32Ty(M.getContext()), - NumFunctions); - GlobalVariable *Counters = - new GlobalVariable(M, ATy, false, GlobalValue::InternalLinkage, - Constant::getNullValue(ATy), "FuncProfCounters"); - - // Instrument all of the functions... - unsigned i = 0; - for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) - if (!I->isDeclaration()) - // Insert counter at the start of the function - IncrementCounterInBlock(&I->getEntryBlock(), i++, Counters); - - // Add the initialization call to main. - InsertProfilingInitCall(Main, "llvm_start_func_profiling", Counters); - return true; -} - - -namespace { - class BlockProfiler : public RSProfilers_std { - bool runOnModule(Module &M); - public: - static char ID; - }; -} - -char BlockProfiler::ID = 0; -static RegisterPass -Y("insert-block-profiling", "Insert instrumentation for block profiling"); -static RegisterAnalysisGroup YG(Y); - -ModulePass *llvm::createBlockProfilerPass() { return new BlockProfiler(); } - -bool BlockProfiler::runOnModule(Module &M) { - Function *Main = M.getFunction("main"); - if (Main == 0) { - errs() << "WARNING: cannot insert block profiling into a module" - << " with no main function!\n"; - return false; // No main, no instrumentation! - } - - unsigned NumBlocks = 0; - for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) - if (!I->isDeclaration()) - NumBlocks += I->size(); - - const Type *ATy = ArrayType::get(Type::getInt32Ty(M.getContext()), NumBlocks); - GlobalVariable *Counters = - new GlobalVariable(M, ATy, false, GlobalValue::InternalLinkage, - Constant::getNullValue(ATy), "BlockProfCounters"); - - // Instrument all of the blocks... - unsigned i = 0; - for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { - if (I->isDeclaration()) continue; - for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB) - // Insert counter at the start of the block - IncrementCounterInBlock(BB, i++, Counters); - } - - // Add the initialization call to main. - InsertProfilingInitCall(Main, "llvm_start_block_profiling", Counters); - return true; -} - Modified: llvm/trunk/lib/Transforms/Instrumentation/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Instrumentation/CMakeLists.txt?rev=92422&r1=92421&r2=92422&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Instrumentation/CMakeLists.txt (original) +++ llvm/trunk/lib/Transforms/Instrumentation/CMakeLists.txt Sat Jan 2 14:07:03 2010 @@ -1,7 +1,5 @@ add_llvm_library(LLVMInstrumentation - BlockProfiling.cpp EdgeProfiling.cpp OptimalEdgeProfiling.cpp ProfilingUtils.cpp - RSProfiling.cpp ) Removed: llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.cpp?rev=92421&view=auto ============================================================================== --- llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.cpp (original) +++ llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.cpp (removed) @@ -1,662 +0,0 @@ -//===- RSProfiling.cpp - Various profiling using random sampling ----------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// These passes implement a random sampling based profiling. Different methods -// of choosing when to sample are supported, as well as different types of -// profiling. This is done as two passes. The first is a sequence of profiling -// passes which insert profiling into the program, and remember what they -// inserted. -// -// The second stage duplicates all instructions in a function, ignoring the -// profiling code, then connects the two versions togeather at the entry and at -// backedges. At each connection point a choice is made as to whether to jump -// to the profiled code (take a sample) or execute the unprofiled code. -// -// It is highly recommended that after this pass one runs mem2reg and adce -// (instcombine load-vn gdce dse also are good to run afterwards) -// -// This design is intended to make the profiling passes independent of the RS -// framework, but any profiling pass that implements the RSProfiling interface -// is compatible with the rs framework (and thus can be sampled) -// -// TODO: obviously the block and function profiling are almost identical to the -// existing ones, so they can be unified (esp since these passes are valid -// without the rs framework). -// TODO: Fix choice code so that frequency is not hard coded -// -//===----------------------------------------------------------------------===// - -#include "llvm/Pass.h" -#include "llvm/LLVMContext.h" -#include "llvm/Module.h" -#include "llvm/Instructions.h" -#include "llvm/Constants.h" -#include "llvm/DerivedTypes.h" -#include "llvm/Intrinsics.h" -#include "llvm/Transforms/Scalar.h" -#include "llvm/Transforms/Utils/BasicBlockUtils.h" -#include "llvm/Support/CommandLine.h" -#include "llvm/Support/Debug.h" -#include "llvm/Support/ErrorHandling.h" -#include "llvm/Support/raw_ostream.h" -#include "llvm/Transforms/Instrumentation.h" -#include "RSProfiling.h" -#include -#include -#include -using namespace llvm; - -namespace { - enum RandomMeth { - GBV, GBVO, HOSTCC - }; -} - -static cl::opt RandomMethod("profile-randomness", - cl::desc("How to randomly choose to profile:"), - cl::values( - clEnumValN(GBV, "global", "global counter"), - clEnumValN(GBVO, "ra_global", - "register allocated global counter"), - clEnumValN(HOSTCC, "rdcc", "cycle counter"), - clEnumValEnd)); - -namespace { - /// NullProfilerRS - The basic profiler that does nothing. It is the default - /// profiler and thus terminates RSProfiler chains. It is useful for - /// measuring framework overhead - class NullProfilerRS : public RSProfilers { - public: - static char ID; // Pass identification, replacement for typeid - bool isProfiling(Value* v) { - return false; - } - bool runOnModule(Module &M) { - return false; - } - void getAnalysisUsage(AnalysisUsage &AU) const { - AU.setPreservesAll(); - } - }; -} - -static RegisterAnalysisGroup A("Profiling passes"); -static RegisterPass NP("insert-null-profiling-rs", - "Measure profiling framework overhead"); -static RegisterAnalysisGroup NPT(NP); - -namespace { - /// Chooser - Something that chooses when to make a sample of the profiled code - class Chooser { - public: - /// ProcessChoicePoint - is called for each basic block inserted to choose - /// between normal and sample code - virtual void ProcessChoicePoint(BasicBlock*) = 0; - /// PrepFunction - is called once per function before other work is done. - /// This gives the opertunity to insert new allocas and such. - virtual void PrepFunction(Function*) = 0; - virtual ~Chooser() {} - }; - - //Things that implement sampling policies - //A global value that is read-mod-stored to choose when to sample. - //A sample is taken when the global counter hits 0 - class GlobalRandomCounter : public Chooser { - GlobalVariable* Counter; - Value* ResetValue; - const IntegerType* T; - public: - GlobalRandomCounter(Module& M, const IntegerType* t, uint64_t resetval); - virtual ~GlobalRandomCounter(); - virtual void PrepFunction(Function* F); - virtual void ProcessChoicePoint(BasicBlock* bb); - }; - - //Same is GRC, but allow register allocation of the global counter - class GlobalRandomCounterOpt : public Chooser { - GlobalVariable* Counter; - Value* ResetValue; - AllocaInst* AI; - const IntegerType* T; - public: - GlobalRandomCounterOpt(Module& M, const IntegerType* t, uint64_t resetval); - virtual ~GlobalRandomCounterOpt(); - virtual void PrepFunction(Function* F); - virtual void ProcessChoicePoint(BasicBlock* bb); - }; - - //Use the cycle counter intrinsic as a source of pseudo randomness when - //deciding when to sample. - class CycleCounter : public Chooser { - uint64_t rm; - Constant *F; - public: - CycleCounter(Module& m, uint64_t resetmask); - virtual ~CycleCounter(); - virtual void PrepFunction(Function* F); - virtual void ProcessChoicePoint(BasicBlock* bb); - }; - - /// ProfilerRS - Insert the random sampling framework - struct ProfilerRS : public FunctionPass { - static char ID; // Pass identification, replacement for typeid - ProfilerRS() : FunctionPass(&ID) {} - - std::map TransCache; - std::set ChoicePoints; - Chooser* c; - - //Translate and duplicate values for the new profile free version of stuff - Value* Translate(Value* v); - //Duplicate an entire function (with out profiling) - void Duplicate(Function& F, RSProfilers& LI); - //Called once for each backedge, handle the insertion of choice points and - //the interconection of the two versions of the code - void ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F); - bool runOnFunction(Function& F); - bool doInitialization(Module &M); - virtual void getAnalysisUsage(AnalysisUsage &AU) const; - }; -} - -static RegisterPass -X("insert-rs-profiling-framework", - "Insert random sampling instrumentation framework"); - -char RSProfilers::ID = 0; -char NullProfilerRS::ID = 0; -char ProfilerRS::ID = 0; - -//Local utilities -static void ReplacePhiPred(BasicBlock* btarget, - BasicBlock* bold, BasicBlock* bnew); - -static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc); - -template -static void recBackEdge(BasicBlock* bb, T& BackEdges, - std::map& color, - std::map& depth, - std::map& finish, - int& time); - -//find the back edges and where they go to -template -static void getBackEdges(Function& F, T& BackEdges); - - -/////////////////////////////////////// -// Methods of choosing when to profile -/////////////////////////////////////// - -GlobalRandomCounter::GlobalRandomCounter(Module& M, const IntegerType* t, - uint64_t resetval) : T(t) { - ConstantInt* Init = ConstantInt::get(T, resetval); - ResetValue = Init; - Counter = new GlobalVariable(M, T, false, GlobalValue::InternalLinkage, - Init, "RandomSteeringCounter"); -} - -GlobalRandomCounter::~GlobalRandomCounter() {} - -void GlobalRandomCounter::PrepFunction(Function* F) {} - -void GlobalRandomCounter::ProcessChoicePoint(BasicBlock* bb) { - BranchInst* t = cast(bb->getTerminator()); - - //decrement counter - LoadInst* l = new LoadInst(Counter, "counter", t); - - ICmpInst* s = new ICmpInst(t, ICmpInst::ICMP_EQ, l, - ConstantInt::get(T, 0), - "countercc"); - - Value* nv = BinaryOperator::CreateSub(l, ConstantInt::get(T, 1), - "counternew", t); - new StoreInst(nv, Counter, t); - t->setCondition(s); - - //reset counter - BasicBlock* oldnext = t->getSuccessor(0); - BasicBlock* resetblock = BasicBlock::Create(bb->getContext(), - "reset", oldnext->getParent(), - oldnext); - TerminatorInst* t2 = BranchInst::Create(oldnext, resetblock); - t->setSuccessor(0, resetblock); - new StoreInst(ResetValue, Counter, t2); - ReplacePhiPred(oldnext, bb, resetblock); -} - -GlobalRandomCounterOpt::GlobalRandomCounterOpt(Module& M, const IntegerType* t, - uint64_t resetval) - : AI(0), T(t) { - ConstantInt* Init = ConstantInt::get(T, resetval); - ResetValue = Init; - Counter = new GlobalVariable(M, T, false, GlobalValue::InternalLinkage, - Init, "RandomSteeringCounter"); -} - -GlobalRandomCounterOpt::~GlobalRandomCounterOpt() {} - -void GlobalRandomCounterOpt::PrepFunction(Function* F) { - //make a local temporary to cache the global - BasicBlock& bb = F->getEntryBlock(); - BasicBlock::iterator InsertPt = bb.begin(); - AI = new AllocaInst(T, 0, "localcounter", InsertPt); - LoadInst* l = new LoadInst(Counter, "counterload", InsertPt); - new StoreInst(l, AI, InsertPt); - - //modify all functions and return values to restore the local variable to/from - //the global variable - for(Function::iterator fib = F->begin(), fie = F->end(); - fib != fie; ++fib) - for(BasicBlock::iterator bib = fib->begin(), bie = fib->end(); - bib != bie; ++bib) - if (isa(bib)) { - LoadInst* l = new LoadInst(AI, "counter", bib); - new StoreInst(l, Counter, bib); - l = new LoadInst(Counter, "counter", ++bib); - new StoreInst(l, AI, bib--); - } else if (isa(bib)) { - LoadInst* l = new LoadInst(AI, "counter", bib); - new StoreInst(l, Counter, bib); - - BasicBlock* bb = cast(bib)->getNormalDest(); - BasicBlock::iterator i = bb->getFirstNonPHI(); - l = new LoadInst(Counter, "counter", i); - - bb = cast(bib)->getUnwindDest(); - i = bb->getFirstNonPHI(); - l = new LoadInst(Counter, "counter", i); - new StoreInst(l, AI, i); - } else if (isa(&*bib) || isa(&*bib)) { - LoadInst* l = new LoadInst(AI, "counter", bib); - new StoreInst(l, Counter, bib); - } -} - -void GlobalRandomCounterOpt::ProcessChoicePoint(BasicBlock* bb) { - BranchInst* t = cast(bb->getTerminator()); - - //decrement counter - LoadInst* l = new LoadInst(AI, "counter", t); - - ICmpInst* s = new ICmpInst(t, ICmpInst::ICMP_EQ, l, - ConstantInt::get(T, 0), - "countercc"); - - Value* nv = BinaryOperator::CreateSub(l, ConstantInt::get(T, 1), - "counternew", t); - new StoreInst(nv, AI, t); - t->setCondition(s); - - //reset counter - BasicBlock* oldnext = t->getSuccessor(0); - BasicBlock* resetblock = BasicBlock::Create(bb->getContext(), - "reset", oldnext->getParent(), - oldnext); - TerminatorInst* t2 = BranchInst::Create(oldnext, resetblock); - t->setSuccessor(0, resetblock); - new StoreInst(ResetValue, AI, t2); - ReplacePhiPred(oldnext, bb, resetblock); -} - - -CycleCounter::CycleCounter(Module& m, uint64_t resetmask) : rm(resetmask) { - F = Intrinsic::getDeclaration(&m, Intrinsic::readcyclecounter); -} - -CycleCounter::~CycleCounter() {} - -void CycleCounter::PrepFunction(Function* F) {} - -void CycleCounter::ProcessChoicePoint(BasicBlock* bb) { - BranchInst* t = cast(bb->getTerminator()); - - CallInst* c = CallInst::Create(F, "rdcc", t); - BinaryOperator* b = - BinaryOperator::CreateAnd(c, - ConstantInt::get(Type::getInt64Ty(bb->getContext()), rm), - "mrdcc", t); - - ICmpInst *s = new ICmpInst(t, ICmpInst::ICMP_EQ, b, - ConstantInt::get(Type::getInt64Ty(bb->getContext()), 0), - "mrdccc"); - - t->setCondition(s); -} - -/////////////////////////////////////// -// Profiling: -/////////////////////////////////////// -bool RSProfilers_std::isProfiling(Value* v) { - if (profcode.find(v) != profcode.end()) - return true; - //else - RSProfilers& LI = getAnalysis(); - return LI.isProfiling(v); -} - -void RSProfilers_std::IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum, - GlobalValue *CounterArray) { - // Insert the increment after any alloca or PHI instructions... - BasicBlock::iterator InsertPos = BB->getFirstNonPHI(); - while (isa(InsertPos)) - ++InsertPos; - - // Create the getelementptr constant expression - std::vector Indices(2); - Indices[0] = Constant::getNullValue(Type::getInt32Ty(BB->getContext())); - Indices[1] = ConstantInt::get(Type::getInt32Ty(BB->getContext()), CounterNum); - Constant *ElementPtr =ConstantExpr::getGetElementPtr(CounterArray, - &Indices[0], 2); - - // Load, increment and store the value back. - Value *OldVal = new LoadInst(ElementPtr, "OldCounter", InsertPos); - profcode.insert(OldVal); - Value *NewVal = BinaryOperator::CreateAdd(OldVal, - ConstantInt::get(Type::getInt32Ty(BB->getContext()), 1), - "NewCounter", InsertPos); - profcode.insert(NewVal); - profcode.insert(new StoreInst(NewVal, ElementPtr, InsertPos)); -} - -void RSProfilers_std::getAnalysisUsage(AnalysisUsage &AU) const { - //grab any outstanding profiler, or get the null one - AU.addRequired(); -} - -/////////////////////////////////////// -// RS Framework -/////////////////////////////////////// - -Value* ProfilerRS::Translate(Value* v) { - if(TransCache[v]) - return TransCache[v]; - - if (BasicBlock* bb = dyn_cast(v)) { - if (bb == &bb->getParent()->getEntryBlock()) - TransCache[bb] = bb; //don't translate entry block - else - TransCache[bb] = BasicBlock::Create(v->getContext(), - "dup_" + bb->getName(), - bb->getParent(), NULL); - return TransCache[bb]; - } else if (Instruction* i = dyn_cast(v)) { - //we have already translated this - //do not translate entry block allocas - if(&i->getParent()->getParent()->getEntryBlock() == i->getParent()) { - TransCache[i] = i; - return i; - } else { - //translate this - Instruction* i2 = i->clone(); - if (i->hasName()) - i2->setName("dup_" + i->getName()); - TransCache[i] = i2; - //NumNewInst++; - for (unsigned x = 0; x < i2->getNumOperands(); ++x) - i2->setOperand(x, Translate(i2->getOperand(x))); - return i2; - } - } else if (isa(v) || isa(v) || isa(v)) { - TransCache[v] = v; - return v; - } - llvm_unreachable("Value not handled"); - return 0; -} - -void ProfilerRS::Duplicate(Function& F, RSProfilers& LI) -{ - //perform a breadth first search, building up a duplicate of the code - std::queue worklist; - std::set seen; - - //This loop ensures proper BB order, to help performance - for (Function::iterator fib = F.begin(), fie = F.end(); fib != fie; ++fib) - worklist.push(fib); - while (!worklist.empty()) { - Translate(worklist.front()); - worklist.pop(); - } - - //remember than reg2mem created a new entry block we don't want to duplicate - worklist.push(F.getEntryBlock().getTerminator()->getSuccessor(0)); - seen.insert(&F.getEntryBlock()); - - while (!worklist.empty()) { - BasicBlock* bb = worklist.front(); - worklist.pop(); - if(seen.find(bb) == seen.end()) { - BasicBlock* bbtarget = cast(Translate(bb)); - BasicBlock::InstListType& instlist = bbtarget->getInstList(); - for (BasicBlock::iterator iib = bb->begin(), iie = bb->end(); - iib != iie; ++iib) { - //NumOldInst++; - if (!LI.isProfiling(&*iib)) { - Instruction* i = cast(Translate(iib)); - instlist.insert(bbtarget->end(), i); - } - } - //updated search state; - seen.insert(bb); - TerminatorInst* ti = bb->getTerminator(); - for (unsigned x = 0; x < ti->getNumSuccessors(); ++x) { - BasicBlock* bbs = ti->getSuccessor(x); - if (seen.find(bbs) == seen.end()) { - worklist.push(bbs); - } - } - } - } -} - -void ProfilerRS::ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F) { - //given a backedge from B -> A, and translations A' and B', - //a: insert C and C' - //b: add branches in C to A and A' and in C' to A and A' - //c: mod terminators at B, replace A with C - //d: mod terminators at B', replace A' with C' - //e: mod phis at A for pred B to be pred C - // if multiple entries, simplify to one - //f: mod phis at A' for pred B' to be pred C' - // if multiple entries, simplify to one - //g: for all phis at A with pred C using x - // add in edge from C' using x' - // add in edge from C using x in A' - - //a: - Function::iterator BBN = src; ++BBN; - BasicBlock* bbC = BasicBlock::Create(F.getContext(), "choice", &F, BBN); - //ChoicePoints.insert(bbC); - BBN = cast(Translate(src)); - BasicBlock* bbCp = BasicBlock::Create(F.getContext(), "choice", &F, ++BBN); - ChoicePoints.insert(bbCp); - - //b: - BranchInst::Create(cast(Translate(dst)), bbC); - BranchInst::Create(dst, cast(Translate(dst)), - ConstantInt::get(Type::getInt1Ty(src->getContext()), true), bbCp); - //c: - { - TerminatorInst* iB = src->getTerminator(); - for (unsigned x = 0; x < iB->getNumSuccessors(); ++x) - if (iB->getSuccessor(x) == dst) - iB->setSuccessor(x, bbC); - } - //d: - { - TerminatorInst* iBp = cast(Translate(src->getTerminator())); - for (unsigned x = 0; x < iBp->getNumSuccessors(); ++x) - if (iBp->getSuccessor(x) == cast(Translate(dst))) - iBp->setSuccessor(x, bbCp); - } - //e: - ReplacePhiPred(dst, src, bbC); - //src could be a switch, in which case we are replacing several edges with one - //thus collapse those edges int the Phi - CollapsePhi(dst, bbC); - //f: - ReplacePhiPred(cast(Translate(dst)), - cast(Translate(src)),bbCp); - CollapsePhi(cast(Translate(dst)), bbCp); - //g: - for(BasicBlock::iterator ib = dst->begin(), ie = dst->end(); ib != ie; - ++ib) - if (PHINode* phi = dyn_cast(&*ib)) { - for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x) - if(bbC == phi->getIncomingBlock(x)) { - phi->addIncoming(Translate(phi->getIncomingValue(x)), bbCp); - cast(Translate(phi))->addIncoming(phi->getIncomingValue(x), - bbC); - } - phi->removeIncomingValue(bbC); - } -} - -bool ProfilerRS::runOnFunction(Function& F) { - if (!F.isDeclaration()) { - std::set > BackEdges; - RSProfilers& LI = getAnalysis(); - - getBackEdges(F, BackEdges); - Duplicate(F, LI); - //assume that stuff worked. now connect the duplicated basic blocks - //with the originals in such a way as to preserve ssa. yuk! - for (std::set >::iterator - ib = BackEdges.begin(), ie = BackEdges.end(); ib != ie; ++ib) - ProcessBackEdge(ib->first, ib->second, F); - - //oh, and add the edge from the reg2mem created entry node to the - //duplicated second node - TerminatorInst* T = F.getEntryBlock().getTerminator(); - ReplaceInstWithInst(T, BranchInst::Create(T->getSuccessor(0), - cast( - Translate(T->getSuccessor(0))), - ConstantInt::get(Type::getInt1Ty(F.getContext()), true))); - - //do whatever is needed now that the function is duplicated - c->PrepFunction(&F); - - //add entry node to choice points - ChoicePoints.insert(&F.getEntryBlock()); - - for (std::set::iterator - ii = ChoicePoints.begin(), ie = ChoicePoints.end(); ii != ie; ++ii) - c->ProcessChoicePoint(*ii); - - ChoicePoints.clear(); - TransCache.clear(); - - return true; - } - return false; -} - -bool ProfilerRS::doInitialization(Module &M) { - switch (RandomMethod) { - case GBV: - c = new GlobalRandomCounter(M, Type::getInt32Ty(M.getContext()), - (1 << 14) - 1); - break; - case GBVO: - c = new GlobalRandomCounterOpt(M, Type::getInt32Ty(M.getContext()), - (1 << 14) - 1); - break; - case HOSTCC: - c = new CycleCounter(M, (1 << 14) - 1); - break; - }; - return true; -} - -void ProfilerRS::getAnalysisUsage(AnalysisUsage &AU) const { - AU.addRequired(); - AU.addRequiredID(DemoteRegisterToMemoryID); -} - -/////////////////////////////////////// -// Utilities: -/////////////////////////////////////// -static void ReplacePhiPred(BasicBlock* btarget, - BasicBlock* bold, BasicBlock* bnew) { - for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end(); - ib != ie; ++ib) - if (PHINode* phi = dyn_cast(&*ib)) { - for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x) - if(bold == phi->getIncomingBlock(x)) - phi->setIncomingBlock(x, bnew); - } -} - -static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc) { - for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end(); - ib != ie; ++ib) - if (PHINode* phi = dyn_cast(&*ib)) { - std::map counter; - for(unsigned i = 0; i < phi->getNumIncomingValues(); ) { - if (counter[phi->getIncomingBlock(i)]) { - assert(phi->getIncomingValue(i) == counter[phi->getIncomingBlock(i)]); - phi->removeIncomingValue(i, false); - } else { - counter[phi->getIncomingBlock(i)] = phi->getIncomingValue(i); - ++i; - } - } - } -} - -template -static void recBackEdge(BasicBlock* bb, T& BackEdges, - std::map& color, - std::map& depth, - std::map& finish, - int& time) -{ - color[bb] = 1; - ++time; - depth[bb] = time; - TerminatorInst* t= bb->getTerminator(); - for(unsigned i = 0; i < t->getNumSuccessors(); ++i) { - BasicBlock* bbnew = t->getSuccessor(i); - if (color[bbnew] == 0) - recBackEdge(bbnew, BackEdges, color, depth, finish, time); - else if (color[bbnew] == 1) { - BackEdges.insert(std::make_pair(bb, bbnew)); - //NumBackEdges++; - } - } - color[bb] = 2; - ++time; - finish[bb] = time; -} - - - -//find the back edges and where they go to -template -static void getBackEdges(Function& F, T& BackEdges) { - std::map color; - std::map depth; - std::map finish; - int time = 0; - recBackEdge(&F.getEntryBlock(), BackEdges, color, depth, finish, time); - DEBUG(errs() << F.getName() << " " << BackEdges.size() << "\n"); -} - - -//Creation functions -ModulePass* llvm::createNullProfilerRSPass() { - return new NullProfilerRS(); -} - -FunctionPass* llvm::createRSProfilingPass() { - return new ProfilerRS(); -} Removed: llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.h URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.h?rev=92421&view=auto ============================================================================== --- llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.h (original) +++ llvm/trunk/lib/Transforms/Instrumentation/RSProfiling.h (removed) @@ -1,31 +0,0 @@ -//===- RSProfiling.h - Various profiling using random sampling ----------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// See notes in RSProfiling.cpp -// -//===----------------------------------------------------------------------===// -#include "llvm/Transforms/RSProfiling.h" -#include - -namespace llvm { - /// RSProfilers_std - a simple support class for profilers that handles most - /// of the work of chaining and tracking inserted code. - struct RSProfilers_std : public RSProfilers { - static char ID; - std::set profcode; - // Lookup up values in profcode - virtual bool isProfiling(Value* v); - // handles required chaining - virtual void getAnalysisUsage(AnalysisUsage &AU) const; - // places counter updates in basic blocks and recordes added instructions in - // profcode - void IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum, - GlobalValue *CounterArray); - }; -} Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92422&r1=92421&r2=92422&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 14:07:03 2010 @@ -6167,6 +6167,12 @@ // TODO: Range check // TODO: GEP 0, i, 4 + + //errs() << "XFORM: " << *GV << "\n"; + //errs() << "\t" << *GEP << "\n"; + //errs() << "\t " << ICI << "\n\n\n\n"; + + return 0; } Removed: llvm/trunk/runtime/libprofile/BlockProfiling.c URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/runtime/libprofile/BlockProfiling.c?rev=92421&view=auto ============================================================================== --- llvm/trunk/runtime/libprofile/BlockProfiling.c (original) +++ llvm/trunk/runtime/libprofile/BlockProfiling.c (removed) @@ -1,45 +0,0 @@ -/*===-- BlockProfiling.c - Support library for block profiling ------------===*\ -|* -|* The LLVM Compiler Infrastructure -|* -|* This file is distributed under the University of Illinois Open Source -|* License. See LICENSE.TXT for details. -|* -|*===----------------------------------------------------------------------===*| -|* -|* This file implements the call back routines for the block profiling -|* instrumentation pass. This should be used with the -insert-block-profiling -|* LLVM pass. -|* -\*===----------------------------------------------------------------------===*/ - -#include "Profiling.h" -#include - -static unsigned *ArrayStart; -static unsigned NumElements; - -/* BlockProfAtExitHandler - When the program exits, just write out the profiling - * data. - */ -static void BlockProfAtExitHandler() { - /* Note that if this were doing something more intelligent with the - * instrumentation, we could do some computation here to expand what we - * collected into simple block profiles. (Or we could do it in llvm-prof.) - * Regardless, we directly count each block, so no expansion is necessary. - */ - write_profiling_data(BlockInfo, ArrayStart, NumElements); -} - - -/* llvm_start_block_profiling - This is the main entry point of the block - * profiling library. It is responsible for setting up the atexit handler. - */ -int llvm_start_block_profiling(int argc, const char **argv, - unsigned *arrayStart, unsigned numElements) { - int Ret = save_arguments(argc, argv); - ArrayStart = arrayStart; - NumElements = numElements; - atexit(BlockProfAtExitHandler); - return Ret; -} Removed: llvm/trunk/runtime/libprofile/FunctionProfiling.c URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/runtime/libprofile/FunctionProfiling.c?rev=92421&view=auto ============================================================================== --- llvm/trunk/runtime/libprofile/FunctionProfiling.c (original) +++ llvm/trunk/runtime/libprofile/FunctionProfiling.c (removed) @@ -1,42 +0,0 @@ -/*===-- FunctionProfiling.c - Support library for function profiling ------===*\ -|* -|* The LLVM Compiler Infrastructure -|* -|* This file is distributed under the University of Illinois Open Source -|* License. See LICENSE.TXT for details. -|* -|*===----------------------------------------------------------------------===*| -|* -|* This file implements the call back routines for the function profiling -|* instrumentation pass. This should be used with the -|* -insert-function-profiling LLVM pass. -|* -\*===----------------------------------------------------------------------===*/ - -#include "Profiling.h" -#include - -static unsigned *ArrayStart; -static unsigned NumElements; - -/* FuncProfAtExitHandler - When the program exits, just write out the profiling - * data. - */ -static void FuncProfAtExitHandler() { - /* Just write out the data we collected. - */ - write_profiling_data(FunctionInfo, ArrayStart, NumElements); -} - - -/* llvm_start_func_profiling - This is the main entry point of the function - * profiling library. It is responsible for setting up the atexit handler. - */ -int llvm_start_func_profiling(int argc, const char **argv, - unsigned *arrayStart, unsigned numElements) { - int Ret = save_arguments(argc, argv); - ArrayStart = arrayStart; - NumElements = numElements; - atexit(FuncProfAtExitHandler); - return Ret; -} Modified: llvm/trunk/runtime/libprofile/exported_symbols.lst URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/runtime/libprofile/exported_symbols.lst?rev=92422&r1=92421&r2=92422&view=diff ============================================================================== --- llvm/trunk/runtime/libprofile/exported_symbols.lst (original) +++ llvm/trunk/runtime/libprofile/exported_symbols.lst Sat Jan 2 14:07:03 2010 @@ -1,6 +1,4 @@ -llvm_start_func_profiling -llvm_start_block_profiling llvm_start_edge_profiling llvm_start_opt_edge_profiling llvm_start_basic_block_tracing From sabre at nondot.org Sat Jan 2 14:20:33 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 20:20:33 -0000 Subject: [llvm-commits] [llvm] r92423 - /llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Message-ID: <201001022020.o02KKXtf029152@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 14:20:33 2010 New Revision: 92423 URL: http://llvm.org/viewvc/llvm-project?rev=92423&view=rev Log: use enums for the over/underdefined markers for clarity. Switch to using -2/-3 instead of -1/-2 for a future xform. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92423&r1=92422&r2=92423&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 14:20:33 2010 @@ -6020,9 +6020,8 @@ /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern: /// cmp pred (load (gep GV, ...)), cmpcst /// where GV is a global variable with a constant initializer. Try to simplify -/// this into one or two simpler comparisons that do not need the load. For -/// example, we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into -/// "icmp eq i, 3". We assume that eliminating a load is always goodness. +/// this into some simple computation that does not need the load. For example +/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". Instruction *InstCombiner:: FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI) { @@ -6039,19 +6038,20 @@ ConstantArray *Init = dyn_cast(GV->getInitializer()); if (Init == 0 || Init->getNumOperands() > 1024) return 0; - + enum { Overdefined = -3, Undefined = -2 }; + // Variables for our state machines. // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form // "i == 47 | i == 87", where 47 is the first index the condition is true for, - // and 87 is the second (and last) index. FirstTrueElement is -1 when + // and 87 is the second (and last) index. FirstTrueElement is -2 when // undefined, otherwise set to the first true element. SecondTrueElement is - // -1 when undefined, -2 when overdefined and >= 0 when that index is true. - int FirstTrueElement = -1, SecondTrueElement = -1; + // -2 when undefined, -3 when overdefined and >= 0 when that index is true. + int FirstTrueElement = Undefined, SecondTrueElement = Undefined; // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the // form "i != 47 & i != 87". Same state transitions as for true elements. - int FirstFalseElement = -1, SecondFalseElement = -1; + int FirstFalseElement = Undefined, SecondFalseElement = Undefined; // MagicBitvector - This is a magic bitvector where we set a bit if the // comparison is true for element 'i'. If there are 64 elements or less in @@ -6080,20 +6080,20 @@ // State machine for single index comparison. if (IsTrueForElt) { // Update the TrueElement state machine. - if (FirstTrueElement == -1) + if (FirstTrueElement == Undefined) FirstTrueElement = i; - else if (SecondTrueElement == -1) + else if (SecondTrueElement == Undefined) SecondTrueElement = i; else - SecondTrueElement = -2; + SecondTrueElement = Overdefined; } else { // Update the FalseElement state machine. - if (FirstFalseElement == -1) + if (FirstFalseElement == Undefined) FirstFalseElement = i; - else if (SecondFalseElement == -1) + else if (SecondFalseElement == Undefined) SecondFalseElement = i; else - SecondFalseElement = -2; + SecondFalseElement = Overdefined; } // If this element is in range, update our magic bitvector. @@ -6101,7 +6101,8 @@ MagicBitvector |= 1ULL << i; // If all of our states become overdefined, bail out early. - if (i >= 64 && SecondTrueElement == -2 && SecondFalseElement == -2) + if (i >= 64 && SecondTrueElement == Overdefined && + SecondFalseElement == Overdefined) return 0; } @@ -6111,15 +6112,15 @@ // If the comparison is only true for one or two elements, emit direct // comparisons. - if (SecondTrueElement != -2) { + if (SecondTrueElement != Overdefined) { // None true -> false. - if (FirstTrueElement == -1) + if (FirstTrueElement == Undefined) return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context)); Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); // True for one element -> 'i == 47'. - if (SecondTrueElement == -1) + if (SecondTrueElement == Undefined) return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); // True for two elements -> 'i == 47 | i == 72'. @@ -6131,15 +6132,15 @@ // If the comparison is only false for one or two elements, emit direct // comparisons. - if (SecondFalseElement != -2) { + if (SecondFalseElement != Overdefined) { // None false -> true. - if (FirstFalseElement == -1) + if (FirstFalseElement == Undefined) return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context)); Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); // False for one element -> 'i != 47'. - if (SecondFalseElement == -1) + if (SecondFalseElement == Undefined) return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); // False for two elements -> 'i != 47 & i != 72'. @@ -6167,6 +6168,7 @@ // TODO: Range check // TODO: GEP 0, i, 4 + // TODO: A[i]&4 == 0 //errs() << "XFORM: " << *GV << "\n"; //errs() << "\t" << *GEP << "\n"; From sabre at nondot.org Sat Jan 2 15:46:34 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 21:46:34 -0000 Subject: [llvm-commits] [llvm] r92425 - /llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Message-ID: <201001022146.o02LkYB2032172@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 15:46:33 2010 New Revision: 92425 URL: http://llvm.org/viewvc/llvm-project?rev=92425&view=rev Log: theoretically the negate we find could be in a different function, check for this case. Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Modified: llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp?rev=92425&r1=92424&r2=92425&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/Reassociate.cpp Sat Jan 2 15:46:33 2010 @@ -414,6 +414,10 @@ // non-instruction value) or right after the definition. These negates will // be zapped by reassociate later, so we don't need much finesse here. BinaryOperator *TheNeg = cast(*UI); + + // Verify that the negate is in this function, V might be a constant expr. + if (TheNeg->getParent()->getParent() != BI->getParent()->getParent()) + continue; BasicBlock::iterator InsertPt; if (Instruction *InstInput = dyn_cast(V)) { From sabre at nondot.org Sat Jan 2 15:50:25 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 21:50:25 -0000 Subject: [llvm-commits] [llvm] r92426 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/load-cmp.ll Message-ID: <201001022150.o02LoQMY032361@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 15:50:18 2010 New Revision: 92426 URL: http://llvm.org/viewvc/llvm-project?rev=92426&view=rev Log: Teach the table lookup optimization to generate range compares when a consequtive sequence of elements all satisfies the predicate. Like the double compare case, this generates better code than the magic constant case and generalizes to more than 32/64 element array lookups. Here are some examples where it triggers. From 403.gcc, most accesses to the rtx_class array are handled, e.g.: @rtx_class = constant [153 x i8] c"xxxxxmmmmmmmmxxxxxxxxxxxxmxxxxxxiiixxxxxxxxxxxxxxxxxxxooxooooooxxoooooox3x2c21c2222ccc122222ccccaaaaaa<<<<<<<<<<<<<<<<<<111111111111bbooxxxxxxxxxxcc2211x", align 32 ; <[153 x i8]*> [#uses=547] %142 = icmp eq i8 %141, 105 @rtx_class = constant [153 x i8] c"xxxxxmmmmmmmmxxxxxxxxxxxxmxxxxxxiiixxxxxxxxxxxxxxxxxxxooxooooooxxoooooox3x2c21c2222ccc122222ccccaaaaaa<<<<<<<<<<<<<<<<<<111111111111bbooxxxxxxxxxxcc2211x", align 32 ; <[153 x i8]*> [#uses=543] %165 = icmp eq i8 %164, 60 Also, most of the 59-element arrays (mode_class/rid_to_yy, etc) optimized before are actually range compares. This lets 32-bit machines optimize them. 400.perlbmk has stuff like this: 400.perlbmk: PL_regkind, even for 32-bit: @PL_regkind = constant [62 x i8] c"\00\00\02\02\02\06\06\06\06\09\09\0B\0B\0D\0E\0E\0E\11\12\12\14\14\16\16\18\18\1A\1A\1C\1C\1E\1F !!!$$&'((((,-.///88886789:;8$", align 32 ; <[62 x i8]*> [#uses=4] %811 = icmp ne i8 %810, 33 @PL_utf8skip = constant [256 x i8] c"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\04\04\04\04\04\04\04\04\05\05\05\05\06\06\07\0D", align 32 ; <[256 x i8]*> [#uses=94] %12 = icmp ult i8 %10, 2 etc. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92426&r1=92425&r2=92426&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 15:50:18 2010 @@ -6053,6 +6053,14 @@ // form "i != 47 & i != 87". Same state transitions as for true elements. int FirstFalseElement = Undefined, SecondFalseElement = Undefined; + /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these + /// define a state machine that triggers for ranges of values that the index + /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. + /// This is -2 when undefined, -3 when overdefined, and otherwise the last + /// index in the range (inclusive). We use -2 for undefined here because we + /// use relative comparisons and don't want 0-1 to match -1. + int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; + // MagicBitvector - This is a magic bitvector where we set a bit if the // comparison is true for element 'i'. If there are 64 elements or less in // the array, this will fully represent all the comparison results. @@ -6067,7 +6075,15 @@ Init->getOperand(i), CompareRHS, TD); // If the result is undef for this element, ignore it. - if (isa(C)) continue; + if (isa(C)) { + // Extend range state machines to cover this element in case there is an + // undef in the middle of the range. + if (TrueRangeEnd == (int)i-1) + TrueRangeEnd = i; + if (FalseRangeEnd == (int)i-1) + FalseRangeEnd = i; + continue; + } // If we can't compute the result for any of the elements, we have to give // up evaluating the entire conditional. @@ -6077,32 +6093,54 @@ // update our state machines. bool IsTrueForElt = !cast(C)->isZero(); - // State machine for single index comparison. + // State machine for single/double/range index comparison. if (IsTrueForElt) { // Update the TrueElement state machine. if (FirstTrueElement == Undefined) - FirstTrueElement = i; - else if (SecondTrueElement == Undefined) - SecondTrueElement = i; - else - SecondTrueElement = Overdefined; + FirstTrueElement = TrueRangeEnd = i; // First true element. + else { + // Update double-compare state machine. + if (SecondTrueElement == Undefined) + SecondTrueElement = i; + else + SecondTrueElement = Overdefined; + + // Update range state machine. + if (TrueRangeEnd == (int)i-1) + TrueRangeEnd = i; + else + TrueRangeEnd = Overdefined; + } } else { // Update the FalseElement state machine. if (FirstFalseElement == Undefined) - FirstFalseElement = i; - else if (SecondFalseElement == Undefined) - SecondFalseElement = i; - else - SecondFalseElement = Overdefined; + FirstFalseElement = FalseRangeEnd = i; // First false element. + else { + // Update double-compare state machine. + if (SecondFalseElement == Undefined) + SecondFalseElement = i; + else + SecondFalseElement = Overdefined; + + // Update range state machine. + if (FalseRangeEnd == (int)i-1) + FalseRangeEnd = i; + else + FalseRangeEnd = Overdefined; + } } + // If this element is in range, update our magic bitvector. if (i < 64 && IsTrueForElt) MagicBitvector |= 1ULL << i; - // If all of our states become overdefined, bail out early. - if (i >= 64 && SecondTrueElement == Overdefined && - SecondFalseElement == Overdefined) + // If all of our states become overdefined, bail out early. Since the + // predicate is expensive, only check it every 8 elements. This is only + // really useful for really huge arrays. + if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && + SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && + FalseRangeEnd == Overdefined) return 0; } @@ -6110,6 +6148,7 @@ // order the state machines in complexity of the generated code. Value *Idx = GEP->getOperand(2); + // If the comparison is only true for one or two elements, emit direct // comparisons. if (SecondTrueElement != Overdefined) { @@ -6150,6 +6189,37 @@ return BinaryOperator::CreateAnd(C1, C2); } + // If the comparison can be replaced with a range comparison for the elements + // where it is true, emit the range check. + if (TrueRangeEnd != Overdefined) { + assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); + + // Generate (i-FirstTrue) getType(), -FirstTrueElement); + Idx = Builder->CreateAdd(Idx, Offs); + } + + Value *End = ConstantInt::get(Idx->getType(), + TrueRangeEnd-FirstTrueElement+1); + return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); + } + + // False range check. + if (FalseRangeEnd != Overdefined) { + assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); + // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). + if (FirstFalseElement) { + Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); + Idx = Builder->CreateAdd(Idx, Offs); + } + + Value *End = ConstantInt::get(Idx->getType(), + FalseRangeEnd-FirstFalseElement); + return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); + } + + // If a 32-bit or 64-bit magic bitvector captures the entire comparison state // of this load, replace it with computation that does: // ((magic_cst >> i) & 1) != 0 @@ -6166,14 +6236,8 @@ return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); } - // TODO: Range check - // TODO: GEP 0, i, 4 // TODO: A[i]&4 == 0 - - //errs() << "XFORM: " << *GV << "\n"; - //errs() << "\t" << *GEP << "\n"; - //errs() << "\t " << ICI << "\n\n\n\n"; - + // TODO: GEP 0, i, 4 return 0; } Modified: llvm/trunk/test/Transforms/InstCombine/load-cmp.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/load-cmp.ll?rev=92426&r1=92425&r2=92426&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/load-cmp.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Sat Jan 2 15:50:18 2010 @@ -2,7 +2,8 @@ @G16 = internal constant [10 x i16] [i16 35, i16 82, i16 69, i16 81, i16 85, i16 73, i16 82, i16 69, i16 68, i16 0] - at GD = internal constant [3 x double] [double 1.0, double 4.0, double -20.0] + at GD = internal constant [6 x double] + [double -10.0, double 1.0, double 4.0, double 2.0, double -20.0, double -40.0] define i1 @test1(i32 %X) { %P = getelementptr [10 x i16]* @G16, i32 0, i32 %X @@ -25,12 +26,12 @@ } define i1 @test3(i32 %X) { - %P = getelementptr [3 x double]* @GD, i32 0, i32 %X + %P = getelementptr [6 x double]* @GD, i32 0, i32 %X %Q = load double* %P %R = fcmp oeq double %Q, 1.0 ret i1 %R ; CHECK: @test3 -; CHECK-NEXT: %R = icmp eq i32 %X, 0 +; CHECK-NEXT: %R = icmp eq i32 %X, 1 ; CHECK-NEXT: ret i1 %R } @@ -57,3 +58,25 @@ ; CHECK-NEXT: %R = or i1 ; CHECK-NEXT: ret i1 %R } + +define i1 @test6(i32 %X) { + %P = getelementptr [6 x double]* @GD, i32 0, i32 %X + %Q = load double* %P + %R = fcmp ogt double %Q, 0.0 + ret i1 %R +; CHECK: @test6 +; CHECK-NEXT: add i32 %X, -1 +; CHECK-NEXT: %R = icmp ult i32 {{.*}}, 3 +; CHECK-NEXT: ret i1 %R +} + +define i1 @test7(i32 %X) { + %P = getelementptr [6 x double]* @GD, i32 0, i32 %X + %Q = load double* %P + %R = fcmp olt double %Q, 0.0 + ret i1 %R +; CHECK: @test7 +; CHECK-NEXT: add i32 %X, -1 +; CHECK-NEXT: %R = icmp ugt i32 {{.*}}, 2 +; CHECK-NEXT: ret i1 %R +} From sabre at nondot.org Sat Jan 2 16:08:39 2010 From: sabre at nondot.org (Chris Lattner) Date: Sat, 02 Jan 2010 22:08:39 -0000 Subject: [llvm-commits] [llvm] r92427 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/load-cmp.ll Message-ID: <201001022208.o02M8f4N000839@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 16:08:28 2010 New Revision: 92427 URL: http://llvm.org/viewvc/llvm-project?rev=92427&view=rev Log: teach instcombine to optimize idioms like A[i]&42 == 0. This occurs in 403.gcc in mode_mask_array, in safe-ctype.c (which is copied in multiple apps) in _sch_istable, etc. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92427&r1=92426&r2=92427&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 16:08:28 2010 @@ -259,7 +259,8 @@ Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI, Constant *RHSC); Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, - GlobalVariable *GV, CmpInst &ICI); + GlobalVariable *GV, CmpInst &ICI, + ConstantInt *AndCst = 0); Instruction *visitFCmpInst(FCmpInst &I); Instruction *visitICmpInst(ICmpInst &I); Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI); @@ -6022,9 +6023,12 @@ /// where GV is a global variable with a constant initializer. Try to simplify /// this into some simple computation that does not need the load. For example /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". +/// +/// If AndCst is non-null, then the loaded value is masked with that constant +/// before doing the comparison. This handles cases like "A[i]&4 == 0". Instruction *InstCombiner:: FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV, - CmpInst &ICI) { + CmpInst &ICI, ConstantInt *AndCst) { // There are many forms of this optimization we can handle, for now, just do // the simple index into a single-dimensional array. @@ -6070,9 +6074,13 @@ // Scan the array and see if one of our patterns matches. Constant *CompareRHS = cast(ICI.getOperand(1)); for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { + Constant *Elt = Init->getOperand(i); + + // If the element is masked, handle it. + if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); + // Find out if the comparison would be true or false for the i'th element. - Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), - Init->getOperand(i), + Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, CompareRHS, TD); // If the result is undef for this element, ignore it. if (isa(C)) { @@ -6236,7 +6244,6 @@ return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); } - // TODO: A[i]&4 == 0 // TODO: GEP 0, i, 4 return 0; @@ -6333,7 +6340,7 @@ !cast(LHSI)->isVolatile()) if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) return Res; - //errs() << "NOT HANDLED: " << *GV << "\n"; + //errs() << "NOT HANDLED FP: " << *GV << "\n"; //errs() << "\t" << *GEP << "\n"; //errs() << "\t " << I << "\n\n\n"; } @@ -6719,6 +6726,7 @@ break; case Instruction::Load: + // Try to optimize things like "A[i] > 4" to index computations. if (GetElementPtrInst *GEP = dyn_cast(LHSI->getOperand(0))) { if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) @@ -6726,7 +6734,7 @@ !cast(LHSI)->isVolatile()) if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) return Res; - //errs() << "NOT HANDLED: " << *GV << "\n"; + //errs() << "NOT HANDLED INT: " << *GV << "\n"; //errs() << "\t" << *GEP << "\n"; //errs() << "\t " << I << "\n\n\n"; } @@ -7382,6 +7390,22 @@ return &ICI; } } + + // Try to optimize things like "A[i]&42 == 0" to index computations. + if (LoadInst *LI = dyn_cast(LHSI->getOperand(0))) { + if (GetElementPtrInst *GEP = + dyn_cast(LI->getOperand(0))) + if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) + if (GV->isConstant() && GV->hasDefinitiveInitializer() && + !LI->isVolatile() && isa(LHSI->getOperand(1))) { + ConstantInt *C = cast(LHSI->getOperand(1)); + if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C)) + return Res; + //errs() << "NOT HANDLED INT: " << *GV << "\n"; + //errs() << "\t" << *GEP << "\n"; + //errs() << "\t " << I << "\n\n\n"; + } + } break; case Instruction::Or: { Modified: llvm/trunk/test/Transforms/InstCombine/load-cmp.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/load-cmp.ll?rev=92427&r1=92426&r2=92427&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/load-cmp.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Sat Jan 2 16:08:28 2010 @@ -80,3 +80,15 @@ ; CHECK-NEXT: %R = icmp ugt i32 {{.*}}, 2 ; CHECK-NEXT: ret i1 %R } + +define i1 @test8(i32 %X) { + %P = getelementptr [10 x i16]* @G16, i32 0, i32 %X + %Q = load i16* %P + %R = and i16 %Q, 3 + %S = icmp eq i16 %R, 0 + ret i1 %S +; CHECK: @test8 +; CHECK-NEXT: add i32 %X, -8 +; CHECK-NEXT: %S = icmp ult i32 {{.*}}, 2 +; CHECK-NEXT: ret i1 %S +} From nicholas at mxc.ca Sat Jan 2 18:55:32 2010 From: nicholas at mxc.ca (Nick Lewycky) Date: Sun, 03 Jan 2010 00:55:32 -0000 Subject: [llvm-commits] [llvm] r92436 - /llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Message-ID: <201001030055.o030tWbZ006317@zion.cs.uiuc.edu> Author: nicholas Date: Sat Jan 2 18:55:31 2010 New Revision: 92436 URL: http://llvm.org/viewvc/llvm-project?rev=92436&view=rev Log: Cleanup. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92436&r1=92435&r2=92436&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 18:55:31 2010 @@ -7422,10 +7422,9 @@ Constant::getNullValue(Q->getType())); Instruction *Op; if (ICI.getPredicate() == ICmpInst::ICMP_EQ) - Op = BinaryOperator::CreateAnd(ICIP, ICIQ, ""); + Op = BinaryOperator::CreateAnd(ICIP, ICIQ); else - Op = BinaryOperator::CreateOr(ICIP, ICIQ, ""); - Op->takeName(&ICI); + Op = BinaryOperator::CreateOr(ICIP, ICIQ); return Op; } break; From sabre at nondot.org Sat Jan 2 21:03:27 2010 From: sabre at nondot.org (Chris Lattner) Date: Sun, 03 Jan 2010 03:03:27 -0000 Subject: [llvm-commits] [llvm] r92444 - in /llvm/trunk: lib/Transforms/Scalar/InstructionCombining.cpp test/Transforms/InstCombine/load-cmp.ll Message-ID: <201001030303.o0333Rmo010063@zion.cs.uiuc.edu> Author: lattner Date: Sat Jan 2 21:03:27 2010 New Revision: 92444 URL: http://llvm.org/viewvc/llvm-project?rev=92444&view=rev Log: generalize the previous transformation to handle indexing into arrays of structs and other arrays, so long as all the subsequent indexes are constants. This triggers frequently for stuff like: @divisions = internal constant [29 x [2 x i32]] [[2 x i32] zeroinitializer, [2 x i32] [i32 0, i32 1], [2 x i32] [i32 0, i32 2], [2 x i32] [i32 0, i32 1], [2 x i32] zeroinitializer, [2 x i32] [i32 0, i32 1], [2 x i32] [i32 0, i32 1], [2 x i32] [i32 0, i32 2], [2 x i32] [i32 0, i32 2], [2 x i32] zeroinitializer, [2 x i32] zeroinitializer, [2 x i32] zeroinitializer, [2 x i32] [i32 0, i32 2], [2 x i32] [i32 0, i32 1], [2 x i32] zeroinitializer, [2 x i32] [i32 1, i32 0], [2 x i32] [i32 1, i32 1], [2 x i32] [i32 1, i32 1], [2 x i32] [i32 1, i32 2], [2 x i32] [i32 1, i32 1], [2 x i32] [i32 1, i32 0], [2 x i32] [i32 1, i32 2], [2 x i32] [i32 1, i32 2], [2 x i32] [i32 1, i32 0], [2 x i32] [i32 1, i32 0], [2 x i32] [i32 1, i32 0], [2 x i32] [i32 1, i32 1], [2 x i32] [i32 1, i32 2], [2 x i32] [i32 1, i32 2]], align 32 ; <[29 x [2 x i32]]*> [#uses=50] %623 = getelementptr inbounds [29 x [2 x i32]]* @divisions, i64 0, i64 %619, i64 0 ; [#uses=1] %684 = icmp eq i32 %683, 999 also for the "my_defs" table in 'gs', etc. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92444&r1=92443&r2=92444&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sat Jan 2 21:03:27 2010 @@ -6017,7 +6017,6 @@ return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); } - /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern: /// cmp pred (load (gep GV, ...)), cmpcst /// where GV is a global variable with a constant initializer. Try to simplify @@ -6029,18 +6028,43 @@ Instruction *InstCombiner:: FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI, ConstantInt *AndCst) { + ConstantArray *Init = dyn_cast(GV->getInitializer()); + if (Init == 0 || Init->getNumOperands() > 1024) return 0; // There are many forms of this optimization we can handle, for now, just do // the simple index into a single-dimensional array. // - // Require: GEP GV, 0, i - if (GEP->getNumOperands() != 3 || + // Require: GEP GV, 0, i {{, constant indices}} + if (GEP->getNumOperands() < 3 || !isa(GEP->getOperand(1)) || - !cast(GEP->getOperand(1))->isZero()) + !cast(GEP->getOperand(1))->isZero() || + isa(GEP->getOperand(2))) return 0; - - ConstantArray *Init = dyn_cast(GV->getInitializer()); - if (Init == 0 || Init->getNumOperands() > 1024) return 0; + + // Check that indices after the variable are constants and in-range for the + // type they index. Collect the indices. This is typically for arrays of + // structs. + SmallVector LaterIndices; + + const Type *EltTy = cast(Init->getType())->getElementType(); + for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { + ConstantInt *Idx = dyn_cast(GEP->getOperand(i)); + if (Idx == 0) return 0; // Variable index. + + uint64_t IdxVal = Idx->getZExtValue(); + if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index. + + if (const StructType *STy = dyn_cast(EltTy)) + EltTy = STy->getElementType(IdxVal); + else if (const ArrayType *ATy = dyn_cast(EltTy)) { + if (IdxVal >= ATy->getNumElements()) return 0; + EltTy = ATy->getElementType(); + } else { + return 0; // Unknown type. + } + + LaterIndices.push_back(IdxVal); + } enum { Overdefined = -3, Undefined = -2 }; @@ -6076,6 +6100,11 @@ for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { Constant *Elt = Init->getOperand(i); + // If this is indexing an array of structures, get the structure element. + if (!LaterIndices.empty()) + Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(), + LaterIndices.size()); + // If the element is masked, handle it. if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); @@ -6244,8 +6273,6 @@ return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); } - // TODO: GEP 0, i, 4 - return 0; } @@ -6337,12 +6364,15 @@ dyn_cast(LHSI->getOperand(0))) { if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) if (GV->isConstant() && GV->hasDefinitiveInitializer() && - !cast(LHSI)->isVolatile()) + !cast(LHSI)->isVolatile()) { if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) return Res; - //errs() << "NOT HANDLED FP: " << *GV << "\n"; - //errs() << "\t" << *GEP << "\n"; - //errs() << "\t " << I << "\n\n\n"; +#if 0 + errs() << "NOT HANDLED FP: " << *GV << "\n"; + errs() << "\t" << *GEP << "\n"; + errs() << "\t " << I << "\n\n\n"; +#endif + } } break; } @@ -6731,12 +6761,15 @@ dyn_cast(LHSI->getOperand(0))) { if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) if (GV->isConstant() && GV->hasDefinitiveInitializer() && - !cast(LHSI)->isVolatile()) + !cast(LHSI)->isVolatile()) { if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) return Res; - //errs() << "NOT HANDLED INT: " << *GV << "\n"; - //errs() << "\t" << *GEP << "\n"; - //errs() << "\t " << I << "\n\n\n"; +#if 0 + errs() << "NOT HANDLED INT: " << *GV << "\n"; + errs() << "\t" << *GEP << "\n"; + errs() << "\t " << I << "\n\n\n"; +#endif + } } break; } @@ -7401,9 +7434,12 @@ ConstantInt *C = cast(LHSI->getOperand(1)); if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C)) return Res; - //errs() << "NOT HANDLED INT: " << *GV << "\n"; - //errs() << "\t" << *GEP << "\n"; - //errs() << "\t " << I << "\n\n\n"; +#if 0 + errs() << "NOT HANDLED 'AND': " << *GV << "\n"; + errs() << "\t" << *GEP << "\n"; + errs() << "\t " << *LHSI << "\n\n\n"; + errs() << "\t " << ICI << "\n\n\n"; +#endif } } break; Modified: llvm/trunk/test/Transforms/InstCombine/load-cmp.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Transforms/InstCombine/load-cmp.ll?rev=92444&r1=92443&r2=92444&view=diff ============================================================================== --- llvm/trunk/test/Transforms/InstCombine/load-cmp.ll (original) +++ llvm/trunk/test/Transforms/InstCombine/load-cmp.ll Sat Jan 2 21:03:27 2010 @@ -92,3 +92,21 @@ ; CHECK-NEXT: %S = icmp ult i32 {{.*}}, 2 ; CHECK-NEXT: ret i1 %S } + + at GA = internal constant [4 x { i32, i32 } ] [ + { i32, i32 } { i32 1, i32 0 }, + { i32, i32 } { i32 2, i32 1 }, + { i32, i32 } { i32 3, i32 1 }, + { i32, i32 } { i32 4, i32 0 } +] + +define i1 @test9(i32 %X) { + %P = getelementptr [4 x { i32, i32 } ]* @GA, i32 0, i32 %X, i32 1 + %Q = load i32* %P + %R = icmp eq i32 %Q, 1 + ret i1 %R +; CHECK: @test9 +; CHECK-NEXT: add i32 %X, -1 +; CHECK-NEXT: %R = icmp ult i32 {{.*}}, 2 +; CHECK-NEXT: ret i1 %R +} From nicholas at mxc.ca Sat Jan 2 22:39:11 2010 From: nicholas at mxc.ca (Nick Lewycky) Date: Sun, 03 Jan 2010 04:39:11 -0000 Subject: [llvm-commits] [llvm] r92445 - /llvm/trunk/lib/Transforms/Scalar/DeadStoreElimination.cpp Message-ID: <201001030439.o034dDpv012993@zion.cs.uiuc.edu> Author: nicholas Date: Sat Jan 2 22:39:07 2010 New Revision: 92445 URL: http://llvm.org/viewvc/llvm-project?rev=92445&view=rev Log: Small cleanups, refactor some duplicated code into a single method. No functionality change. Modified: llvm/trunk/lib/Transforms/Scalar/DeadStoreElimination.cpp Modified: llvm/trunk/lib/Transforms/Scalar/DeadStoreElimination.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/DeadStoreElimination.cpp?rev=92445&r1=92444&r2=92445&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/DeadStoreElimination.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/DeadStoreElimination.cpp Sat Jan 2 22:39:07 2010 @@ -52,9 +52,9 @@ bool runOnBasicBlock(BasicBlock &BB); bool handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep); bool handleEndBlock(BasicBlock &BB); - bool RemoveUndeadPointers(Value* Ptr, uint64_t killPointerSize, - BasicBlock::iterator& BBI, - SmallPtrSet& deadPointers); + bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize, + BasicBlock::iterator &BBI, + SmallPtrSet &deadPointers); void DeleteDeadInstruction(Instruction *I, SmallPtrSet *deadPointers = 0); @@ -70,6 +70,8 @@ AU.addPreserved(); AU.addPreserved(); } + + unsigned getPointerSize(Value *V) const; }; } @@ -173,7 +175,7 @@ } bool DSE::runOnBasicBlock(BasicBlock &BB) { - MemoryDependenceAnalysis& MD = getAnalysis(); + MemoryDependenceAnalysis &MD = getAnalysis(); TD = getAnalysisIfAvailable(); bool MadeChange = false; @@ -355,7 +357,7 @@ continue; } - Value* killPointer = 0; + Value *killPointer = 0; uint64_t killPointerSize = ~0UL; // If we encounter a use of the pointer, it is no longer considered dead @@ -371,14 +373,14 @@ } killPointer = L->getPointerOperand(); - } else if (VAArgInst* V = dyn_cast(BBI)) { + } else if (VAArgInst *V = dyn_cast(BBI)) { killPointer = V->getOperand(0); } else if (isa(BBI) && isa(cast(BBI)->getLength())) { killPointer = cast(BBI)->getSource(); killPointerSize = cast( cast(BBI)->getLength())->getZExtValue(); - } else if (AllocaInst* A = dyn_cast(BBI)) { + } else if (AllocaInst *A = dyn_cast(BBI)) { deadPointers.erase(A); // Dead alloca's can be DCE'd when we reach them @@ -412,23 +414,10 @@ deadPointers.clear(); return MadeChange; } - - // Get size information for the alloca - unsigned pointerSize = ~0U; - if (TD) { - if (AllocaInst* A = dyn_cast(*I)) { - if (ConstantInt* C = dyn_cast(A->getArraySize())) - pointerSize = C->getZExtValue() * - TD->getTypeAllocSize(A->getAllocatedType()); - } else { - const PointerType* PT = cast( - cast(*I)->getType()); - pointerSize = TD->getTypeAllocSize(PT->getElementType()); - } - } - + // See if the call site touches it - AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize); + AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, + getPointerSize(*I)); if (A == AliasAnalysis::ModRef) modRef++; @@ -469,11 +458,11 @@ /// RemoveUndeadPointers - check for uses of a pointer that make it /// undead when scanning for dead stores to alloca's. -bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize, +bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize, BasicBlock::iterator &BBI, - SmallPtrSet& deadPointers) { + SmallPtrSet &deadPointers) { AliasAnalysis &AA = getAnalysis(); - + // If the kill pointer can be easily reduced to an alloca, // don't bother doing extraneous AA queries. if (deadPointers.count(killPointer)) { @@ -488,32 +477,19 @@ bool MadeChange = false; SmallVector undead; - + for (SmallPtrSet::iterator I = deadPointers.begin(), - E = deadPointers.end(); I != E; ++I) { - // Get size information for the alloca. - unsigned pointerSize = ~0U; - if (TD) { - if (AllocaInst* A = dyn_cast(*I)) { - if (ConstantInt* C = dyn_cast(A->getArraySize())) - pointerSize = C->getZExtValue() * - TD->getTypeAllocSize(A->getAllocatedType()); - } else { - const PointerType* PT = cast(cast(*I)->getType()); - pointerSize = TD->getTypeAllocSize(PT->getElementType()); - } - } - + E = deadPointers.end(); I != E; ++I) { // See if this pointer could alias it - AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize, + AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I), killPointer, killPointerSize); // If it must-alias and a store, we can delete it if (isa(BBI) && A == AliasAnalysis::MustAlias) { - StoreInst* S = cast(BBI); + StoreInst *S = cast(BBI); // Remove it! - BBI++; + ++BBI; DeleteDeadInstruction(S, &deadPointers); NumFastStores++; MadeChange = true; @@ -575,3 +551,18 @@ if (ValueSet) ValueSet->erase(DeadInst); } } + +unsigned DSE::getPointerSize(Value *V) const { + if (TD) { + if (AllocaInst *A = dyn_cast(V)) { + // Get size information for the alloca + if (ConstantInt *C = dyn_cast(A->getArraySize())) + return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType()); + } else { + assert(isa(V) && "Expected AllocaInst or Argument!"); + const PointerType *PT = cast(V->getType()); + return TD->getTypeAllocSize(PT->getElementType()); + } + } + return ~0U; +} From rjmccall at apple.com Sun Jan 3 00:50:02 2010 From: rjmccall at apple.com (John McCall) Date: Sat, 2 Jan 2010 22:50:02 -0800 Subject: [llvm-commits] [llvm] r92340 - in /llvm/trunk: lib/Support/StringRef.cpp unittests/ADT/StringRefTest.cpp In-Reply-To: <200912310424.nBV4Ockn023461@zion.cs.uiuc.edu> References: <200912310424.nBV4Ockn023461@zion.cs.uiuc.edu> Message-ID: <60C9B04F-FE9A-4A74-BCE4-55986095BAA3@apple.com> On Dec 30, 2009, at 8:24 PM, Douglas Gregor wrote: > Author: dgregor > Date: Wed Dec 30 22:24:34 2009 > New Revision: 92340 > > URL: http://llvm.org/viewvc/llvm-project?rev=92340&view=rev > Log: > Document the edit-distance algorithm used in StringRef, switch it over > to SmallVector, and add a unit test. Swapping llvm::SmallVectors is significantly less trivial than swapping std::vectors. Pointers would suffice, though. John. From sabre at nondot.org Sun Jan 3 00:58:50 2010 From: sabre at nondot.org (Chris Lattner) Date: Sun, 03 Jan 2010 06:58:50 -0000 Subject: [llvm-commits] [llvm] r92446 - /llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Message-ID: <201001030658.o036wonP017155@zion.cs.uiuc.edu> Author: lattner Date: Sun Jan 3 00:58:48 2010 New Revision: 92446 URL: http://llvm.org/viewvc/llvm-project?rev=92446&view=rev Log: pull my debug hooks out, I'm done with this xform for now. Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Modified: llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp?rev=92446&r1=92445&r2=92446&view=diff ============================================================================== --- llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp (original) +++ llvm/trunk/lib/Transforms/Scalar/InstructionCombining.cpp Sun Jan 3 00:58:48 2010 @@ -6364,15 +6364,9 @@ dyn_cast(LHSI->getOperand(0))) { if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) if (GV->isConstant() && GV->hasDefinitiveInitializer() && - !cast(LHSI)->isVolatile()) { + !cast(LHSI)->isVolatile()) if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) return Res; -#if 0 - errs() << "NOT HANDLED FP: " << *GV << "\n"; - errs() << "\t" << *GEP << "\n"; - errs() << "\t " << I << "\n\n\n"; -#endif - } } break; } @@ -6761,15 +6755,9 @@ dyn_cast(LHSI->getOperand(0))) { if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) if (GV->isConstant() && GV->hasDefinitiveInitializer() && - !cast(LHSI)->isVolatile()) { + !cast(LHSI)->isVolatile()) if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) return Res; -#if 0 - errs() << "NOT HANDLED INT: " << *GV << "\n"; - errs() << "\t" << *GEP << "\n"; - errs() << "\t " << I << "\n\n\n"; -#endif - } } break; } @@ -7434,12 +7422,6 @@ ConstantInt *C = cast(LHSI->getOperand(1)); if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C)) return Res; -#if 0 - errs() << "NOT HANDLED 'AND': " << *GV << "\n"; - errs() << "\t" << *GEP << "\n"; - errs() << "\t " << *LHSI << "\n\n\n"; - errs() << "\t " << ICI << "\n\n\n"; -#endif } } break; From sabre at nondot.org Sun Jan 3 12:09:48 2010 From: sabre at nondot.org (Chris Lattner) Date: Sun, 03 Jan 2010 18:09:48 -0000 Subject: [llvm-commits] [llvm] r92450 - in /llvm/trunk: lib/VMCore/Constants.cpp test/CodeGen/X86/addr-label-difference.ll Message-ID: <201001031809.o03I9pJ8012124@zion.cs.uiuc.edu> Author: lattner Date: Sun Jan 3 12:09:40 2010 New Revision: 92450 URL: http://llvm.org/viewvc/llvm-project?rev=92450&view=rev Log: differences between two blockaddress's don't cause a global variable initializer to require relocations. Added: llvm/trunk/test/CodeGen/X86/addr-label-difference.ll Modified: llvm/trunk/lib/VMCore/Constants.cpp Modified: llvm/trunk/lib/VMCore/Constants.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Constants.cpp?rev=92450&r1=92449&r2=92450&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Constants.cpp (original) +++ llvm/trunk/lib/VMCore/Constants.cpp Sun Jan 3 12:09:40 2010 @@ -197,6 +197,24 @@ if (const BlockAddress *BA = dyn_cast(this)) return BA->getFunction()->getRelocationInfo(); + // While raw uses of blockaddress need to be relocated, differences between + // two of them don't when they are for labels in the same function. This is a + // common idiom when creating a table for the indirect goto extension, so we + // handle it efficiently here. + if (const ConstantExpr *CE = dyn_cast(this)) + if (CE->getOpcode() == Instruction::Sub) { + ConstantExpr *LHS = dyn_cast(CE->getOperand(0)); + ConstantExpr *RHS = dyn_cast(CE->getOperand(1)); + if (LHS && RHS && + LHS->getOpcode() == Instruction::PtrToInt && + RHS->getOpcode() == Instruction::PtrToInt && + isa(LHS->getOperand(0)) && + isa(RHS->getOperand(0)) && + cast(LHS->getOperand(0))->getFunction() == + cast(RHS->getOperand(0))->getFunction()) + return NoRelocation; + } + PossibleRelocationsTy Result = NoRelocation; for (unsigned i = 0, e = getNumOperands(); i != e; ++i) Result = std::max(Result, Added: llvm/trunk/test/CodeGen/X86/addr-label-difference.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/X86/addr-label-difference.ll?rev=92450&view=auto ============================================================================== --- llvm/trunk/test/CodeGen/X86/addr-label-difference.ll (added) +++ llvm/trunk/test/CodeGen/X86/addr-label-difference.ll Sun Jan 3 12:09:40 2010 @@ -0,0 +1,21 @@ +; RUN: llc %s -o - | grep {__TEXT,__const} +target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:128:128-n8:16:32" +target triple = "i386-apple-darwin10.0" + +; This array should go into the __TEXT,__const section, not into the +; __DATA,__const section, because the elements don't need relocations. + at test.array = internal constant [3 x i32] [i32 sub (i32 ptrtoint (i8* blockaddress(@test, %foo) to i32), i32 ptrtoint (i8* blockaddress(@test, %foo) to i32)), i32 sub (i32 ptrtoint (i8* blockaddress(@test, %bar) to i32), i32 ptrtoint (i8* blockaddress(@test, %foo) to i32)), i32 sub (i32 ptrtoint (i8* blockaddress(@test, %hack) to i32), i32 ptrtoint (i8* blockaddress(@test, %foo) to i32))] ; <[3 x i32]*> [#uses=1] + +define void @test(i32 %i) nounwind ssp { +entry: + br label %foo + +foo: ; preds = %indirectgoto, %indirectgoto, %indirectgoto, %indirectgoto, %indirectgoto + br label %bar + +bar: ; preds = %foo, %indirectgoto + br label %hack + +hack: ; preds = %bar, %indirectgoto + ret void +} From sabre at nondot.org Sun Jan 3 12:10:59 2010 From: sabre at nondot.org (Chris Lattner) Date: Sun, 03 Jan 2010 18:10:59 -0000 Subject: [llvm-commits] [llvm] r92451 - /llvm/trunk/test/CodeGen/X86/addr-label-difference.ll Message-ID: <201001031810.o03IAxiK012192@zion.cs.uiuc.edu> Author: lattner Date: Sun Jan 3 12:10:58 2010 New Revision: 92451 URL: http://llvm.org/viewvc/llvm-project?rev=92451&view=rev Log: add PR# Modified: llvm/trunk/test/CodeGen/X86/addr-label-difference.ll Modified: llvm/trunk/test/CodeGen/X86/addr-label-difference.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/X86/addr-label-difference.ll?rev=92451&r1=92450&r2=92451&view=diff ============================================================================== --- llvm/trunk/test/CodeGen/X86/addr-label-difference.ll (original) +++ llvm/trunk/test/CodeGen/X86/addr-label-difference.ll Sun Jan 3 12:10:58 2010 @@ -1,4 +1,5 @@ ; RUN: llc %s -o - | grep {__TEXT,__const} +; PR5929 target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:128:128-n8:16:32" target triple = "i386-apple-darwin10.0" From sabre at nondot.org Sun Jan 3 12:14:25 2010 From: sabre at nondot.org (Chris Lattner) Date: Sun, 03 Jan 2010 18:14:25 -0000 Subject: [llvm-commits] [llvm] r92452 - /llvm/trunk/lib/VMCore/Instruction.cpp Message-ID: <201001031814.o03IEQQN012348@zion.cs.uiuc.edu> Author: lattner Date: Sun Jan 3 12:14:24 2010 New Revision: 92452 URL: http://llvm.org/viewvc/llvm-project?rev=92452&view=rev Log: it isn't safe to speculative load from a malloc, it might have returned null, and may not have been big enough in any case. Thanks to Jay Foad for pointing this out! Modified: llvm/trunk/lib/VMCore/Instruction.cpp Modified: llvm/trunk/lib/VMCore/Instruction.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/VMCore/Instruction.cpp?rev=92452&r1=92451&r2=92452&view=diff ============================================================================== --- llvm/trunk/lib/VMCore/Instruction.cpp (original) +++ llvm/trunk/lib/VMCore/Instruction.cpp Sun Jan 3 12:14:24 2010 @@ -374,37 +374,6 @@ } } -// Code here matches isMalloc from MemoryBuiltins, which is not in VMCore. -static bool isMalloc(const Value* I) { - const CallInst *CI = dyn_cast(I); - if (!CI) { - const BitCastInst *BCI = dyn_cast(I); - if (!BCI) return false; - - CI = dyn_cast(BCI->getOperand(0)); - } - - if (!CI) - return false; - Function *Callee = CI->getCalledFunction(); - if (Callee == 0 || !Callee->isDeclaration() || Callee->getName() != "malloc") - return false; - - // Check malloc prototype. - // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin - // attribute will exist. - const FunctionType *FTy = Callee->getFunctionType(); - if (FTy->getNumParams() != 1) - return false; - if (IntegerType *ITy = dyn_cast(FTy->param_begin()->get())) { - if (ITy->getBitWidth() != 32 && ITy->getBitWidth() != 64) - return false; - return true; - } - - return false; -} - bool Instruction::isSafeToSpeculativelyExecute() const { for (unsigned i = 0, e = getNumOperands(); i != e; ++i) if (Constant *C = dyn_cast(getOperand(i))) @@ -430,7 +399,7 @@ case Load: { if (cast(this)->isVolatile()) return false; - if (isa(getOperand(0)) || isMalloc(getOperand(0))) + if (isa(getOperand(0))) return true; if (GlobalVariable *GV = dyn_cast(getOperand(0))) return !GV->hasExternalWeakLinkage(); From sabre at nondot.org Sun Jan 3 12:33:18 2010 From: sabre at nondot.org (Chris Lattner) Date: Sun, 03 Jan 2010 18:33:18 -0000 Subject: [llvm-commits] [llvm] r92455 - in /llvm/trunk: lib/CodeGen/AsmPrinter/AsmPrinter.cpp test/CodeGen/X86/x86-64-jumps.ll Message-ID: <201001031833.o03IXIEO013128@zion.cs.uiuc.edu> Author: lattner Date: Sun Jan 3 12:33:18 2010 New Revision: 92455 URL: http://llvm.org/viewvc/llvm-project?rev=92455&view=rev Log: fix PR5930, allowing the asmprinter to emit difference between two labels as a truncate. Modified: llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp llvm/trunk/test/CodeGen/X86/x86-64-jumps.ll Modified: llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp?rev=92455&r1=92454&r2=92455&view=diff ============================================================================== --- llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp (original) +++ llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp Sun Jan 3 12:33:18 2010 @@ -819,7 +819,6 @@ const TargetData *TD = TM.getTargetData(); unsigned Opcode = CE->getOpcode(); switch (Opcode) { - case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: case Instruction::FPTrunc: @@ -865,7 +864,6 @@ return EmitConstantValueOnly(Op); } - case Instruction::PtrToInt: { // Support only foldable casts to/from pointers that can be eliminated by // changing the pointer to the appropriately sized integer type. @@ -887,6 +885,14 @@ O << ") & " << S.str() << ')'; break; } + + case Instruction::Trunc: + // We emit the value and depend on the assembler to truncate the generated + // expression properly. This is important for differences between + // blockaddress labels. Since the two labels are in the same function, it + // is reasonable to treat their delta as a 32-bit value. + return EmitConstantValueOnly(CE->getOperand(0)); + case Instruction::Add: case Instruction::Sub: case Instruction::And: Modified: llvm/trunk/test/CodeGen/X86/x86-64-jumps.ll URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/CodeGen/X86/x86-64-jumps.ll?rev=92455&r1=92454&r2=92455&view=diff ============================================================================== --- llvm/trunk/test/CodeGen/X86/x86-64-jumps.ll (original) +++ llvm/trunk/test/CodeGen/X86/x86-64-jumps.ll Sun Jan 3 12:33:18 2010 @@ -14,3 +14,32 @@ ret i8 2 } + +; PR5930 - Trunc of block address differences. + at test.array = internal constant [3 x i32] [i32 trunc (i64 sub (i64 ptrtoint (i8* blockaddress(@test2, %foo) to i64), i64 ptrtoint (i8* blockaddress(@test2, %foo) to i64)) to i32), i32 trunc (i64 sub (i64 ptrtoint (i8* blockaddress(@test2, %bar) to i64), i64 ptrtoint (i8* blockaddress(@test2, %foo) to i64)) to i32), i32 trunc (i64 sub (i64 ptrtoint (i8* blockaddress(@test2, %hack) to i64), i64 ptrtoint (i8* blockaddress(@test2, %foo) to i64)) to i32)] ; <[3 x i32]*> [#uses=1] + +define void @test2(i32 %i) nounwind ssp { +entry: + %i.addr = alloca i32 ; [#uses=2] + store i32 %i, i32* %i.addr + %tmp = load i32* %i.addr ; [#uses=1] + %idxprom = sext i32 %tmp to i64 ; [#uses=1] + %arrayidx = getelementptr inbounds i32* getelementptr inbounds ([3 x i32]* @test.array, i32 0, i32 0), i64 %idxprom ; [#uses=1] + %tmp1 = load i32* %arrayidx ; [#uses=1] + %idx.ext = sext i32 %tmp1 to i64 ; [#uses=1] + %add.ptr = getelementptr i8* blockaddress(@test2, %foo), i64 %idx.ext ; [#uses=1] + br label %indirectgoto + +foo: ; preds = %indirectgoto, %indirectgoto, %indirectgoto, %indirectgoto, %indirectgoto + br label %bar + +bar: ; preds = %foo, %indirectgoto + br label %hack + +hack: ; preds = %bar, %indirectgoto + ret void + +indirectgoto: ; preds = %entry + %indirect.goto.dest = phi i8* [ %add.ptr, %entry ] ; [#uses=1] + indirectbr i8* %indirect.goto.dest, [label %foo, label %foo, label %bar, label %foo, label %hack, label %foo, label %foo] +} From nicholas at mxc.ca Sun Jan 3 15:56:18 2010 From: nicholas at mxc.ca (Nick Lewycky) Date: Sun, 03 Jan 2010 16:56:18 -0500 Subject: [llvm-commits] patch: partial dse Message-ID: <4B411282.3070308@mxc.ca> This patch implements partially-dead store elimination, turning: %P16 = bitcast i32* %P32 to i16 store i32 0, i32* %P32 store i16 -1, i16* %P16 into: store i32 65535, i32* %P32 Please review! At the moment, it restricts itself to the case where we have TargetData. This seems odd at first, but the problem is that DSE itself doesn't seem to be sure how many bits will be modified by a store without it. 'i32' and 'i16' are clear, but 'i6' less so (and which 2 bits does it leave alone). My opinion is that the only sane behaviour for an i6* store is that it overwrite only the first 6 bits of the pointee and no others, which is the same rule that i16* and i32* have. However, I know that this sort of thing is limited by actual hardware capabilities and wanted to ask before I implement :) It's also restricted to integers. I don't know whether it would be profitable to binary-and and binary-or together floats or pointers. We could certainly do it in the case where both sides are constant values. Nick -------------- next part -------------- A non-text attachment was scrubbed... Name: partial-dse.patch Type: text/x-patch Size: 4855 bytes Desc: not available Url : http://lists.cs.uiuc.edu/pipermail/llvm-commits/attachments/20100103/2526922f/attachment.bin From nicholas at mxc.ca Sun Jan 3 20:02:21 2010 From: nicholas at mxc.ca (Nick Lewycky) Date: Sun, 03 Jan 2010 21:02:21 -0500 Subject: [llvm-commits] patch: teach deadargelim to work on externally visible functions! Message-ID: <4B414C2D.90407@mxc.ca> This patch implements dead argument elimination for functions which are externally visible. We can't modify the function signature, but we can find all direct callers and make sure they aren't doing any work to calculate the argument that's going to be discarded. Please review! Nick -------------- next part -------------- A non-text attachment was scrubbed... Name: deadargelim.patch Type: text/x-patch Size: 8232 bytes Desc: not available Url : http://lists.cs.uiuc.edu/pipermail/llvm-commits/attachments/20100103/46c2be09/attachment.bin From clattner at apple.com Sun Jan 3 23:12:40 2010 From: clattner at apple.com (Chris Lattner) Date: Sun, 3 Jan 2010 21:12:40 -0800 Subject: [llvm-commits] [llvm] r84134 - in /llvm/trunk/lib/CodeGen/AsmPrinter: DwarfDebug.cpp DwarfDebug.h In-Reply-To: <200910142108.n9EL89PR023324@zion.cs.uiuc.edu> References: <200910142108.n9EL89PR023324@zion.cs.uiuc.edu> Message-ID: <1103E7BC-53DE-49F4-9DC1-A335327EA2A1@apple.com> On Oct 14, 2009, at 2:08 PM, Devang Patel wrote: > Author: dpatel > Date: Wed Oct 14 16:08:09 2009 > New Revision: 84134 > > URL: http://llvm.org/viewvc/llvm-project?rev=84134&view=rev > Log: > Add support to record DbgScope as inlined scope. Devang, why does InlinedAt need to be a WeakVH here? WeakVH is much more expensive than it looks. -Chris > > Modified: > llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp > llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.h > > Modified: llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp?rev=84134&r1=84133&r2=84134&view=diff > > ============================================================================== > --- llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp (original) > +++ llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp Wed Oct 14 16:08:09 2009 > @@ -145,7 +145,10 @@ > class VISIBILITY_HIDDEN DbgScope { > DbgScope *Parent; // Parent to this scope. > DIDescriptor Desc; // Debug info descriptor for scope. > - // Either subprogram or block. > + // FIXME use WeakVH for Desc. > + WeakVH InlinedAt; // If this scope represents inlined > + // function body then this is the location > + // where this body is inlined. > unsigned StartLabelID; // Label ID of the beginning of scope. > unsigned EndLabelID; // Label ID of the end of scope. > const MachineInstr *LastInsn; // Last instruction of this scope. > @@ -157,14 +160,17 @@ > // Private state for dump() > mutable unsigned IndentLevel; > public: > - DbgScope(DbgScope *P, DIDescriptor D) > - : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), LastInsn(0), > - FirstInsn(0), IndentLevel(0) {} > + DbgScope(DbgScope *P, DIDescriptor D, MDNode *I = 0) > + : Parent(P), Desc(D), InlinedAt(I), StartLabelID(0), EndLabelID(0), > + LastInsn(0), FirstInsn(0), IndentLevel(0) {} > virtual ~DbgScope(); > > // Accessors. > DbgScope *getParent() const { return Parent; } > DIDescriptor getDesc() const { return Desc; } > + MDNode *getInlinedAt() const { > + return dyn_cast_or_null(InlinedAt); > + } > unsigned getStartLabelID() const { return StartLabelID; } > unsigned getEndLabelID() const { return EndLabelID; } > SmallVector &getScopes() { return Scopes; } > @@ -1296,29 +1302,39 @@ > > /// getOrCreateScope - Returns the scope associated with the given descriptor. > /// > -DbgScope *DwarfDebug::getDbgScope(MDNode *N, const MachineInstr *MI) { > +DbgScope *DwarfDebug::getDbgScope(MDNode *N, const MachineInstr *MI, > + MDNode *InlinedAt) { > DbgScope *&Slot = DbgScopeMap[N]; > if (Slot) return Slot; > > DbgScope *Parent = NULL; > > - DIDescriptor Scope(N); > - if (Scope.isCompileUnit()) { > - return NULL; > - } else if (Scope.isSubprogram()) { > - DISubprogram SP(N); > - DIDescriptor ParentDesc = SP.getContext(); > - if (!ParentDesc.isNull() && !ParentDesc.isCompileUnit()) > - Parent = getDbgScope(ParentDesc.getNode(), MI); > - } else if (Scope.isLexicalBlock()) { > - DILexicalBlock DB(N); > - DIDescriptor ParentDesc = DB.getContext(); > - if (!ParentDesc.isNull()) > - Parent = getDbgScope(ParentDesc.getNode(), MI); > - } else > - assert (0 && "Unexpected scope info"); > + if (InlinedAt) { > + DILocation IL(InlinedAt); > + assert (!IL.isNull() && "Invalid InlindAt location!"); > + DenseMap::iterator DSI = > + DbgScopeMap.find(IL.getScope().getNode()); > + assert (DSI != DbgScopeMap.end() && "Unable to find InlineAt scope!"); > + Parent = DSI->second; > + } else { > + DIDescriptor Scope(N); > + if (Scope.isCompileUnit()) { > + return NULL; > + } else if (Scope.isSubprogram()) { > + DISubprogram SP(N); > + DIDescriptor ParentDesc = SP.getContext(); > + if (!ParentDesc.isNull() && !ParentDesc.isCompileUnit()) > + Parent = getDbgScope(ParentDesc.getNode(), MI, InlinedAt); > + } else if (Scope.isLexicalBlock()) { > + DILexicalBlock DB(N); > + DIDescriptor ParentDesc = DB.getContext(); > + if (!ParentDesc.isNull()) > + Parent = getDbgScope(ParentDesc.getNode(), MI, InlinedAt); > + } else > + assert (0 && "Unexpected scope info"); > + } > > - Slot = new DbgScope(Parent, DIDescriptor(N)); > + Slot = new DbgScope(Parent, DIDescriptor(N), InlinedAt); > Slot->setFirstInsn(MI); > > if (Parent) > @@ -1795,7 +1811,10 @@ > DIVariable DV (Var); > if (DV.isNull()) continue; > unsigned VSlot = VI->second; > - DbgScope *Scope = getDbgScope(DV.getContext().getNode(), NULL); > + DenseMap::iterator DSI = > + DbgScopeMap.find(DV.getContext().getNode()); > + assert (DSI != DbgScopeMap.end() && "Unable to find variable scope!"); > + DbgScope *Scope = DSI->second; > Scope->AddVariable(new DbgVariable(DV, VSlot, false)); > } > } > @@ -1849,7 +1868,7 @@ > // into a scope DIE at the end. > DIDescriptor D(DLT.Scope); > if (!D.isCompileUnit()) { > - DbgScope *Scope = getDbgScope(DLT.Scope, MInsn); > + DbgScope *Scope = getDbgScope(DLT.Scope, MInsn, DLT.InlinedAtLoc); > Scope->setLastInsn(MInsn); > } > } > > Modified: llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.h > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.h?rev=84134&r1=84133&r2=84134&view=diff > > ============================================================================== > --- llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.h (original) > +++ llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.h Wed Oct 14 16:08:09 2009 > @@ -364,7 +364,7 @@ > /// getDbgScope - Returns the scope associated with the given descriptor. > /// > DbgScope *getOrCreateScope(MDNode *N); > - DbgScope *getDbgScope(MDNode *N, const MachineInstr *MI); > + DbgScope *getDbgScope(MDNode *N, const MachineInstr *MI, MDNode *InlinedAt); > > /// ConstructDbgScope - Construct the components of a scope. > /// > > > _______________________________________________ > llvm-commits mailing list > llvm-commits at cs.uiuc.edu > http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits From clattner at apple.com Sun Jan 3 23:22:07 2010 From: clattner at apple.com (Chris Lattner) Date: Sun, 3 Jan 2010 21:22:07 -0800 Subject: [llvm-commits] [llvm] r83207 - /llvm/trunk/lib/CodeGen/AsmPrinter/DwarfDebug.cpp In-Reply-To: <4764FB07-DE5E-457B-91C7-25E07D0297A9@apple.com> References: <200910011825.n91IPNZF028439@zion.cs.uiuc.edu> <0C06FEC3-55F5-477E-A885-3D9EE47AD5AD@apple.com> <4764FB07-DE5E-457B-91C7-25E07D0297A9@apple.com> Message-ID: <3BE3E47E-F850-47A6-A28B-163A7C01A34E@apple.com> On Oct 1, 2009, at 2:35 PM, Evan Cheng wrote: > Can't we compute these on demand so codegen passes don't have to change these? Devang, I never saw an answer to this. I have serious concerns about DbgScope and the presence of two MachineInstr*'s that can dangle seems very dubious. -Chris > > Evan > > On Oct 1, 2009, at 2:25 PM, Devang Patel wrote: > >> >> On Oct 1, 2009, at 1:38 PM, Dan Gohman wrote: >> >>> >>> On Oct 1, 2009, at 11:25 AM, Devang Patel wrote: >>> >>>> Author: dpatel >>>> Date: Thu Oct 1 13:25:23 2009 >>>> New Revision: 83207 >>>> >>>> URL: http://llvm.org/viewvc/llvm-project?rev=83207&view=rev >>>> Log: >>>> Record first and last instruction of a scope in DbgScope. >>> >>> How does this interact with Post-RA scheduling, MachineLICM, and MachineHoist? >> >> It depends on when we run this DwarfDebug pass. Today, at iSel time we put the stake in the ground and emit label node (or instruction) to mark scope boundaries. In future, this will be divided into three steps >> >> 1 - Just before AsmPrinter, the DwarfDebug will note down scope boundaries in DbgScope based on info attached with an machine instruction. >> 2 - @processDebugLoc() in AsmPrinter the labels will be emitted to mark scope boundaries and DW will be updated according. >> 3 - At the end, the scope DIEs will be created based on DbgScope entries. >> >> So MachineLICM will have as much freedom as standard LICM. >> >> - >> Devang >> _______________________________________________ >> llvm-commits mailing list >> llvm-commits at cs.uiuc.edu >> http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits > > _______________________________________________ > llvm-commits mailing list > llvm-commits at cs.uiuc.edu > http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits -------------- next part -------------- An HTML attachment was scrubbed... URL: http://lists.cs.uiuc.edu/pipermail/llvm-commits/attachments/20100103/644f9029/attachment.html From clattner at apple.com Sun Jan 3 23:23:09 2010 From: clattner at apple.com (Chris Lattner) Date: Sun, 3 Jan 2010 21:23:09 -0800 Subject: [llvm-commits] [llvm] r83190 - in /llvm/trunk: include/llvm/Support/DebugLoc.h lib/Analysis/DebugInfo.cpp lib/CodeGen/AsmPrinter/AsmPrinter.cpp In-Reply-To: <200910010115.n911FSZQ014854@zion.cs.uiuc.edu> References: <200910010115.n911FSZQ014854@zion.cs.uiuc.edu> Message-ID: <2BABC018-0E6F-4477-B8A0-B6ACB5F17E4F@apple.com> On Sep 30, 2009, at 6:15 PM, Devang Patel wrote: > Author: dpatel > Date: Wed Sep 30 20:15:28 2009 > New Revision: 83190 > > URL: http://llvm.org/viewvc/llvm-project?rev=83190&view=rev > Log: > Add another MDNode into DebugLocTuple. This will be used to keep track of inlined functions. Do you need both InlinedLoc and CompileUnit? Can't one be obtained from the other? -Chris > > Modified: > llvm/trunk/include/llvm/Support/DebugLoc.h > llvm/trunk/lib/Analysis/DebugInfo.cpp > llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp > > Modified: llvm/trunk/include/llvm/Support/DebugLoc.h > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/DebugLoc.h?rev=83190&r1=83189&r2=83190&view=diff > > ============================================================================== > --- llvm/trunk/include/llvm/Support/DebugLoc.h (original) > +++ llvm/trunk/include/llvm/Support/DebugLoc.h Wed Sep 30 20:15:28 2009 > @@ -25,17 +25,19 @@ > /// > struct DebugLocTuple { > MDNode *CompileUnit; > + MDNode *InlinedLoc; > unsigned Line, Col; > > DebugLocTuple() > - : CompileUnit(0), Line(~0U), Col(~0U) {}; > + : CompileUnit(0), InlinedLoc(0), Line(~0U), Col(~0U) {}; > > - DebugLocTuple(MDNode *n, unsigned l, unsigned c) > - : CompileUnit(n), Line(l), Col(c) {}; > + DebugLocTuple(MDNode *n, MDNode *i, unsigned l, unsigned c) > + : CompileUnit(n), InlinedLoc(i), Line(l), Col(c) {}; > > bool operator==(const DebugLocTuple &DLT) const { > return CompileUnit == DLT.CompileUnit && > - Line == DLT.Line && Col == DLT.Col; > + InlinedLoc == DLT.InlinedLoc && > + Line == DLT.Line && Col == DLT.Col; > } > bool operator!=(const DebugLocTuple &DLT) const { > return !(*this == DLT); > @@ -66,18 +68,20 @@ > // Specialize DenseMapInfo for DebugLocTuple. > template<> struct DenseMapInfo { > static inline DebugLocTuple getEmptyKey() { > - return DebugLocTuple(0, ~0U, ~0U); > + return DebugLocTuple(0, 0, ~0U, ~0U); > } > static inline DebugLocTuple getTombstoneKey() { > - return DebugLocTuple((MDNode*)~1U, ~1U, ~1U); > + return DebugLocTuple((MDNode*)~1U, (MDNode*)~1U, ~1U, ~1U); > } > static unsigned getHashValue(const DebugLocTuple &Val) { > return DenseMapInfo::getHashValue(Val.CompileUnit) ^ > + DenseMapInfo::getHashValue(Val.InlinedLoc) ^ > DenseMapInfo::getHashValue(Val.Line) ^ > DenseMapInfo::getHashValue(Val.Col); > } > static bool isEqual(const DebugLocTuple &LHS, const DebugLocTuple &RHS) { > return LHS.CompileUnit == RHS.CompileUnit && > + LHS.InlinedLoc == RHS.InlinedLoc && > LHS.Line == RHS.Line && > LHS.Col == RHS.Col; > } > > Modified: llvm/trunk/lib/Analysis/DebugInfo.cpp > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Analysis/DebugInfo.cpp?rev=83190&r1=83189&r2=83190&view=diff > > ============================================================================== > --- llvm/trunk/lib/Analysis/DebugInfo.cpp (original) > +++ llvm/trunk/lib/Analysis/DebugInfo.cpp Wed Sep 30 20:15:28 2009 > @@ -952,7 +952,6 @@ > /// processModule - Process entire module and collect debug info. > void DebugInfoFinder::processModule(Module &M) { > > - > for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) > for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI) > for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE; > @@ -1271,7 +1270,7 @@ > Value *Context = SPI.getContext(); > > // If this location is already tracked then use it. > - DebugLocTuple Tuple(cast(Context), SPI.getLine(), > + DebugLocTuple Tuple(cast(Context), NULL, SPI.getLine(), > SPI.getColumn()); > DenseMap::iterator II > = DebugLocInfo.DebugIdMap.find(Tuple); > @@ -1292,9 +1291,11 @@ > DebugLocTracker &DebugLocInfo) { > DebugLoc DL; > MDNode *Context = Loc.getScope().getNode(); > - > + MDNode *InlinedLoc = NULL; > + if (!Loc.getOrigLocation().isNull()) > + InlinedLoc = Loc.getOrigLocation().getNode(); > // If this location is already tracked then use it. > - DebugLocTuple Tuple(Context, Loc.getLineNumber(), > + DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(), > Loc.getColumnNumber()); > DenseMap::iterator II > = DebugLocInfo.DebugIdMap.find(Tuple); > @@ -1321,7 +1322,7 @@ > DICompileUnit CU(Subprogram.getCompileUnit()); > > // If this location is already tracked then use it. > - DebugLocTuple Tuple(CU.getNode(), Line, /* Column */ 0); > + DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0); > DenseMap::iterator II > = DebugLocInfo.DebugIdMap.find(Tuple); > if (II != DebugLocInfo.DebugIdMap.end()) > > Modified: llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp > URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp?rev=83190&r1=83189&r2=83190&view=diff > > ============================================================================== > --- llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp (original) > +++ llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinter.cpp Wed Sep 30 20:15:28 2009 > @@ -60,7 +60,7 @@ > OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)), > > LastMI(0), LastFn(0), Counter(~0U), > - PrevDLT(0, ~0U, ~0U) { > + PrevDLT(0, 0, ~0U, ~0U) { > DW = 0; MMI = 0; > switch (AsmVerbose) { > case cl::BOU_UNSET: VerboseAsm = VDef; break; > > > _______________________________________________ > llvm-commits mailing list > llvm-commits at cs.uiuc.edu > http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits