From: Eugene Zelenko Date: Wed, 11 Oct 2017 21:41:43 +0000 (+0000) Subject: [Transforms] Fix some Clang-tidy modernize and Include What You Use warnings; other... X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=761e543ac73ddc55d2cf3c6892fe18eecb0c89d9;p=llvm [Transforms] Fix some Clang-tidy modernize and Include What You Use warnings; other minor fixes (NFC). git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@315516 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/include/llvm/Transforms/Utils/CodeExtractor.h b/include/llvm/Transforms/Utils/CodeExtractor.h index 682b353ab5a..acbea804392 100644 --- a/include/llvm/Transforms/Utils/CodeExtractor.h +++ b/include/llvm/Transforms/Utils/CodeExtractor.h @@ -1,4 +1,4 @@ -//===-- Transform/Utils/CodeExtractor.h - Code extraction util --*- C++ -*-===// +//===- Transform/Utils/CodeExtractor.h - Code extraction util ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -15,22 +15,24 @@ #ifndef LLVM_TRANSFORMS_UTILS_CODEEXTRACTOR_H #define LLVM_TRANSFORMS_UTILS_CODEEXTRACTOR_H +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SetVector.h" +#include namespace llvm { -template class ArrayRef; - class BasicBlock; - class BlockFrequency; - class BlockFrequencyInfo; - class BranchProbabilityInfo; - class DominatorTree; - class Function; - class Instruction; - class Loop; - class Module; - class RegionNode; - class Type; - class Value; + +class BasicBlock; +class BlockFrequency; +class BlockFrequencyInfo; +class BranchProbabilityInfo; +class DominatorTree; +class Function; +class Instruction; +class Loop; +class Module; +class Type; +class Value; /// \brief Utility class for extracting code into a new function. /// @@ -46,7 +48,7 @@ template class ArrayRef; /// 3) Add allocas for any scalar outputs, adding all of the outputs' allocas /// as arguments, and inserting stores to the arguments for any scalars. class CodeExtractor { - typedef SetVector ValueSet; + using ValueSet = SetVector; // Various bits of state computed on construction. DominatorTree *const DT; @@ -56,16 +58,10 @@ template class ArrayRef; // Bits of intermediate state computed at various phases of extraction. SetVector Blocks; - unsigned NumExitBlocks; + unsigned NumExitBlocks = std::numeric_limits::max(); Type *RetTy; public: - - /// \brief Check to see if a block is valid for extraction. - /// - /// Blocks containing EHPads, allocas, invokes, or vastarts are not valid. - static bool isBlockValidForExtraction(const BasicBlock &BB); - /// \brief Create a code extractor for a sequence of blocks. /// /// Given a sequence of basic blocks where the first block in the sequence @@ -84,6 +80,11 @@ template class ArrayRef; BlockFrequencyInfo *BFI = nullptr, BranchProbabilityInfo *BPI = nullptr); + /// \brief Check to see if a block is valid for extraction. + /// + /// Blocks containing EHPads, allocas, invokes, or vastarts are not valid. + static bool isBlockValidForExtraction(const BasicBlock &BB); + /// \brief Perform the extraction, returning the new function. /// /// Returns zero when called on a CodeExtractor instance where isEligible @@ -112,6 +113,7 @@ template class ArrayRef; /// /// Returns true if it is safe to do the code motion. bool isLegalToShrinkwrapLifetimeMarkers(Instruction *AllocaAddr) const; + /// Find the set of allocas whose life ranges are contained within the /// outlined region. /// @@ -155,6 +157,7 @@ template class ArrayRef; ValueSet &inputs, ValueSet &outputs); }; -} -#endif +} // end namespace llvm + +#endif // LLVM_TRANSFORMS_UTILS_CODEEXTRACTOR_H diff --git a/include/llvm/Transforms/Utils/FunctionComparator.h b/include/llvm/Transforms/Utils/FunctionComparator.h index b0f10eafaa9..e0c79a1027e 100644 --- a/include/llvm/Transforms/Utils/FunctionComparator.h +++ b/include/llvm/Transforms/Utils/FunctionComparator.h @@ -15,10 +15,10 @@ #ifndef LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H #define LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H -#include "llvm/ADT/APFloat.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/StringRef.h" -#include "llvm/IR/Function.h" +#include "llvm/IR/Attributes.h" +#include "llvm/IR/Instructions.h" #include "llvm/IR/Operator.h" #include "llvm/IR/ValueMap.h" #include "llvm/Support/AtomicOrdering.h" @@ -28,7 +28,17 @@ namespace llvm { -class GetElementPtrInst; +class APFloat; +class APInt; +class BasicBlock; +class Constant; +class Function; +class GlobalValue; +class InlineAsm; +class Instruction; +class MDNode; +class Type; +class Value; /// GlobalNumberState assigns an integer to each global value in the program, /// which is used by the comparison routine to order references to globals. This @@ -43,14 +53,16 @@ class GetElementPtrInst; /// compare those, but this would not work for stripped bitcodes or for those /// few symbols without a name. class GlobalNumberState { - struct Config : ValueMapConfig { + struct Config : ValueMapConfig { enum { FollowRAUW = false }; }; + // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW // occurs, the mapping does not change. Tracking changes is unnecessary, and // also problematic for weak symbols (which may be overwritten). - typedef ValueMap ValueNumberMap; + using ValueNumberMap = ValueMap; ValueNumberMap GlobalNumbers; + // The next unused serial number to assign to a global. uint64_t NextNumber = 0; @@ -83,9 +95,10 @@ public: /// Test whether the two functions have equivalent behaviour. int compare(); + /// Hash a function. Equivalent functions will have the same hash, and unequal /// functions will have different hashes with high probability. - typedef uint64_t FunctionHash; + using FunctionHash = uint64_t; static FunctionHash functionHash(Function &); protected: diff --git a/include/llvm/Transforms/Utils/PredicateInfo.h b/include/llvm/Transforms/Utils/PredicateInfo.h index 8150f152839..bc1e405a56c 100644 --- a/include/llvm/Transforms/Utils/PredicateInfo.h +++ b/include/llvm/Transforms/Utils/PredicateInfo.h @@ -1,4 +1,4 @@ -//===- PredicateInfo.h - Build PredicateInfo ----------------------*-C++-*-===// +//===- PredicateInfo.h - Build PredicateInfo --------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -6,7 +6,7 @@ // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// -/// +// /// \file /// \brief This file implements the PredicateInfo analysis, which creates an Extended /// SSA form for operations used in branch comparisons and llvm.assume @@ -44,8 +44,7 @@ /// inserted where it would actually be live. This means if there are no uses of /// an operation dominated by the branch edges, or by an assume, the associated /// predicate info is never inserted. -/// -/// +// //===----------------------------------------------------------------------===// #ifndef LLVM_TRANSFORMS_UTILS_PREDICATEINFO_H @@ -57,39 +56,27 @@ #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/ilist.h" #include "llvm/ADT/ilist_node.h" -#include "llvm/ADT/iterator.h" -#include "llvm/Analysis/AssumptionCache.h" -#include "llvm/IR/BasicBlock.h" -#include "llvm/IR/Dominators.h" #include "llvm/IR/Instructions.h" -#include "llvm/IR/IntrinsicInst.h" -#include "llvm/IR/Module.h" -#include "llvm/IR/OperandTraits.h" -#include "llvm/IR/Type.h" -#include "llvm/IR/Use.h" -#include "llvm/IR/User.h" -#include "llvm/IR/Value.h" #include "llvm/Pass.h" -#include "llvm/PassAnalysisSupport.h" -#include "llvm/Support/Casting.h" -#include "llvm/Support/Compiler.h" -#include "llvm/Support/ErrorHandling.h" #include "llvm/Transforms/Utils/OrderedInstructions.h" -#include -#include -#include -#include -#include #include namespace llvm { +class AssumptionCache; +class BasicBlock; class DominatorTree; class Function; -class Instruction; -class MemoryAccess; -class LLVMContext; +class IntrinsicInst; class raw_ostream; +class Value; + +// This name is used in a few places, so kick it into their own namespace +namespace PredicateInfoClasses { + +struct ValueDFS; + +} enum PredicateType { PT_Branch, PT_Assume, PT_Switch }; @@ -98,10 +85,12 @@ enum PredicateType { PT_Branch, PT_Assume, PT_Switch }; class PredicateBase : public ilist_node { public: PredicateType Type; + // The original operand before we renamed it. // This can be use by passes, when destroying predicateinfo, to know // whether they can just drop the intrinsic, or have to merge metadata. Value *OriginalOp; + PredicateBase(const PredicateBase &) = delete; PredicateBase &operator=(const PredicateBase &) = delete; PredicateBase() = delete; @@ -114,6 +103,7 @@ protected: class PredicateWithCondition : public PredicateBase { public: Value *Condition; + static bool classof(const PredicateBase *PB) { return PB->Type == PT_Assume || PB->Type == PT_Branch || PB->Type == PT_Switch; @@ -130,10 +120,12 @@ protected: class PredicateAssume : public PredicateWithCondition { public: IntrinsicInst *AssumeInst; + PredicateAssume(Value *Op, IntrinsicInst *AssumeInst, Value *Condition) : PredicateWithCondition(PT_Assume, Op, Condition), AssumeInst(AssumeInst) {} PredicateAssume() = delete; + static bool classof(const PredicateBase *PB) { return PB->Type == PT_Assume; } @@ -146,7 +138,9 @@ class PredicateWithEdge : public PredicateWithCondition { public: BasicBlock *From; BasicBlock *To; + PredicateWithEdge() = delete; + static bool classof(const PredicateBase *PB) { return PB->Type == PT_Branch || PB->Type == PT_Switch; } @@ -162,11 +156,13 @@ class PredicateBranch : public PredicateWithEdge { public: // If true, SplitBB is the true successor, otherwise it's the false successor. bool TrueEdge; + PredicateBranch(Value *Op, BasicBlock *BranchBB, BasicBlock *SplitBB, Value *Condition, bool TakenEdge) : PredicateWithEdge(PT_Branch, Op, BranchBB, SplitBB, Condition), TrueEdge(TakenEdge) {} PredicateBranch() = delete; + static bool classof(const PredicateBase *PB) { return PB->Type == PT_Branch; } @@ -175,24 +171,22 @@ public: class PredicateSwitch : public PredicateWithEdge { public: Value *CaseValue; + // This is the switch instruction. SwitchInst *Switch; + PredicateSwitch(Value *Op, BasicBlock *SwitchBB, BasicBlock *TargetBB, Value *CaseValue, SwitchInst *SI) : PredicateWithEdge(PT_Switch, Op, SwitchBB, TargetBB, SI->getCondition()), CaseValue(CaseValue), Switch(SI) {} PredicateSwitch() = delete; + static bool classof(const PredicateBase *PB) { return PB->Type == PT_Switch; } }; -// This name is used in a few places, so kick it into their own namespace -namespace PredicateInfoClasses { -struct ValueDFS; -} - /// \brief Encapsulates PredicateInfo, including all data associated with memory /// accesses. class PredicateInfo { @@ -205,11 +199,12 @@ private: SmallVector Infos; SmallVector UninsertedInfos; }; + // This owns the all the predicate infos in the function, placed or not. iplist AllInfos; public: - PredicateInfo(Function &, DominatorTree &, AssumptionCache &); + PredicateInfo(Function &F, DominatorTree &DT, AssumptionCache &AC); ~PredicateInfo(); void verifyPredicateInfo() const; @@ -227,13 +222,14 @@ protected: friend class PredicateInfoPrinterLegacyPass; private: + using ValueDFS = PredicateInfoClasses::ValueDFS; + using ValueDFSStack = SmallVectorImpl; + void buildPredicateInfo(); void processAssume(IntrinsicInst *, BasicBlock *, SmallPtrSetImpl &); void processBranch(BranchInst *, BasicBlock *, SmallPtrSetImpl &); void processSwitch(SwitchInst *, BasicBlock *, SmallPtrSetImpl &); void renameUses(SmallPtrSetImpl &); - using ValueDFS = PredicateInfoClasses::ValueDFS; - typedef SmallVectorImpl ValueDFSStack; void convertUsesToDFSOrdered(Value *, SmallVectorImpl &); Value *materializeStack(unsigned int &, ValueDFSStack &, Value *); bool stackIsInScope(const ValueDFSStack &, const ValueDFS &) const; @@ -242,22 +238,27 @@ private: void addInfoFor(SmallPtrSetImpl &OpsToRename, Value *Op, PredicateBase *PB); const ValueInfo &getValueInfo(Value *) const; + Function &F; DominatorTree &DT; AssumptionCache &AC; OrderedInstructions OI; + // This maps from copy operands to Predicate Info. Note that it does not own // the Predicate Info, they belong to the ValueInfo structs in the ValueInfos // vector. DenseMap PredicateMap; + // This stores info about each operand or comparison result we make copies // of. The real ValueInfos start at index 1, index 0 is unused so that we can // more easily detect invalid indexing. SmallVector ValueInfos; + // This gives the index into the ValueInfos array for a given Value. Because // 0 is not a valid Value Info index, you can use DenseMap::lookup and tell // whether it returned a valid result. DenseMap ValueInfoNums; + // The set of edges along which we can only handle phi uses, due to critical // edges. DenseSet> EdgeUsesOnly; @@ -268,9 +269,10 @@ private: // the tests to be able to build, dump, and verify PredicateInfo. class PredicateInfoPrinterLegacyPass : public FunctionPass { public: + static char ID; + PredicateInfoPrinterLegacyPass(); - static char ID; bool runOnFunction(Function &) override; void getAnalysisUsage(AnalysisUsage &AU) const override; }; @@ -282,6 +284,7 @@ class PredicateInfoPrinterPass public: explicit PredicateInfoPrinterPass(raw_ostream &OS) : OS(OS) {} + PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); }; diff --git a/include/llvm/Transforms/Utils/SSAUpdater.h b/include/llvm/Transforms/Utils/SSAUpdater.h index 8cbcdf47156..6cd9f1539b0 100644 --- a/include/llvm/Transforms/Utils/SSAUpdater.h +++ b/include/llvm/Transforms/Utils/SSAUpdater.h @@ -1,4 +1,4 @@ -//===-- SSAUpdater.h - Unstructured SSA Update Tool -------------*- C++ -*-===// +//===- SSAUpdater.h - Unstructured SSA Update Tool --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -14,6 +14,7 @@ #ifndef LLVM_TRANSFORMS_UTILS_SSAUPDATER_H #define LLVM_TRANSFORMS_UTILS_SSAUPDATER_H +#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include @@ -22,10 +23,9 @@ namespace llvm { class BasicBlock; class Instruction; class LoadInst; -template class ArrayRef; +class PHINode; template class SmallVectorImpl; template class SSAUpdaterTraits; -class PHINode; class Type; class Use; class Value; @@ -42,7 +42,6 @@ class SSAUpdater { private: /// This keeps track of which value to use on a per-block basis. When we /// insert PHI nodes, we keep track of them here. - //typedef DenseMap AvailableValsTy; void *AV = nullptr; /// ProtoType holds the type of the values being rewritten. @@ -53,12 +52,12 @@ private: /// If this is non-null, the SSAUpdater adds all PHI nodes that it creates to /// the vector. - SmallVectorImpl *InsertedPHIs; + SmallVectorImpl *InsertedPHIs; public: /// If InsertedPHIs is specified, it will be filled /// in with all PHI Nodes created by rewriting. - explicit SSAUpdater(SmallVectorImpl *InsertedPHIs = nullptr); + explicit SSAUpdater(SmallVectorImpl *InsertedPHIs = nullptr); SSAUpdater(const SSAUpdater &) = delete; SSAUpdater &operator=(const SSAUpdater &) = delete; ~SSAUpdater(); @@ -136,7 +135,7 @@ protected: SSAUpdater &SSA; public: - LoadAndStorePromoter(ArrayRef Insts, + LoadAndStorePromoter(ArrayRef Insts, SSAUpdater &S, StringRef Name = StringRef()); virtual ~LoadAndStorePromoter() = default; @@ -145,32 +144,28 @@ public: /// Insts is a list of loads and stores to promote, and Name is the basename /// for the PHIs to insert. After this is complete, the loads and stores are /// removed from the code. - void run(const SmallVectorImpl &Insts) const; + void run(const SmallVectorImpl &Insts) const; /// \brief Return true if the specified instruction is in the Inst list. /// /// The Insts list is the one passed into the constructor. Clients should /// implement this with a more efficient version if possible. virtual bool isInstInList(Instruction *I, - const SmallVectorImpl &Insts) const; + const SmallVectorImpl &Insts) const; /// \brief This hook is invoked after all the stores are found and inserted as /// available values. - virtual void doExtraRewritesBeforeFinalDeletion() const { - } + virtual void doExtraRewritesBeforeFinalDeletion() const {} /// \brief Clients can choose to implement this to get notified right before /// a load is RAUW'd another value. - virtual void replaceLoadWithValue(LoadInst *LI, Value *V) const { - } + virtual void replaceLoadWithValue(LoadInst *LI, Value *V) const {} /// \brief Called before each instruction is deleted. - virtual void instructionDeleted(Instruction *I) const { - } + virtual void instructionDeleted(Instruction *I) const {} /// \brief Called to update debug info associated with the instruction. - virtual void updateDebugInfo(Instruction *I) const { - } + virtual void updateDebugInfo(Instruction *I) const {} }; } // end namespace llvm diff --git a/include/llvm/Transforms/Utils/SSAUpdaterImpl.h b/include/llvm/Transforms/Utils/SSAUpdaterImpl.h index 2dd205d8b2a..b1611d49a45 100644 --- a/include/llvm/Transforms/Utils/SSAUpdaterImpl.h +++ b/include/llvm/Transforms/Utils/SSAUpdaterImpl.h @@ -1,4 +1,4 @@ -//===-- SSAUpdaterImpl.h - SSA Updater Implementation -----------*- C++ -*-===// +//===- SSAUpdaterImpl.h - SSA Updater Implementation ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -17,17 +17,14 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" -#include "llvm/IR/Instructions.h" -#include "llvm/IR/ValueHandle.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/raw_ostream.h" #define DEBUG_TYPE "ssaupdater" namespace llvm { -class CastInst; -class PHINode; template class SSAUpdaterTraits; template @@ -35,51 +32,67 @@ class SSAUpdaterImpl { private: UpdaterT *Updater; - typedef SSAUpdaterTraits Traits; - typedef typename Traits::BlkT BlkT; - typedef typename Traits::ValT ValT; - typedef typename Traits::PhiT PhiT; + using Traits = SSAUpdaterTraits; + using BlkT = typename Traits::BlkT; + using ValT = typename Traits::ValT; + using PhiT = typename Traits::PhiT; /// BBInfo - Per-basic block information used internally by SSAUpdaterImpl. /// The predecessors of each block are cached here since pred_iterator is /// slow and we need to iterate over the blocks at least a few times. class BBInfo { public: - BlkT *BB; // Back-pointer to the corresponding block. - ValT AvailableVal; // Value to use in this block. - BBInfo *DefBB; // Block that defines the available value. - int BlkNum; // Postorder number. - BBInfo *IDom; // Immediate dominator. - unsigned NumPreds; // Number of predecessor blocks. - BBInfo **Preds; // Array[NumPreds] of predecessor blocks. - PhiT *PHITag; // Marker for existing PHIs that match. + // Back-pointer to the corresponding block. + BlkT *BB; + + // Value to use in this block. + ValT AvailableVal; + + // Block that defines the available value. + BBInfo *DefBB; + + // Postorder number. + int BlkNum = 0; + + // Immediate dominator. + BBInfo *IDom = nullptr; + + // Number of predecessor blocks. + unsigned NumPreds = 0; + + // Array[NumPreds] of predecessor blocks. + BBInfo **Preds = nullptr; + + // Marker for existing PHIs that match. + PhiT *PHITag = nullptr; BBInfo(BlkT *ThisBB, ValT V) - : BB(ThisBB), AvailableVal(V), DefBB(V ? this : nullptr), BlkNum(0), - IDom(nullptr), NumPreds(0), Preds(nullptr), PHITag(nullptr) {} + : BB(ThisBB), AvailableVal(V), DefBB(V ? this : nullptr) {} }; - typedef DenseMap AvailableValsTy; + using AvailableValsTy = DenseMap; + AvailableValsTy *AvailableVals; - SmallVectorImpl *InsertedPHIs; + SmallVectorImpl *InsertedPHIs; + + using BlockListTy = SmallVectorImpl; + using BBMapTy = DenseMap; - typedef SmallVectorImpl BlockListTy; - typedef DenseMap BBMapTy; BBMapTy BBMap; BumpPtrAllocator Allocator; public: explicit SSAUpdaterImpl(UpdaterT *U, AvailableValsTy *A, - SmallVectorImpl *Ins) : - Updater(U), AvailableVals(A), InsertedPHIs(Ins) { } + SmallVectorImpl *Ins) : + Updater(U), AvailableVals(A), InsertedPHIs(Ins) {} /// GetValue - Check to see if AvailableVals has an entry for the specified /// BB and if so, return it. If not, construct SSA form by first /// calculating the required placement of PHIs and then inserting new PHIs /// where needed. ValT GetValue(BlkT *BB) { - SmallVector BlockList; + SmallVector BlockList; BBInfo *PseudoEntry = BuildBlockList(BB, &BlockList); // Special case: bail out if BB is unreachable. @@ -101,8 +114,8 @@ public: /// Create BBInfo structures for the blocks and append them to the block /// list. BBInfo *BuildBlockList(BlkT *BB, BlockListTy *BlockList) { - SmallVector RootList; - SmallVector WorkList; + SmallVector RootList; + SmallVector WorkList; BBInfo *Info = new (Allocator) BBInfo(BB, 0); BBMap[BB] = Info; @@ -111,7 +124,7 @@ public: // Search backward from BB, creating BBInfos along the way and stopping // when reaching blocks that define the value. Record those defining // blocks on the RootList. - SmallVector Preds; + SmallVector Preds; while (!WorkList.empty()) { Info = WorkList.pop_back_val(); Preds.clear(); @@ -395,7 +408,7 @@ public: /// CheckIfPHIMatches - Check if a PHI node matches the placement and values /// in the BBMap. bool CheckIfPHIMatches(PhiT *PHI) { - SmallVector WorkList; + SmallVector WorkList; WorkList.push_back(PHI); // Mark that the block containing this PHI has been visited. @@ -453,7 +466,7 @@ public: } }; -} // end llvm namespace +} // end namespace llvm #undef DEBUG_TYPE // "ssaupdater" diff --git a/include/llvm/Transforms/Utils/SymbolRewriter.h b/include/llvm/Transforms/Utils/SymbolRewriter.h index 93658989fba..e0caf7741ff 100644 --- a/include/llvm/Transforms/Utils/SymbolRewriter.h +++ b/include/llvm/Transforms/Utils/SymbolRewriter.h @@ -1,4 +1,4 @@ -//===-- SymbolRewriter.h - Symbol Rewriting Pass ----------------*- C++ -*-===// +//===- SymbolRewriter.h - Symbol Rewriting Pass -----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // @@ -33,7 +33,6 @@ #ifndef LLVM_TRANSFORMS_UTILS_SYMBOLREWRITER_H #define LLVM_TRANSFORMS_UTILS_SYMBOLREWRITER_H -#include "llvm/IR/Module.h" #include "llvm/IR/PassManager.h" #include #include @@ -42,6 +41,8 @@ namespace llvm { class MemoryBuffer; +class Module; +class ModulePass; namespace yaml { @@ -89,7 +90,7 @@ private: const Type Kind; }; -typedef std::list> RewriteDescriptorList; +using RewriteDescriptorList = std::list>; class RewriteMapParser { public: @@ -120,6 +121,7 @@ ModulePass *createRewriteSymbolsPass(SymbolRewriter::RewriteDescriptorList &); class RewriteSymbolPass : public PassInfoMixin { public: RewriteSymbolPass() { loadAndParseMapFiles(); } + RewriteSymbolPass(SymbolRewriter::RewriteDescriptorList &DL) { Descriptors.splice(Descriptors.begin(), DL); } diff --git a/lib/Transforms/Utils/CodeExtractor.cpp b/lib/Transforms/Utils/CodeExtractor.cpp index b6cea517346..0bcf58bd490 100644 --- a/lib/Transforms/Utils/CodeExtractor.cpp +++ b/lib/Transforms/Utils/CodeExtractor.cpp @@ -14,34 +14,57 @@ //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/CodeExtractor.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" -#include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallVector.h" #include "llvm/Analysis/BlockFrequencyInfo.h" #include "llvm/Analysis/BlockFrequencyInfoImpl.h" #include "llvm/Analysis/BranchProbabilityInfo.h" #include "llvm/Analysis/LoopInfo.h" -#include "llvm/Analysis/RegionInfo.h" -#include "llvm/Analysis/RegionIterator.h" +#include "llvm/IR/Argument.h" +#include "llvm/IR/Attributes.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/CFG.h" +#include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" +#include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Dominators.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/GlobalValue.h" +#include "llvm/IR/InstrTypes.h" +#include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" +#include "llvm/IR/Type.h" +#include "llvm/IR/User.h" +#include "llvm/IR/Value.h" #include "llvm/IR/Verifier.h" #include "llvm/Pass.h" #include "llvm/Support/BlockFrequency.h" +#include "llvm/Support/BranchProbability.h" +#include "llvm/Support/Casting.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/Utils/BasicBlockUtils.h" -#include +#include +#include +#include +#include #include +#include +#include + using namespace llvm; #define DEBUG_TYPE "code-extractor" @@ -109,7 +132,6 @@ buildExtractionBlockSet(ArrayRef BBs, DominatorTree *DT) { // Loop over the blocks, adding them to our set-vector, and aborting with an // empty set if we encounter invalid blocks. for (BasicBlock *BB : BBs) { - // If this block is dead, don't process it. if (DT && !DT->isReachableFromEntry(BB)) continue; @@ -140,14 +162,13 @@ CodeExtractor::CodeExtractor(ArrayRef BBs, DominatorTree *DT, bool AggregateArgs, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI) : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), - BPI(BPI), Blocks(buildExtractionBlockSet(BBs, DT)), NumExitBlocks(~0U) {} + BPI(BPI), Blocks(buildExtractionBlockSet(BBs, DT)) {} CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI) : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), - BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks(), &DT)), - NumExitBlocks(~0U) {} + BPI(BPI), Blocks(buildExtractionBlockSet(L.getBlocks(), &DT)) {} /// definedInRegion - Return true if the specified value is defined in the /// extracted region. @@ -202,7 +223,6 @@ bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers( if (Blocks.count(&BB)) continue; for (Instruction &II : BB) { - if (isa(II)) continue; @@ -373,7 +393,6 @@ void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands, // Follow the bitcast. Instruction *MarkerAddr = nullptr; for (User *U : AI->users()) { - if (U->stripInBoundsConstantOffsets() == AI) { SinkLifeStart = false; HoistLifeEnd = false; @@ -407,7 +426,6 @@ void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands, void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, const ValueSet &SinkCands) const { - for (BasicBlock *BB : Blocks) { // If a used value is defined outside the region, it's an input. If an // instruction is used outside the region, it's an output. @@ -457,7 +475,7 @@ void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) { // containing PHI nodes merging values from outside of the region, and a // second that contains all of the code for the block and merges back any // incoming values from inside of the region. - BasicBlock *NewBB = llvm::SplitBlock(Header, Header->getFirstNonPHI(), DT); + BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT); // We only want to code extract the second block now, and it becomes the new // header of the region. @@ -525,7 +543,6 @@ void CodeExtractor::splitReturnBlocks() { /// constructFunction - make a function based on inputs and outputs, as follows: /// f(in0, ..., inN, out0, ..., outN) -/// Function *CodeExtractor::constructFunction(const ValueSet &inputs, const ValueSet &outputs, BasicBlock *header, @@ -544,7 +561,7 @@ Function *CodeExtractor::constructFunction(const ValueSet &inputs, default: RetTy = Type::getInt16Ty(header->getContext()); break; } - std::vector paramTy; + std::vector paramTy; // Add the types of the input values to the function's argument list for (Value *value : inputs) { @@ -620,7 +637,7 @@ Function *CodeExtractor::constructFunction(const ValueSet &inputs, } else RewriteVal = &*AI++; - std::vector Users(inputs[i]->user_begin(), inputs[i]->user_end()); + std::vector Users(inputs[i]->user_begin(), inputs[i]->user_end()); for (User *use : Users) if (Instruction *inst = dyn_cast(use)) if (Blocks.count(inst->getParent())) @@ -639,7 +656,7 @@ Function *CodeExtractor::constructFunction(const ValueSet &inputs, // Rewrite branches to basic blocks outside of the loop to new dummy blocks // within the new function. This must be done before we lose track of which // blocks were originally in the code region. - std::vector Users(header->user_begin(), header->user_end()); + std::vector Users(header->user_begin(), header->user_end()); for (unsigned i = 0, e = Users.size(); i != e; ++i) // The BasicBlock which contains the branch is not in the region // modify the branch target to a new block @@ -659,7 +676,7 @@ emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, ValueSet &inputs, ValueSet &outputs) { // Emit a call to the new function, passing in: *pointer to struct (if // aggregating parameters), or plan inputs and allocated memory for outputs - std::vector params, StructValues, ReloadOutputs, Reloads; + std::vector params, StructValues, ReloadOutputs, Reloads; Module *M = newFunction->getParent(); LLVMContext &Context = M->getContext(); @@ -689,7 +706,7 @@ emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, StructType *StructArgTy = nullptr; AllocaInst *Struct = nullptr; if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { - std::vector ArgTypes; + std::vector ArgTypes; for (ValueSet::iterator v = StructValues.begin(), ve = StructValues.end(); v != ve; ++v) ArgTypes.push_back((*v)->getType()); @@ -741,7 +758,7 @@ emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload"); Reloads.push_back(load); codeReplacer->getInstList().push_back(load); - std::vector Users(outputs[i]->user_begin(), outputs[i]->user_end()); + std::vector Users(outputs[i]->user_begin(), outputs[i]->user_end()); for (unsigned u = 0, e = Users.size(); u != e; ++u) { Instruction *inst = cast(Users[u]); if (!Blocks.count(inst->getParent())) @@ -787,7 +804,7 @@ emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, // over all of the blocks in the extracted region, updating any terminator // instructions in the to-be-extracted region that branch to blocks that are // not in the region to be extracted. - std::map ExitBlockMap; + std::map ExitBlockMap; unsigned switchVal = 0; for (BasicBlock *Block : Blocks) { @@ -823,7 +840,6 @@ emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), SuccNum), OldTarget); - } // rewrite the original branch instruction with this new target @@ -894,8 +910,8 @@ void CodeExtractor::calculateNewCallTerminatorWeights( BasicBlock *CodeReplacer, DenseMap &ExitWeights, BranchProbabilityInfo *BPI) { - typedef BlockFrequencyInfoImplBase::Distribution Distribution; - typedef BlockFrequencyInfoImplBase::BlockNode BlockNode; + using Distribution = BlockFrequencyInfoImplBase::Distribution; + using BlockNode = BlockFrequencyInfoImplBase::BlockNode; // Update the branch weights for the exit block. TerminatorInst *TI = CodeReplacer->getTerminator(); @@ -998,7 +1014,7 @@ Function *CodeExtractor::extractCodeRegion() { } // Calculate the exit blocks for the extracted region and the total exit - // weights for each of those blocks. + // weights for each of those blocks. DenseMap ExitWeights; SmallPtrSet ExitBlocks; for (BasicBlock *Block : Blocks) { @@ -1051,8 +1067,8 @@ Function *CodeExtractor::extractCodeRegion() { // Look at all successors of the codeReplacer block. If any of these blocks // had PHI nodes in them, we need to update the "from" block to be the code // replacer, not the original block in the extracted region. - std::vector Succs(succ_begin(codeReplacer), - succ_end(codeReplacer)); + std::vector Succs(succ_begin(codeReplacer), + succ_end(codeReplacer)); for (unsigned i = 0, e = Succs.size(); i != e; ++i) for (BasicBlock::iterator I = Succs[i]->begin(); isa(I); ++I) { PHINode *PN = cast(I); diff --git a/lib/Transforms/Utils/FunctionComparator.cpp b/lib/Transforms/Utils/FunctionComparator.cpp index 4a2be3a5317..bddcbd86e91 100644 --- a/lib/Transforms/Utils/FunctionComparator.cpp +++ b/lib/Transforms/Utils/FunctionComparator.cpp @@ -13,13 +13,41 @@ //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/FunctionComparator.h" +#include "llvm/ADT/APFloat.h" +#include "llvm/ADT/APInt.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/IR/Attributes.h" +#include "llvm/IR/BasicBlock.h" #include "llvm/IR/CallSite.h" +#include "llvm/IR/Constant.h" +#include "llvm/IR/Constants.h" +#include "llvm/IR/DataLayout.h" +#include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/GlobalValue.h" #include "llvm/IR/InlineAsm.h" +#include "llvm/IR/InstrTypes.h" +#include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" +#include "llvm/IR/LLVMContext.h" +#include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" +#include "llvm/IR/Operator.h" +#include "llvm/IR/Type.h" +#include "llvm/IR/Value.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" +#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" +#include +#include +#include +#include using namespace llvm; @@ -160,7 +188,6 @@ int FunctionComparator::cmpOperandBundlesSchema(const Instruction *L, /// For more details see declaration comments. int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) const { - Type *TyL = L->getType(); Type *TyR = R->getType(); @@ -226,8 +253,8 @@ int FunctionComparator::cmpConstants(const Constant *L, if (!L->isNullValue() && R->isNullValue()) return -1; - auto GlobalValueL = const_cast(dyn_cast(L)); - auto GlobalValueR = const_cast(dyn_cast(R)); + auto GlobalValueL = const_cast(dyn_cast(L)); + auto GlobalValueR = const_cast(dyn_cast(R)); if (GlobalValueL && GlobalValueR) { return cmpGlobalValues(GlobalValueL, GlobalValueR); } @@ -401,10 +428,9 @@ int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const { case Type::TokenTyID: return 0; - case Type::PointerTyID: { + case Type::PointerTyID: assert(PTyL && PTyR && "Both types must be pointers here."); return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace()); - } case Type::StructTyID: { StructType *STyL = cast(TyL); @@ -637,7 +663,6 @@ int FunctionComparator::cmpOperations(const Instruction *L, // Read method declaration comments for more details. int FunctionComparator::cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR) const { - unsigned int ASL = GEPL->getPointerAddressSpace(); unsigned int ASR = GEPR->getPointerAddressSpace(); @@ -869,15 +894,19 @@ namespace { // buffer. class HashAccumulator64 { uint64_t Hash; + public: // Initialize to random constant, so the state isn't zero. HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; } + void add(uint64_t V) { - Hash = llvm::hashing::detail::hash_16_bytes(Hash, V); + Hash = hashing::detail::hash_16_bytes(Hash, V); } + // No finishing is required, because the entire hash value is used. uint64_t getHash() { return Hash; } }; + } // end anonymous namespace // A function hash is calculated by considering only the number of arguments and @@ -919,5 +948,3 @@ FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) { } return H.getHash(); } - - diff --git a/lib/Transforms/Utils/PredicateInfo.cpp b/lib/Transforms/Utils/PredicateInfo.cpp index 16b80923bf5..4002c71fbf3 100644 --- a/lib/Transforms/Utils/PredicateInfo.cpp +++ b/lib/Transforms/Utils/PredicateInfo.cpp @@ -1,61 +1,78 @@ -//===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===// +//===- PredicateInfo.cpp - PredicateInfo Builder --------------------------===// // // 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 PredicateInfo class. // -//===----------------------------------------------------------------===// +//===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/PredicateInfo.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" -#include "llvm/ADT/Statistic.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/Twine.h" #include "llvm/Analysis/AssumptionCache.h" -#include "llvm/Analysis/CFG.h" +#include "llvm/IR/Argument.h" #include "llvm/IR/AssemblyAnnotationWriter.h" -#include "llvm/IR/DataLayout.h" +#include "llvm/IR/BasicBlock.h" #include "llvm/IR/Dominators.h" -#include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" +#include "llvm/IR/InstrTypes.h" +#include "llvm/IR/Instruction.h" +#include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" -#include "llvm/IR/LLVMContext.h" -#include "llvm/IR/Metadata.h" -#include "llvm/IR/Module.h" +#include "llvm/IR/Intrinsics.h" +#include "llvm/IR/PassManager.h" #include "llvm/IR/PatternMatch.h" +#include "llvm/IR/Use.h" +#include "llvm/IR/User.h" +#include "llvm/IR/Value.h" +#include "llvm/Pass.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/DebugCounter.h" +#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" -#include "llvm/Transforms/Scalar.h" +#include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/OrderedInstructions.h" #include -#define DEBUG_TYPE "predicateinfo" +#include +#include +#include +#include + using namespace llvm; using namespace PatternMatch; using namespace llvm::PredicateInfoClasses; +#define DEBUG_TYPE "predicateinfo" + INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo", "PredicateInfo Printer", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo", "PredicateInfo Printer", false, false) + static cl::opt VerifyPredicateInfo( "verify-predicateinfo", cl::init(false), cl::Hidden, cl::desc("Verify PredicateInfo in legacy printer pass.")); + DEBUG_COUNTER(RenameCounter, "predicateinfo-rename", "Controls which variables are renamed with predicateinfo"); -namespace { // Given a predicate info that is a type of branching terminator, get the // branching block. -const BasicBlock *getBranchBlock(const PredicateBase *PB) { +static const BasicBlock *getBranchBlock(const PredicateBase *PB) { assert(isa(PB) && "Only branches and switches should have PHIOnly defs that " "require branch blocks."); @@ -72,17 +89,31 @@ static Instruction *getBranchTerminator(const PredicateBase *PB) { // Given a predicate info that is a type of branching terminator, get the // edge this predicate info represents -const std::pair +static const std::pair getBlockEdge(const PredicateBase *PB) { assert(isa(PB) && "Not a predicate info type we know how to get an edge from."); const auto *PEdge = cast(PB); return std::make_pair(PEdge->From, PEdge->To); } + +// Perform a strict weak ordering on instructions and arguments. +static bool valueComesBefore(OrderedInstructions &OI, const Value *A, + const Value *B) { + auto *ArgA = dyn_cast_or_null(A); + auto *ArgB = dyn_cast_or_null(B); + if (ArgA && !ArgB) + return true; + if (ArgB && !ArgA) + return false; + if (ArgA && ArgB) + return ArgA->getArgNo() < ArgB->getArgNo(); + return OI.dominates(cast(A), cast(B)); } namespace llvm { namespace PredicateInfoClasses { + enum LocalNum { // Operations that must appear first in the block. LN_First, @@ -107,25 +138,12 @@ struct ValueDFS { bool EdgeOnly = false; }; -// Perform a strict weak ordering on instructions and arguments. -static bool valueComesBefore(OrderedInstructions &OI, const Value *A, - const Value *B) { - auto *ArgA = dyn_cast_or_null(A); - auto *ArgB = dyn_cast_or_null(B); - if (ArgA && !ArgB) - return true; - if (ArgB && !ArgA) - return false; - if (ArgA && ArgB) - return ArgA->getArgNo() < ArgB->getArgNo(); - return OI.dominates(cast(A), cast(B)); -} - // This compares ValueDFS structures, creating OrderedBasicBlocks where // necessary to compare uses/defs in the same block. Doing so allows us to walk // the minimum number of instructions necessary to compute our def/use ordering. struct ValueDFS_Compare { OrderedInstructions &OI; + ValueDFS_Compare(OrderedInstructions &OI) : OI(OI) {} bool operator()(const ValueDFS &A, const ValueDFS &B) const { @@ -219,7 +237,8 @@ struct ValueDFS_Compare { } }; -} // namespace PredicateInfoClasses +} // end namespace PredicateInfoClasses +} // end namespace llvm bool PredicateInfo::stackIsInScope(const ValueDFSStack &Stack, const ValueDFS &VDUse) const { @@ -289,7 +308,8 @@ void PredicateInfo::convertUsesToDFSOrdered( // Collect relevant operations from Comparison that we may want to insert copies // for. -void collectCmpOps(CmpInst *Comparison, SmallVectorImpl &CmpOperands) { +static void collectCmpOps(CmpInst *Comparison, + SmallVectorImpl &CmpOperands) { auto *Op0 = Comparison->getOperand(0); auto *Op1 = Comparison->getOperand(1); if (Op0 == Op1) @@ -424,6 +444,7 @@ void PredicateInfo::processBranch(BranchInst *BI, BasicBlock *BranchBB, CmpOperands.clear(); } } + // Process a block terminating switch, and place relevant operations to be // renamed into OpsToRename. void PredicateInfo::processSwitch(SwitchInst *SI, BasicBlock *BranchBB, @@ -697,7 +718,7 @@ PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT, buildPredicateInfo(); } -PredicateInfo::~PredicateInfo() {} +PredicateInfo::~PredicateInfo() = default; void PredicateInfo::verifyPredicateInfo() const {} @@ -739,16 +760,17 @@ PreservedAnalyses PredicateInfoPrinterPass::run(Function &F, /// comments. class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter { friend class PredicateInfo; + const PredicateInfo *PredInfo; public: PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {} - virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, - formatted_raw_ostream &OS) {} + void emitBasicBlockStartAnnot(const BasicBlock *BB, + formatted_raw_ostream &OS) override {} - virtual void emitInstructionAnnot(const Instruction *I, - formatted_raw_ostream &OS) { + void emitInstructionAnnot(const Instruction *I, + formatted_raw_ostream &OS) override { if (const auto *PI = PredInfo->getPredicateInfoFor(I)) { OS << "; Has predicate info\n"; if (const auto *PB = dyn_cast(PI)) { @@ -791,4 +813,3 @@ PreservedAnalyses PredicateInfoVerifierPass::run(Function &F, return PreservedAnalyses::all(); } -} diff --git a/lib/Transforms/Utils/SSAUpdater.cpp b/lib/Transforms/Utils/SSAUpdater.cpp index 6ccf54e49dd..e4b20b0faa1 100644 --- a/lib/Transforms/Utils/SSAUpdater.cpp +++ b/lib/Transforms/Utils/SSAUpdater.cpp @@ -15,7 +15,6 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/StringRef.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/IR/BasicBlock.h" @@ -39,12 +38,13 @@ using namespace llvm; #define DEBUG_TYPE "ssaupdater" -typedef DenseMap AvailableValsTy; +using AvailableValsTy = DenseMap; + static AvailableValsTy &getAvailableVals(void *AV) { return *static_cast(AV); } -SSAUpdater::SSAUpdater(SmallVectorImpl *NewPHI) +SSAUpdater::SSAUpdater(SmallVectorImpl *NewPHI) : InsertedPHIs(NewPHI) {} SSAUpdater::~SSAUpdater() { @@ -72,7 +72,7 @@ void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) { } static bool IsEquivalentPHI(PHINode *PHI, - SmallDenseMap &ValueMapping) { + SmallDenseMap &ValueMapping) { unsigned PHINumValues = PHI->getNumIncomingValues(); if (PHINumValues != ValueMapping.size()) return false; @@ -100,7 +100,7 @@ Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) { // Otherwise, we have the hard case. Get the live-in values for each // predecessor. - SmallVector, 8> PredValues; + SmallVector, 8> PredValues; Value *SingularValue = nullptr; // We can get our predecessor info by walking the pred_iterator list, but it @@ -145,8 +145,8 @@ Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) { // Otherwise, we do need a PHI: check to see if we already have one available // in this block that produces the right value. if (isa(BB->begin())) { - SmallDenseMap ValueMapping(PredValues.begin(), - PredValues.end()); + SmallDenseMap ValueMapping(PredValues.begin(), + PredValues.end()); PHINode *SomePHI; for (BasicBlock::iterator It = BB->begin(); (SomePHI = dyn_cast(It)); ++It) { @@ -218,11 +218,11 @@ namespace llvm { template<> class SSAUpdaterTraits { public: - typedef BasicBlock BlkT; - typedef Value *ValT; - typedef PHINode PhiT; + using BlkT = BasicBlock; + using ValT = Value *; + using PhiT = PHINode; + using BlkSucc_iterator = succ_iterator; - typedef succ_iterator BlkSucc_iterator; static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); } static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); } @@ -253,7 +253,7 @@ public: /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds /// vector, set Info->NumPreds, and allocate space in Info->Preds. static void FindPredecessorBlocks(BasicBlock *BB, - SmallVectorImpl *Preds) { + SmallVectorImpl *Preds) { // We can get our predecessor info by walking the pred_iterator list, // but it is relatively slow. If we already have PHI nodes in this // block, walk one of them to get the predecessor list instead. @@ -293,7 +293,6 @@ public: } /// ValueIsPHI - Check if a value is a PHI. - /// static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) { return dyn_cast(Val); } @@ -333,7 +332,7 @@ Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) { //===----------------------------------------------------------------------===// LoadAndStorePromoter:: -LoadAndStorePromoter(ArrayRef Insts, +LoadAndStorePromoter(ArrayRef Insts, SSAUpdater &S, StringRef BaseName) : SSA(S) { if (Insts.empty()) return; @@ -349,11 +348,11 @@ LoadAndStorePromoter(ArrayRef Insts, } void LoadAndStorePromoter:: -run(const SmallVectorImpl &Insts) const { +run(const SmallVectorImpl &Insts) const { // First step: bucket up uses of the alloca by the block they occur in. // This is important because we have to handle multiple defs/uses in a block // ourselves: SSAUpdater is purely for cross-block references. - DenseMap> UsesByBlock; + DenseMap> UsesByBlock; for (Instruction *User : Insts) UsesByBlock[User->getParent()].push_back(User); @@ -361,12 +360,12 @@ run(const SmallVectorImpl &Insts) const { // Okay, now we can iterate over all the blocks in the function with uses, // processing them. Keep track of which loads are loading a live-in value. // Walk the uses in the use-list order to be determinstic. - SmallVector LiveInLoads; - DenseMap ReplacedLoads; + SmallVector LiveInLoads; + DenseMap ReplacedLoads; for (Instruction *User : Insts) { BasicBlock *BB = User->getParent(); - TinyPtrVector &BlockUses = UsesByBlock[BB]; + TinyPtrVector &BlockUses = UsesByBlock[BB]; // If this block has already been processed, ignore this repeat use. if (BlockUses.empty()) continue; @@ -489,7 +488,7 @@ run(const SmallVectorImpl &Insts) const { bool LoadAndStorePromoter::isInstInList(Instruction *I, - const SmallVectorImpl &Insts) + const SmallVectorImpl &Insts) const { return is_contained(Insts, I); } diff --git a/lib/Transforms/Utils/SymbolRewriter.cpp b/lib/Transforms/Utils/SymbolRewriter.cpp index 20107553665..9da862db6a7 100644 --- a/lib/Transforms/Utils/SymbolRewriter.cpp +++ b/lib/Transforms/Utils/SymbolRewriter.cpp @@ -1,4 +1,4 @@ -//===- SymbolRewriter.cpp - Symbol Rewriter ---------------------*- C++ -*-===// +//===- SymbolRewriter.cpp - Symbol Rewriter -------------------------------===// // // The LLVM Compiler Infrastructure // @@ -57,22 +57,37 @@ // //===----------------------------------------------------------------------===// -#define DEBUG_TYPE "symbol-rewriter" #include "llvm/Transforms/Utils/SymbolRewriter.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" -#include "llvm/IR/LegacyPassManager.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/ilist.h" +#include "llvm/ADT/iterator_range.h" +#include "llvm/IR/Comdat.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/GlobalAlias.h" +#include "llvm/IR/GlobalObject.h" +#include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" #include "llvm/Pass.h" +#include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" -#include "llvm/Support/Debug.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/ErrorOr.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Regex.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/YAMLParser.h" -#include "llvm/Support/raw_ostream.h" +#include +#include +#include using namespace llvm; using namespace SymbolRewriter; +#define DEBUG_TYPE "symbol-rewriter" + static cl::list RewriteMapFiles("rewrite-map-file", cl::desc("Symbol Rewrite Map"), cl::value_desc("filename")); @@ -92,8 +107,9 @@ static void rewriteComdat(Module &M, GlobalObject *GO, } namespace { + template + ValueType *(Module::*Get)(StringRef) const> class ExplicitRewriteDescriptor : public RewriteDescriptor { public: const std::string Source; @@ -110,8 +126,10 @@ public: } }; +} // end anonymous namespace + template + ValueType *(Module::*Get)(StringRef) const> bool ExplicitRewriteDescriptor::performOnModule(Module &M) { bool Changed = false; if (ValueType *S = (M.*Get)(Source)) { @@ -128,10 +146,12 @@ bool ExplicitRewriteDescriptor::performOnModule(Module &M) { return Changed; } +namespace { + template ::iterator> - (llvm::Module::*Iterator)()> + (Module::*Iterator)()> class PatternRewriteDescriptor : public RewriteDescriptor { public: const std::string Pattern; @@ -147,10 +167,12 @@ public: } }; +} // end anonymous namespace + template ::iterator> - (llvm::Module::*Iterator)()> + (Module::*Iterator)()> bool PatternRewriteDescriptor:: performOnModule(Module &M) { bool Changed = false; @@ -178,55 +200,52 @@ performOnModule(Module &M) { return Changed; } +namespace { + /// Represents a rewrite for an explicitly named (function) symbol. Both the /// source function name and target function name of the transformation are /// explicitly spelt out. -typedef ExplicitRewriteDescriptor - ExplicitRewriteFunctionDescriptor; +using ExplicitRewriteFunctionDescriptor = + ExplicitRewriteDescriptor; /// Represents a rewrite for an explicitly named (global variable) symbol. Both /// the source variable name and target variable name are spelt out. This /// applies only to module level variables. -typedef ExplicitRewriteDescriptor - ExplicitRewriteGlobalVariableDescriptor; +using ExplicitRewriteGlobalVariableDescriptor = + ExplicitRewriteDescriptor; /// Represents a rewrite for an explicitly named global alias. Both the source /// and target name are explicitly spelt out. -typedef ExplicitRewriteDescriptor - ExplicitRewriteNamedAliasDescriptor; +using ExplicitRewriteNamedAliasDescriptor = + ExplicitRewriteDescriptor; /// Represents a rewrite for a regular expression based pattern for functions. /// A pattern for the function name is provided and a transformation for that /// pattern to determine the target function name create the rewrite rule. -typedef PatternRewriteDescriptor - PatternRewriteFunctionDescriptor; +using PatternRewriteFunctionDescriptor = + PatternRewriteDescriptor; /// Represents a rewrite for a global variable based upon a matching pattern. /// Each global variable matching the provided pattern will be transformed as /// described in the transformation pattern for the target. Applies only to /// module level variables. -typedef PatternRewriteDescriptor - PatternRewriteGlobalVariableDescriptor; +using PatternRewriteGlobalVariableDescriptor = + PatternRewriteDescriptor; /// PatternRewriteNamedAliasDescriptor - represents a rewrite for global /// aliases which match a given pattern. The provided transformation will be /// applied to each of the matching names. -typedef PatternRewriteDescriptor - PatternRewriteNamedAliasDescriptor; -} // namespace +using PatternRewriteNamedAliasDescriptor = + PatternRewriteDescriptor; + +} // end anonymous namespace bool RewriteMapParser::parse(const std::string &MapFile, RewriteDescriptorList *DL) { @@ -497,6 +516,7 @@ parseRewriteGlobalAliasDescriptor(yaml::Stream &YS, yaml::ScalarNode *K, } namespace { + class RewriteSymbolsLegacyPass : public ModulePass { public: static char ID; // Pass identification, replacement for typeid @@ -510,9 +530,11 @@ private: RewriteSymbolPass Impl; }; +} // end anonymous namespace + char RewriteSymbolsLegacyPass::ID = 0; -RewriteSymbolsLegacyPass::RewriteSymbolsLegacyPass() : ModulePass(ID), Impl() { +RewriteSymbolsLegacyPass::RewriteSymbolsLegacyPass() : ModulePass(ID) { initializeRewriteSymbolsLegacyPassPass(*PassRegistry::getPassRegistry()); } @@ -523,9 +545,7 @@ RewriteSymbolsLegacyPass::RewriteSymbolsLegacyPass( bool RewriteSymbolsLegacyPass::runOnModule(Module &M) { return Impl.runImpl(M); } -} -namespace llvm { PreservedAnalyses RewriteSymbolPass::run(Module &M, ModuleAnalysisManager &AM) { if (!runImpl(M)) return PreservedAnalyses::all(); @@ -550,7 +570,6 @@ void RewriteSymbolPass::loadAndParseMapFiles() { for (const auto &MapFile : MapFiles) Parser.parse(MapFile, &Descriptors); } -} INITIALIZE_PASS(RewriteSymbolsLegacyPass, "rewrite-symbols", "Rewrite Symbols", false, false)