LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Local.h
Go to the documentation of this file.
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/IRBuilder.h"
20 #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 Pass;
35 class PHINode;
36 class AllocaInst;
37 class ConstantExpr;
38 class DataLayout;
39 class TargetLibraryInfo;
40 class TargetTransformInfo;
41 class DIBuilder;
42 class AliasAnalysis;
43 
44 template<typename T> class SmallVectorImpl;
45 
46 //===----------------------------------------------------------------------===//
47 // Local constant propagation.
48 //
49 
50 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
51 /// constant value, convert it into an unconditional branch to the constant
52 /// destination. This is a nontrivial operation because the successors of this
53 /// basic block must have their PHI nodes updated.
54 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
55 /// conditions and indirectbr addresses this might make dead if
56 /// DeleteDeadConditions is true.
57 bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions = false,
58  const TargetLibraryInfo *TLI = 0);
59 
60 //===----------------------------------------------------------------------===//
61 // Local dead code elimination.
62 //
63 
64 /// isInstructionTriviallyDead - Return true if the result produced by the
65 /// instruction is not used, and the instruction has no side effects.
66 ///
67 bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=0);
68 
69 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
70 /// trivially dead instruction, delete it. If that makes any of its operands
71 /// trivially dead, delete them too, recursively. Return true if any
72 /// instructions were deleted.
74  const TargetLibraryInfo *TLI=0);
75 
76 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
77 /// dead PHI node, due to being a def-use chain of single-use nodes that
78 /// either forms a cycle or is terminated by a trivially dead instruction,
79 /// delete it. If that makes any of its operands trivially dead, delete them
80 /// too, recursively. Return true if a change was made.
81 bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=0);
82 
83 
84 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
85 /// simplify any instructions in it and recursively delete dead instructions.
86 ///
87 /// This returns true if it changed the code, note that it can delete
88 /// instructions in other blocks as well in this block.
89 bool SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD = 0,
90  const TargetLibraryInfo *TLI = 0);
91 
92 //===----------------------------------------------------------------------===//
93 // Control Flow Graph Restructuring.
94 //
95 
96 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
97 /// method is called when we're about to delete Pred as a predecessor of BB. If
98 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
99 ///
100 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
101 /// nodes that collapse into identity values. For example, if we have:
102 /// x = phi(1, 0, 0, 0)
103 /// y = and x, z
104 ///
105 /// .. and delete the predecessor corresponding to the '1', this will attempt to
106 /// recursively fold the 'and' to 0.
108  DataLayout *TD = 0);
109 
110 
111 /// MergeBasicBlockIntoOnlyPred - BB is a block with one predecessor and its
112 /// predecessor is known to have one successor (BB!). Eliminate the edge
113 /// between them, moving the instructions in the predecessor into BB. This
114 /// deletes the predecessor block.
115 ///
116 void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P = 0);
117 
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.
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 ///
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  const DataLayout *TD = 0);
141 
142 /// FlatternCFG - This function is used to flatten a CFG. For
143 /// example, it uses parallel-and and parallel-or mode to collapse
144 // if-conditions and merge if-regions with identical statements.
145 ///
146 bool FlattenCFG(BasicBlock *BB, AliasAnalysis *AA = 0);
147 
148 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
149 /// and if a predecessor branches to us and one of our successors, fold the
150 /// setcc into the predecessor and use logical operations to pick the right
151 /// destination.
152 bool FoldBranchToCommonDest(BranchInst *BI);
153 
154 /// DemoteRegToStack - This function takes a virtual register computed by an
155 /// Instruction and replaces it with a slot in the stack frame, allocated via
156 /// alloca. This allows the CFG to be changed around without fear of
157 /// invalidating the SSA information for the value. It returns the pointer to
158 /// the alloca inserted to create a stack slot for X.
159 ///
160 AllocaInst *DemoteRegToStack(Instruction &X,
161  bool VolatileLoads = false,
162  Instruction *AllocaPoint = 0);
163 
164 /// DemotePHIToStack - This function takes a virtual register computed by a phi
165 /// node and replaces it with a slot in the stack frame, allocated via alloca.
166 /// The phi node is deleted and it returns the pointer to the alloca inserted.
167 AllocaInst *DemotePHIToStack(PHINode *P, Instruction *AllocaPoint = 0);
168 
169 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
170 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
171 /// and it is more than the alignment of the ultimate object, see if we can
172 /// increase the alignment of the ultimate object, making this check succeed.
173 unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
174  const DataLayout *TD = 0);
175 
176 /// getKnownAlignment - Try to infer an alignment for the specified pointer.
177 static inline unsigned getKnownAlignment(Value *V, const DataLayout *TD = 0) {
178  return getOrEnforceKnownAlignment(V, 0, TD);
179 }
180 
181 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
182 /// code necessary to compute the offset from the base pointer (without adding
183 /// in the base pointer). Return the result as a signed integer of intptr size.
184 /// When NoAssumptions is true, no assumptions about index computation not
185 /// overflowing is made.
186 template<typename IRBuilderTy>
187 Value *EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &TD, User *GEP,
188  bool NoAssumptions = false) {
189  GEPOperator *GEPOp = cast<GEPOperator>(GEP);
190  Type *IntPtrTy = TD.getIntPtrType(GEP->getType());
191  Value *Result = Constant::getNullValue(IntPtrTy);
192 
193  // If the GEP is inbounds, we know that none of the addressing operations will
194  // overflow in an unsigned sense.
195  bool isInBounds = GEPOp->isInBounds() && !NoAssumptions;
196 
197  // Build a mask for high order bits.
198  unsigned IntPtrWidth = IntPtrTy->getScalarType()->getIntegerBitWidth();
199  uint64_t PtrSizeMask = ~0ULL >> (64 - IntPtrWidth);
200 
202  for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
203  ++i, ++GTI) {
204  Value *Op = *i;
205  uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
206  if (Constant *OpC = dyn_cast<Constant>(Op)) {
207  if (OpC->isZeroValue())
208  continue;
209 
210  // Handle a struct index, which adds its field offset to the pointer.
211  if (StructType *STy = dyn_cast<StructType>(*GTI)) {
212  if (OpC->getType()->isVectorTy())
213  OpC = OpC->getSplatValue();
214 
215  uint64_t OpValue = cast<ConstantInt>(OpC)->getZExtValue();
216  Size = TD.getStructLayout(STy)->getElementOffset(OpValue);
217 
218  if (Size)
219  Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
220  GEP->getName()+".offs");
221  continue;
222  }
223 
224  Constant *Scale = ConstantInt::get(IntPtrTy, Size);
225  Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
226  Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
227  // Emit an add instruction.
228  Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
229  continue;
230  }
231  // Convert to correct type.
232  if (Op->getType() != IntPtrTy)
233  Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
234  if (Size != 1) {
235  // We'll let instcombine(mul) convert this to a shl if possible.
236  Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
237  GEP->getName()+".idx", isInBounds /*NUW*/);
238  }
239 
240  // Emit an add instruction.
241  Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
242  }
243  return Result;
244 }
245 
246 ///===---------------------------------------------------------------------===//
247 /// Dbg Intrinsic utilities
248 ///
249 
250 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
251 /// that has an associated llvm.dbg.decl intrinsic.
252 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
253  StoreInst *SI, DIBuilder &Builder);
254 
255 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
256 /// that has an associated llvm.dbg.decl intrinsic.
257 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
258  LoadInst *LI, DIBuilder &Builder);
259 
260 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
261 /// of llvm.dbg.value intrinsics.
262 bool LowerDbgDeclare(Function &F);
263 
264 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic corresponding to
265 /// an alloca, if any.
266 DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
267 
268 /// replaceDbgDeclareForAlloca - Replaces llvm.dbg.declare instruction when
269 /// alloca is replaced with a new value.
270 bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
271  DIBuilder &Builder);
272 
273 /// \brief Remove all blocks that can not be reached from the function's entry.
274 ///
275 /// Returns true if any basic block was removed.
276 bool removeUnreachableBlocks(Function &F);
277 
278 } // End llvm namespace
279 
280 #endif
bool FlattenCFG(BasicBlock *BB, AliasAnalysis *AA=0)
Definition: FlattenCFG.cpp:484
Various leaf nodes.
Definition: ISDOpcodes.h:60
DbgDeclareInst * FindAllocaDbgDeclare(Value *V)
Definition: Local.cpp:1073
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=0)
Definition: Local.cpp:316
void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P=0)
Definition: Local.cpp:477
void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred, DataLayout *TD=0)
Definition: Local.cpp:445
Value * EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &TD, User *GEP, bool NoAssumptions=false)
Definition: Local.h:187
AllocaInst * DemoteRegToStack(Instruction &X, bool VolatileLoads=false, Instruction *AllocaPoint=0)
F(f)
op_iterator op_begin()
Definition: User.h:116
LoopInfoBase< BlockT, LoopT > * LI
Definition: LoopInfoImpl.h:411
static Constant * getNullValue(Type *Ty)
Definition: Constants.cpp:111
StringRef getName() const
Definition: Value.cpp:167
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:1502
const StructLayout * getStructLayout(StructType *Ty) const
Definition: DataLayout.cpp:445
Definition: Use.h:60
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder)
Definition: Local.cpp:1083
bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=0)
Definition: Local.cpp:373
bool EliminateDuplicatePHINodes(BasicBlock *BB)
Definition: Local.cpp:808
bool SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0)
Definition: Local.cpp:398
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:442
#define P(N)
bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, const DataLayout *TD=0)
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB)
Definition: Local.cpp:725
LLVM Constant Representation.
Definition: Constant.h:41
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=0)
Definition: Local.cpp:266
op_iterator op_end()
Definition: User.h:118
AllocaInst * DemotePHIToStack(PHINode *P, Instruction *AllocaPoint=0)
bool LowerDbgDeclare(Function &F)
Definition: Local.cpp:1034
bool FoldBranchToCommonDest(BranchInst *BI)
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Definition: DataLayout.cpp:610
uint64_t getTypeAllocSize(Type *Ty) const
Definition: DataLayout.h:326
bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, StoreInst *SI, DIBuilder &Builder)
Definition: Local.cpp:971
Type * getType() const
Definition: Value.h:111
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
Definition: Constants.cpp:492
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=0)
Definition: Local.cpp:59
unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, const DataLayout *TD=0)
Definition: Local.cpp:922
bool isInBounds() const
Definition: Operator.h:373
#define I(x, y, z)
Definition: MD5.cpp:54
LLVM Value Representation.
Definition: Value.h:66
bool removeUnreachableBlocks(Function &F)
Remove all blocks that can not be reached from the function's entry.
Definition: Local.cpp:1243
static Constant * getMul(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2051
static RegisterPass< NVPTXAllocaHoisting > X("alloca-hoisting","Hoisting alloca instructions in non-entry ""blocks to the entry block")
INITIALIZE_PASS(GlobalMerge,"global-merge","Global Merge", false, false) bool GlobalMerge const DataLayout * TD
static unsigned getKnownAlignment(Value *V, const DataLayout *TD=0)
getKnownAlignment - Try to infer an alignment for the specified pointer.
Definition: Local.h:177
gep_type_iterator gep_type_begin(const User *GEP)