Local.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. //===-- Local.h - Functions to perform local transformations ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This family of functions perform various local transformations to the
  11. // program.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
  15. #define LLVM_TRANSFORMS_UTILS_LOCAL_H
  16. #include "llvm/IR/DataLayout.h"
  17. #include "llvm/IR/Dominators.h"
  18. #include "llvm/IR/GetElementPtrTypeIterator.h"
  19. #include "llvm/IR/IRBuilder.h"
  20. #include "llvm/IR/Operator.h"
  21. namespace llvm {
  22. class User;
  23. class BasicBlock;
  24. class Function;
  25. class BranchInst;
  26. class Instruction;
  27. class DbgDeclareInst;
  28. class StoreInst;
  29. class LoadInst;
  30. class Value;
  31. class PHINode;
  32. class AllocaInst;
  33. class AssumptionCache;
  34. class ConstantExpr;
  35. class DataLayout;
  36. class TargetLibraryInfo;
  37. class TargetTransformInfo;
  38. class DIBuilder;
  39. class AliasAnalysis;
  40. class DominatorTree;
  41. template<typename T> class SmallVectorImpl;
  42. //===----------------------------------------------------------------------===//
  43. // Local constant propagation.
  44. //
  45. /// ConstantFoldTerminator - If a terminator instruction is predicated on a
  46. /// constant value, convert it into an unconditional branch to the constant
  47. /// destination. This is a nontrivial operation because the successors of this
  48. /// basic block must have their PHI nodes updated.
  49. /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
  50. /// conditions and indirectbr addresses this might make dead if
  51. /// DeleteDeadConditions is true.
  52. bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions = false,
  53. const TargetLibraryInfo *TLI = nullptr);
  54. //===----------------------------------------------------------------------===//
  55. // Local dead code elimination.
  56. //
  57. /// isInstructionTriviallyDead - Return true if the result produced by the
  58. /// instruction is not used, and the instruction has no side effects.
  59. ///
  60. bool isInstructionTriviallyDead(Instruction *I,
  61. const TargetLibraryInfo *TLI = nullptr);
  62. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  63. /// trivially dead instruction, delete it. If that makes any of its operands
  64. /// trivially dead, delete them too, recursively. Return true if any
  65. /// instructions were deleted.
  66. bool RecursivelyDeleteTriviallyDeadInstructions(Value *V,
  67. const TargetLibraryInfo *TLI = nullptr);
  68. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  69. /// dead PHI node, due to being a def-use chain of single-use nodes that
  70. /// either forms a cycle or is terminated by a trivially dead instruction,
  71. /// delete it. If that makes any of its operands trivially dead, delete them
  72. /// too, recursively. Return true if a change was made.
  73. bool RecursivelyDeleteDeadPHINode(PHINode *PN,
  74. const TargetLibraryInfo *TLI = nullptr);
  75. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  76. /// simplify any instructions in it and recursively delete dead instructions.
  77. ///
  78. /// This returns true if it changed the code, note that it can delete
  79. /// instructions in other blocks as well in this block.
  80. bool SimplifyInstructionsInBlock(BasicBlock *BB,
  81. const TargetLibraryInfo *TLI = nullptr);
  82. // //
  83. ///////////////////////////////////////////////////////////////////////////////
  84. // Control Flow Graph Restructuring.
  85. //
  86. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  87. /// method is called when we're about to delete Pred as a predecessor of BB. If
  88. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  89. ///
  90. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  91. /// nodes that collapse into identity values. For example, if we have:
  92. /// x = phi(1, 0, 0, 0)
  93. /// y = and x, z
  94. ///
  95. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  96. /// recursively fold the 'and' to 0.
  97. void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred);
  98. /// MergeBasicBlockIntoOnlyPred - BB is a block with one predecessor and its
  99. /// predecessor is known to have one successor (BB!). Eliminate the edge
  100. /// between them, moving the instructions in the predecessor into BB. This
  101. /// deletes the predecessor block.
  102. ///
  103. void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DominatorTree *DT = nullptr);
  104. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  105. /// unconditional branch, and contains no instructions other than PHI nodes,
  106. /// potential debug intrinsics and the branch. If possible, eliminate BB by
  107. /// rewriting all the predecessors to branch to the successor block and return
  108. /// true. If we can't transform, return false.
  109. bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB);
  110. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  111. /// nodes in this block. This doesn't try to be clever about PHI nodes
  112. /// which differ only in the order of the incoming values, but instcombine
  113. /// orders them so it usually won't matter.
  114. ///
  115. bool EliminateDuplicatePHINodes(BasicBlock *BB);
  116. /// SimplifyCFG - This function is used to do simplification of a CFG. For
  117. /// example, it adjusts branches to branches to eliminate the extra hop, it
  118. /// eliminates unreachable basic blocks, and does other "peephole" optimization
  119. /// of the CFG. It returns true if a modification was made, possibly deleting
  120. /// the basic block that was pointed to.
  121. ///
  122. bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
  123. unsigned BonusInstThreshold, AssumptionCache *AC = nullptr);
  124. /// FlatternCFG - This function is used to flatten a CFG. For
  125. /// example, it uses parallel-and and parallel-or mode to collapse
  126. // if-conditions and merge if-regions with identical statements.
  127. ///
  128. bool FlattenCFG(BasicBlock *BB, AliasAnalysis *AA = nullptr);
  129. /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
  130. /// and if a predecessor branches to us and one of our successors, fold the
  131. /// setcc into the predecessor and use logical operations to pick the right
  132. /// destination.
  133. bool FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold = 1);
  134. /// DemoteRegToStack - This function takes a virtual register computed by an
  135. /// Instruction and replaces it with a slot in the stack frame, allocated via
  136. /// alloca. This allows the CFG to be changed around without fear of
  137. /// invalidating the SSA information for the value. It returns the pointer to
  138. /// the alloca inserted to create a stack slot for X.
  139. ///
  140. AllocaInst *DemoteRegToStack(Instruction &X,
  141. bool VolatileLoads = false,
  142. Instruction *AllocaPoint = nullptr);
  143. /// DemotePHIToStack - This function takes a virtual register computed by a phi
  144. /// node and replaces it with a slot in the stack frame, allocated via alloca.
  145. /// The phi node is deleted and it returns the pointer to the alloca inserted.
  146. AllocaInst *DemotePHIToStack(PHINode *P, Instruction *AllocaPoint = nullptr);
  147. /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
  148. /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
  149. /// and it is more than the alignment of the ultimate object, see if we can
  150. /// increase the alignment of the ultimate object, making this check succeed.
  151. unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  152. const DataLayout &DL,
  153. const Instruction *CxtI = nullptr,
  154. AssumptionCache *AC = nullptr,
  155. const DominatorTree *DT = nullptr);
  156. /// getKnownAlignment - Try to infer an alignment for the specified pointer.
  157. static inline unsigned getKnownAlignment(Value *V, const DataLayout &DL,
  158. const Instruction *CxtI = nullptr,
  159. AssumptionCache *AC = nullptr,
  160. const DominatorTree *DT = nullptr) {
  161. return getOrEnforceKnownAlignment(V, 0, DL, CxtI, AC, DT);
  162. }
  163. /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
  164. /// code necessary to compute the offset from the base pointer (without adding
  165. /// in the base pointer). Return the result as a signed integer of intptr size.
  166. /// When NoAssumptions is true, no assumptions about index computation not
  167. /// overflowing is made.
  168. template <typename IRBuilderTy>
  169. Value *EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP,
  170. bool NoAssumptions = false) {
  171. GEPOperator *GEPOp = cast<GEPOperator>(GEP);
  172. Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
  173. Value *Result = Constant::getNullValue(IntPtrTy);
  174. // If the GEP is inbounds, we know that none of the addressing operations will
  175. // overflow in an unsigned sense.
  176. bool isInBounds = GEPOp->isInBounds() && !NoAssumptions;
  177. // Build a mask for high order bits.
  178. unsigned IntPtrWidth = IntPtrTy->getScalarType()->getIntegerBitWidth();
  179. uint64_t PtrSizeMask = ~0ULL >> (64 - IntPtrWidth);
  180. gep_type_iterator GTI = gep_type_begin(GEP);
  181. for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
  182. ++i, ++GTI) {
  183. Value *Op = *i;
  184. uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
  185. if (Constant *OpC = dyn_cast<Constant>(Op)) {
  186. if (OpC->isZeroValue())
  187. continue;
  188. // Handle a struct index, which adds its field offset to the pointer.
  189. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  190. if (OpC->getType()->isVectorTy())
  191. OpC = OpC->getSplatValue();
  192. uint64_t OpValue = cast<ConstantInt>(OpC)->getZExtValue();
  193. Size = DL.getStructLayout(STy)->getElementOffset(OpValue);
  194. if (Size)
  195. Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
  196. GEP->getName()+".offs");
  197. continue;
  198. }
  199. Constant *Scale = ConstantInt::get(IntPtrTy, Size);
  200. Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
  201. Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
  202. // Emit an add instruction.
  203. Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
  204. continue;
  205. }
  206. // Convert to correct type.
  207. if (Op->getType() != IntPtrTy)
  208. Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
  209. if (Size != 1) {
  210. // We'll let instcombine(mul) convert this to a shl if possible.
  211. Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
  212. GEP->getName()+".idx", isInBounds /*NUW*/);
  213. }
  214. // Emit an add instruction.
  215. Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
  216. }
  217. return Result;
  218. }
  219. ///===---------------------------------------------------------------------===//
  220. /// Dbg Intrinsic utilities
  221. ///
  222. /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
  223. /// that has an associated llvm.dbg.decl intrinsic.
  224. bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  225. StoreInst *SI, DIBuilder &Builder);
  226. /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
  227. /// that has an associated llvm.dbg.decl intrinsic.
  228. bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  229. LoadInst *LI, DIBuilder &Builder);
  230. /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
  231. /// of llvm.dbg.value intrinsics.
  232. bool LowerDbgDeclare(Function &F);
  233. /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic corresponding to
  234. /// an alloca, if any.
  235. DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
  236. /// \brief Replaces llvm.dbg.declare instruction when an alloca is replaced with
  237. /// a new value. If Deref is true, tan additional DW_OP_deref is prepended to
  238. /// the expression.
  239. bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  240. DIBuilder &Builder, bool Deref);
  241. /// \brief Remove all blocks that can not be reached from the function's entry.
  242. ///
  243. /// Returns true if any basic block was removed.
  244. bool removeUnreachableBlocks(Function &F);
  245. /// \brief Combine the metadata of two instructions so that K can replace J
  246. ///
  247. /// Metadata not listed as known via KnownIDs is removed
  248. void combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs);
  249. /// \brief Replace each use of 'From' with 'To' if that use is dominated by
  250. /// the given edge. Returns the number of replacements made.
  251. unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT,
  252. const BasicBlockEdge &Edge);
  253. } // End llvm namespace
  254. #endif