1 //===-- Local.h - Functions to perform local transformations ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform various local transformations to the
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
16 #define LLVM_TRANSFORMS_UTILS_LOCAL_H
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/IR/Operator.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 class TargetLibraryInfo;
40 class TargetTransformInfo;
43 template<typename T> class SmallVectorImpl;
45 //===----------------------------------------------------------------------===//
46 // Local constant propagation.
49 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
50 /// constant value, convert it into an unconditional branch to the constant
51 /// destination. This is a nontrivial operation because the successors of this
52 /// basic block must have their PHI nodes updated.
53 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
54 /// conditions and indirectbr addresses this might make dead if
55 /// DeleteDeadConditions is true.
56 bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions = false,
57 const TargetLibraryInfo *TLI = 0);
59 //===----------------------------------------------------------------------===//
60 // Local dead code elimination.
63 /// isInstructionTriviallyDead - Return true if the result produced by the
64 /// instruction is not used, and the instruction has no side effects.
66 bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=0);
68 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
69 /// trivially dead instruction, delete it. If that makes any of its operands
70 /// trivially dead, delete them too, recursively. Return true if any
71 /// instructions were deleted.
72 bool RecursivelyDeleteTriviallyDeadInstructions(Value *V,
73 const TargetLibraryInfo *TLI=0);
75 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
76 /// dead PHI node, due to being a def-use chain of single-use nodes that
77 /// either forms a cycle or is terminated by a trivially dead instruction,
78 /// delete it. If that makes any of its operands trivially dead, delete them
79 /// too, recursively. Return true if a change was made.
80 bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=0);
83 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
84 /// simplify any instructions in it and recursively delete dead instructions.
86 /// This returns true if it changed the code, note that it can delete
87 /// instructions in other blocks as well in this block.
88 bool SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD = 0,
89 const TargetLibraryInfo *TLI = 0);
91 //===----------------------------------------------------------------------===//
92 // Control Flow Graph Restructuring.
95 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
96 /// method is called when we're about to delete Pred as a predecessor of BB. If
97 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
99 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
100 /// nodes that collapse into identity values. For example, if we have:
101 /// x = phi(1, 0, 0, 0)
104 /// .. and delete the predecessor corresponding to the '1', this will attempt to
105 /// recursively fold the 'and' to 0.
106 void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
110 /// MergeBasicBlockIntoOnlyPred - BB is a block with one predecessor and its
111 /// predecessor is known to have one successor (BB!). Eliminate the edge
112 /// between them, moving the instructions in the predecessor into BB. This
113 /// deletes the predecessor block.
115 void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P = 0);
118 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
119 /// unconditional branch, and contains no instructions other than PHI nodes,
120 /// potential debug intrinsics and the branch. If possible, eliminate BB by
121 /// rewriting all the predecessors to branch to the successor block and return
122 /// true. If we can't transform, return false.
123 bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB);
125 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
126 /// nodes in this block. This doesn't try to be clever about PHI nodes
127 /// which differ only in the order of the incoming values, but instcombine
128 /// orders them so it usually won't matter.
130 bool EliminateDuplicatePHINodes(BasicBlock *BB);
132 /// SimplifyCFG - This function is used to do simplification of a CFG. For
133 /// example, it adjusts branches to branches to eliminate the extra hop, it
134 /// eliminates unreachable basic blocks, and does other "peephole" optimization
135 /// of the CFG. It returns true if a modification was made, possibly deleting
136 /// the basic block that was pointed to.
138 bool SimplifyCFG(BasicBlock *BB, const DataLayout *TD = 0,
139 const TargetTransformInfo *TTI = 0);
141 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
142 /// and if a predecessor branches to us and one of our successors, fold the
143 /// setcc into the predecessor and use logical operations to pick the right
145 bool FoldBranchToCommonDest(BranchInst *BI);
147 /// DemoteRegToStack - This function takes a virtual register computed by an
148 /// Instruction and replaces it with a slot in the stack frame, allocated via
149 /// alloca. This allows the CFG to be changed around without fear of
150 /// invalidating the SSA information for the value. It returns the pointer to
151 /// the alloca inserted to create a stack slot for X.
153 AllocaInst *DemoteRegToStack(Instruction &X,
154 bool VolatileLoads = false,
155 Instruction *AllocaPoint = 0);
157 /// DemotePHIToStack - This function takes a virtual register computed by a phi
158 /// node and replaces it with a slot in the stack frame, allocated via alloca.
159 /// The phi node is deleted and it returns the pointer to the alloca inserted.
160 AllocaInst *DemotePHIToStack(PHINode *P, Instruction *AllocaPoint = 0);
162 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
163 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
164 /// and it is more than the alignment of the ultimate object, see if we can
165 /// increase the alignment of the ultimate object, making this check succeed.
166 unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
167 const DataLayout *TD = 0);
169 /// getKnownAlignment - Try to infer an alignment for the specified pointer.
170 static inline unsigned getKnownAlignment(Value *V, const DataLayout *TD = 0) {
171 return getOrEnforceKnownAlignment(V, 0, TD);
174 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
175 /// code necessary to compute the offset from the base pointer (without adding
176 /// in the base pointer). Return the result as a signed integer of intptr size.
177 /// When NoAssumptions is true, no assumptions about index computation not
178 /// overflowing is made.
179 template<typename IRBuilderTy>
180 Value *EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &TD, User *GEP,
181 bool NoAssumptions = false) {
182 gep_type_iterator GTI = gep_type_begin(GEP);
183 Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
184 Value *Result = Constant::getNullValue(IntPtrTy);
186 // If the GEP is inbounds, we know that none of the addressing operations will
187 // overflow in an unsigned sense.
188 bool isInBounds = cast<GEPOperator>(GEP)->isInBounds() && !NoAssumptions;
190 // Build a mask for high order bits.
191 unsigned IntPtrWidth = TD.getPointerSizeInBits();
192 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
194 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
197 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
198 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
199 if (OpC->isZero()) continue;
201 // Handle a struct index, which adds its field offset to the pointer.
202 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
203 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
206 Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
207 GEP->getName()+".offs");
211 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
212 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
213 Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
214 // Emit an add instruction.
215 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
218 // Convert to correct type.
219 if (Op->getType() != IntPtrTy)
220 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
222 // We'll let instcombine(mul) convert this to a shl if possible.
223 Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
224 GEP->getName()+".idx", isInBounds /*NUW*/);
227 // Emit an add instruction.
228 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
233 ///===---------------------------------------------------------------------===//
234 /// Dbg Intrinsic utilities
237 /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
238 /// that has an associated llvm.dbg.decl intrinsic.
239 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
240 StoreInst *SI, DIBuilder &Builder);
242 /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
243 /// that has an associated llvm.dbg.decl intrinsic.
244 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
245 LoadInst *LI, DIBuilder &Builder);
247 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
248 /// of llvm.dbg.value intrinsics.
249 bool LowerDbgDeclare(Function &F);
251 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic corresponding to
252 /// an alloca, if any.
253 DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
255 /// replaceDbgDeclareForAlloca - Replaces llvm.dbg.declare instruction when
256 /// alloca is replaced with a new value.
257 bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
260 /// \brief Remove all blocks that can not be reached from the function's entry.
262 /// Returns true if any basic block was removed.
263 bool removeUnreachableBlocks(Function &F);
265 } // End llvm namespace