be3029e545dec3d12c94c9eb3c88cd934f1bb4ab
[oota-llvm.git] / include / llvm / Transforms / Utils / Local.h
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
15 #ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
16 #define LLVM_TRANSFORMS_UTILS_LOCAL_H
17
18 #include "llvm/IRBuilder.h"
19 #include "llvm/Operator.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/DataLayout.h"
22
23 namespace llvm {
24
25 class User;
26 class BasicBlock;
27 class Function;
28 class BranchInst;
29 class Instruction;
30 class DbgDeclareInst;
31 class StoreInst;
32 class LoadInst;
33 class Value;
34 class Pass;
35 class PHINode;
36 class AllocaInst;
37 class ConstantExpr;
38 class DataLayout;
39 class TargetLibraryInfo;
40 class TargetTransformInfo;
41 class DIBuilder;
42
43 template<typename T> class SmallVectorImpl;
44   
45 //===----------------------------------------------------------------------===//
46 //  Local constant propagation.
47 //
48
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);
58
59 //===----------------------------------------------------------------------===//
60 //  Local dead code elimination.
61 //
62
63 /// isInstructionTriviallyDead - Return true if the result produced by the
64 /// instruction is not used, and the instruction has no side effects.
65 ///
66 bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=0);
67
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);
74
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);
81
82   
83 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
84 /// simplify any instructions in it and recursively delete dead instructions.
85 ///
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);
90     
91 //===----------------------------------------------------------------------===//
92 //  Control Flow Graph Restructuring.
93 //
94
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.
98 ///
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)
102 ///   y = and x, z
103 ///
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,
107                                   DataLayout *TD = 0);
108     
109   
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.
114 ///
115 void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P = 0);
116     
117
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);
124
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.
129 ///
130 bool EliminateDuplicatePHINodes(BasicBlock *BB);
131
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.
137 ///
138 bool SimplifyCFG(BasicBlock *BB, const DataLayout *TD = 0,
139                  const TargetTransformInfo *TTI = 0);
140
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
144 /// destination.
145 bool FoldBranchToCommonDest(BranchInst *BI);
146
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.
152 ///
153 AllocaInst *DemoteRegToStack(Instruction &X,
154                              bool VolatileLoads = false,
155                              Instruction *AllocaPoint = 0);
156
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);
161
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);
168
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);
172 }
173
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);
185
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;
189
190   // Build a mask for high order bits.
191   unsigned IntPtrWidth = TD.getPointerSizeInBits();
192   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
193
194   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
195        ++i, ++GTI) {
196     Value *Op = *i;
197     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
198     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
199       if (OpC->isZero()) continue;
200
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());
204
205         if (Size)
206           Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
207                                       GEP->getName()+".offs");
208         continue;
209       }
210
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");
216       continue;
217     }
218     // Convert to correct type.
219     if (Op->getType() != IntPtrTy)
220       Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
221     if (Size != 1) {
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*/);
225     }
226
227     // Emit an add instruction.
228     Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
229   }
230   return Result;
231 }
232
233 ///===---------------------------------------------------------------------===//
234 ///  Dbg Intrinsic utilities
235 ///
236
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);
241
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);
246
247 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
248 /// of llvm.dbg.value intrinsics.
249 bool LowerDbgDeclare(Function &F);
250
251 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic corresponding to
252 /// an alloca, if any.
253 DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
254
255 } // End llvm namespace
256
257 #endif