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