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/IRBuilder.h"
19 #include "llvm/Operator.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/Target/TargetData.h"
41 template<typename T> class SmallVectorImpl;
43 //===----------------------------------------------------------------------===//
44 // Local constant propagation.
47 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
48 /// constant value, convert it into an unconditional branch to the constant
49 /// destination. This is a nontrivial operation because the successors of this
50 /// basic block must have their PHI nodes updated.
51 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
52 /// conditions and indirectbr addresses this might make dead if
53 /// DeleteDeadConditions is true.
54 bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions = false);
56 //===----------------------------------------------------------------------===//
57 // Local dead code elimination.
60 /// isInstructionTriviallyDead - Return true if the result produced by the
61 /// instruction is not used, and the instruction has no side effects.
63 bool isInstructionTriviallyDead(Instruction *I);
65 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
66 /// trivially dead instruction, delete it. If that makes any of its operands
67 /// trivially dead, delete them too, recursively. Return true if any
68 /// instructions were deleted.
69 bool RecursivelyDeleteTriviallyDeadInstructions(Value *V);
71 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
72 /// dead PHI node, due to being a def-use chain of single-use nodes that
73 /// either forms a cycle or is terminated by a trivially dead instruction,
74 /// delete it. If that makes any of its operands trivially dead, delete them
75 /// too, recursively. Return true if a change was made.
76 bool RecursivelyDeleteDeadPHINode(PHINode *PN);
79 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
80 /// simplify any instructions in it and recursively delete dead instructions.
82 /// This returns true if it changed the code, note that it can delete
83 /// instructions in other blocks as well in this block.
84 bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD = 0);
86 //===----------------------------------------------------------------------===//
87 // Control Flow Graph Restructuring.
90 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
91 /// method is called when we're about to delete Pred as a predecessor of BB. If
92 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
94 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
95 /// nodes that collapse into identity values. For example, if we have:
96 /// x = phi(1, 0, 0, 0)
99 /// .. and delete the predecessor corresponding to the '1', this will attempt to
100 /// recursively fold the 'and' to 0.
101 void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
105 /// MergeBasicBlockIntoOnlyPred - BB is a block with one predecessor and its
106 /// predecessor is known to have one successor (BB!). Eliminate the edge
107 /// between them, moving the instructions in the predecessor into BB. This
108 /// deletes the predecessor block.
110 void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P = 0);
113 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
114 /// unconditional branch, and contains no instructions other than PHI nodes,
115 /// potential debug intrinsics and the branch. If possible, eliminate BB by
116 /// rewriting all the predecessors to branch to the successor block and return
117 /// true. If we can't transform, return false.
118 bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB);
120 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
121 /// nodes in this block. This doesn't try to be clever about PHI nodes
122 /// which differ only in the order of the incoming values, but instcombine
123 /// orders them so it usually won't matter.
125 bool EliminateDuplicatePHINodes(BasicBlock *BB);
127 /// SimplifyCFG - This function is used to do simplification of a CFG. For
128 /// example, it adjusts branches to branches to eliminate the extra hop, it
129 /// eliminates unreachable basic blocks, and does other "peephole" optimization
130 /// of the CFG. It returns true if a modification was made, possibly deleting
131 /// the basic block that was pointed to.
133 bool SimplifyCFG(BasicBlock *BB, const TargetData *TD = 0);
135 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
136 /// and if a predecessor branches to us and one of our successors, fold the
137 /// setcc into the predecessor and use logical operations to pick the right
139 bool FoldBranchToCommonDest(BranchInst *BI);
141 /// DemoteRegToStack - This function takes a virtual register computed by an
142 /// Instruction and replaces it with a slot in the stack frame, allocated via
143 /// alloca. This allows the CFG to be changed around without fear of
144 /// invalidating the SSA information for the value. It returns the pointer to
145 /// the alloca inserted to create a stack slot for X.
147 AllocaInst *DemoteRegToStack(Instruction &X,
148 bool VolatileLoads = false,
149 Instruction *AllocaPoint = 0);
151 /// DemotePHIToStack - This function takes a virtual register computed by a phi
152 /// node and replaces it with a slot in the stack frame, allocated via alloca.
153 /// The phi node is deleted and it returns the pointer to the alloca inserted.
154 AllocaInst *DemotePHIToStack(PHINode *P, Instruction *AllocaPoint = 0);
156 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
157 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
158 /// and it is more than the alignment of the ultimate object, see if we can
159 /// increase the alignment of the ultimate object, making this check succeed.
160 unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
161 const TargetData *TD = 0);
163 /// getKnownAlignment - Try to infer an alignment for the specified pointer.
164 static inline unsigned getKnownAlignment(Value *V, const TargetData *TD = 0) {
165 return getOrEnforceKnownAlignment(V, 0, TD);
168 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
169 /// code necessary to compute the offset from the base pointer (without adding
170 /// in the base pointer). Return the result as a signed integer of intptr size.
171 template<typename IRBuilderTy>
172 Value *EmitGEPOffset(IRBuilderTy *Builder, const TargetData &TD, User *GEP) {
173 gep_type_iterator GTI = gep_type_begin(GEP);
174 Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
175 Value *Result = Constant::getNullValue(IntPtrTy);
177 // If the GEP is inbounds, we know that none of the addressing operations will
178 // overflow in an unsigned sense.
179 bool isInBounds = cast<GEPOperator>(GEP)->isInBounds();
181 // Build a mask for high order bits.
182 unsigned IntPtrWidth = TD.getPointerSizeInBits();
183 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
185 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
188 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
189 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
190 if (OpC->isZero()) continue;
192 // Handle a struct index, which adds its field offset to the pointer.
193 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
194 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
197 Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
198 GEP->getName()+".offs");
202 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
203 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
204 Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
205 // Emit an add instruction.
206 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
209 // Convert to correct type.
210 if (Op->getType() != IntPtrTy)
211 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
213 // We'll let instcombine(mul) convert this to a shl if possible.
214 Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
215 GEP->getName()+".idx", isInBounds /*NUW*/);
218 // Emit an add instruction.
219 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
224 ///===---------------------------------------------------------------------===//
225 /// Dbg Intrinsic utilities
228 /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
229 /// that has an associated llvm.dbg.decl intrinsic.
230 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
231 StoreInst *SI, DIBuilder &Builder);
233 /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
234 /// that has an associated llvm.dbg.decl intrinsic.
235 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
236 LoadInst *LI, DIBuilder &Builder);
238 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
239 /// of llvm.dbg.value intrinsics.
240 bool LowerDbgDeclare(Function &F);
242 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic corresponding to
243 /// an alloca, if any.
244 DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
246 } // End llvm namespace