LLVM API Documentation

Local.h
Go to the documentation of this file.
00001 //===-- Local.h - Functions to perform local transformations ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This family of functions perform various local transformations to the
00011 // program.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
00016 #define LLVM_TRANSFORMS_UTILS_LOCAL_H
00017 
00018 #include "llvm/IR/DataLayout.h"
00019 #include "llvm/IR/GetElementPtrTypeIterator.h"
00020 #include "llvm/IR/IRBuilder.h"
00021 #include "llvm/IR/Operator.h"
00022 
00023 namespace llvm {
00024 
00025 class User;
00026 class BasicBlock;
00027 class Function;
00028 class BranchInst;
00029 class Instruction;
00030 class DbgDeclareInst;
00031 class StoreInst;
00032 class LoadInst;
00033 class Value;
00034 class Pass;
00035 class PHINode;
00036 class AllocaInst;
00037 class ConstantExpr;
00038 class DataLayout;
00039 class TargetLibraryInfo;
00040 class TargetTransformInfo;
00041 class DIBuilder;
00042 class AliasAnalysis;
00043 
00044 template<typename T> class SmallVectorImpl;
00045 
00046 //===----------------------------------------------------------------------===//
00047 //  Local constant propagation.
00048 //
00049 
00050 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
00051 /// constant value, convert it into an unconditional branch to the constant
00052 /// destination.  This is a nontrivial operation because the successors of this
00053 /// basic block must have their PHI nodes updated.
00054 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
00055 /// conditions and indirectbr addresses this might make dead if
00056 /// DeleteDeadConditions is true.
00057 bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions = false,
00058                             const TargetLibraryInfo *TLI = nullptr);
00059 
00060 //===----------------------------------------------------------------------===//
00061 //  Local dead code elimination.
00062 //
00063 
00064 /// isInstructionTriviallyDead - Return true if the result produced by the
00065 /// instruction is not used, and the instruction has no side effects.
00066 ///
00067 bool isInstructionTriviallyDead(Instruction *I,
00068                                 const TargetLibraryInfo *TLI = nullptr);
00069 
00070 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
00071 /// trivially dead instruction, delete it.  If that makes any of its operands
00072 /// trivially dead, delete them too, recursively.  Return true if any
00073 /// instructions were deleted.
00074 bool RecursivelyDeleteTriviallyDeadInstructions(Value *V,
00075                                         const TargetLibraryInfo *TLI = nullptr);
00076 
00077 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
00078 /// dead PHI node, due to being a def-use chain of single-use nodes that
00079 /// either forms a cycle or is terminated by a trivially dead instruction,
00080 /// delete it.  If that makes any of its operands trivially dead, delete them
00081 /// too, recursively.  Return true if a change was made.
00082 bool RecursivelyDeleteDeadPHINode(PHINode *PN,
00083                                   const TargetLibraryInfo *TLI = nullptr);
00084 
00085 
00086 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
00087 /// simplify any instructions in it and recursively delete dead instructions.
00088 ///
00089 /// This returns true if it changed the code, note that it can delete
00090 /// instructions in other blocks as well in this block.
00091 bool SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD = nullptr,
00092                                  const TargetLibraryInfo *TLI = nullptr);
00093 
00094 //===----------------------------------------------------------------------===//
00095 //  Control Flow Graph Restructuring.
00096 //
00097 
00098 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
00099 /// method is called when we're about to delete Pred as a predecessor of BB.  If
00100 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
00101 ///
00102 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
00103 /// nodes that collapse into identity values.  For example, if we have:
00104 ///   x = phi(1, 0, 0, 0)
00105 ///   y = and x, z
00106 ///
00107 /// .. and delete the predecessor corresponding to the '1', this will attempt to
00108 /// recursively fold the 'and' to 0.
00109 void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
00110                                   DataLayout *TD = nullptr);
00111 
00112 
00113 /// MergeBasicBlockIntoOnlyPred - BB is a block with one predecessor and its
00114 /// predecessor is known to have one successor (BB!).  Eliminate the edge
00115 /// between them, moving the instructions in the predecessor into BB.  This
00116 /// deletes the predecessor block.
00117 ///
00118 void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P = nullptr);
00119 
00120 
00121 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
00122 /// unconditional branch, and contains no instructions other than PHI nodes,
00123 /// potential debug intrinsics and the branch.  If possible, eliminate BB by
00124 /// rewriting all the predecessors to branch to the successor block and return
00125 /// true.  If we can't transform, return false.
00126 bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB);
00127 
00128 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
00129 /// nodes in this block. This doesn't try to be clever about PHI nodes
00130 /// which differ only in the order of the incoming values, but instcombine
00131 /// orders them so it usually won't matter.
00132 ///
00133 bool EliminateDuplicatePHINodes(BasicBlock *BB);
00134 
00135 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
00136 /// example, it adjusts branches to branches to eliminate the extra hop, it
00137 /// eliminates unreachable basic blocks, and does other "peephole" optimization
00138 /// of the CFG.  It returns true if a modification was made, possibly deleting
00139 /// the basic block that was pointed to.
00140 ///
00141 bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
00142                  const DataLayout *TD = nullptr);
00143 
00144 /// FlatternCFG - This function is used to flatten a CFG.  For
00145 /// example, it uses parallel-and and parallel-or mode to collapse
00146 //  if-conditions and merge if-regions with identical statements.
00147 ///
00148 bool FlattenCFG(BasicBlock *BB, AliasAnalysis *AA = nullptr);
00149 
00150 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
00151 /// and if a predecessor branches to us and one of our successors, fold the
00152 /// setcc into the predecessor and use logical operations to pick the right
00153 /// destination.
00154 bool FoldBranchToCommonDest(BranchInst *BI);
00155 
00156 /// DemoteRegToStack - This function takes a virtual register computed by an
00157 /// Instruction and replaces it with a slot in the stack frame, allocated via
00158 /// alloca.  This allows the CFG to be changed around without fear of
00159 /// invalidating the SSA information for the value.  It returns the pointer to
00160 /// the alloca inserted to create a stack slot for X.
00161 ///
00162 AllocaInst *DemoteRegToStack(Instruction &X,
00163                              bool VolatileLoads = false,
00164                              Instruction *AllocaPoint = nullptr);
00165 
00166 /// DemotePHIToStack - This function takes a virtual register computed by a phi
00167 /// node and replaces it with a slot in the stack frame, allocated via alloca.
00168 /// The phi node is deleted and it returns the pointer to the alloca inserted.
00169 AllocaInst *DemotePHIToStack(PHINode *P, Instruction *AllocaPoint = nullptr);
00170 
00171 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
00172 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
00173 /// and it is more than the alignment of the ultimate object, see if we can
00174 /// increase the alignment of the ultimate object, making this check succeed.
00175 unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
00176                                     const DataLayout *TD = nullptr);
00177 
00178 /// getKnownAlignment - Try to infer an alignment for the specified pointer.
00179 static inline unsigned getKnownAlignment(Value *V,
00180                                          const DataLayout *TD = nullptr) {
00181   return getOrEnforceKnownAlignment(V, 0, TD);
00182 }
00183 
00184 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
00185 /// code necessary to compute the offset from the base pointer (without adding
00186 /// in the base pointer).  Return the result as a signed integer of intptr size.
00187 /// When NoAssumptions is true, no assumptions about index computation not
00188 /// overflowing is made.
00189 template<typename IRBuilderTy>
00190 Value *EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &TD, User *GEP,
00191                      bool NoAssumptions = false) {
00192   GEPOperator *GEPOp = cast<GEPOperator>(GEP);
00193   Type *IntPtrTy = TD.getIntPtrType(GEP->getType());
00194   Value *Result = Constant::getNullValue(IntPtrTy);
00195 
00196   // If the GEP is inbounds, we know that none of the addressing operations will
00197   // overflow in an unsigned sense.
00198   bool isInBounds = GEPOp->isInBounds() && !NoAssumptions;
00199 
00200   // Build a mask for high order bits.
00201   unsigned IntPtrWidth = IntPtrTy->getScalarType()->getIntegerBitWidth();
00202   uint64_t PtrSizeMask = ~0ULL >> (64 - IntPtrWidth);
00203 
00204   gep_type_iterator GTI = gep_type_begin(GEP);
00205   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
00206        ++i, ++GTI) {
00207     Value *Op = *i;
00208     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
00209     if (Constant *OpC = dyn_cast<Constant>(Op)) {
00210       if (OpC->isZeroValue())
00211         continue;
00212 
00213       // Handle a struct index, which adds its field offset to the pointer.
00214       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00215         if (OpC->getType()->isVectorTy())
00216           OpC = OpC->getSplatValue();
00217 
00218         uint64_t OpValue = cast<ConstantInt>(OpC)->getZExtValue();
00219         Size = TD.getStructLayout(STy)->getElementOffset(OpValue);
00220 
00221         if (Size)
00222           Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
00223                                       GEP->getName()+".offs");
00224         continue;
00225       }
00226 
00227       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
00228       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
00229       Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
00230       // Emit an add instruction.
00231       Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
00232       continue;
00233     }
00234     // Convert to correct type.
00235     if (Op->getType() != IntPtrTy)
00236       Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
00237     if (Size != 1) {
00238       // We'll let instcombine(mul) convert this to a shl if possible.
00239       Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
00240                               GEP->getName()+".idx", isInBounds /*NUW*/);
00241     }
00242 
00243     // Emit an add instruction.
00244     Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
00245   }
00246   return Result;
00247 }
00248 
00249 ///===---------------------------------------------------------------------===//
00250 ///  Dbg Intrinsic utilities
00251 ///
00252 
00253 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
00254 /// that has an associated llvm.dbg.decl intrinsic.
00255 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
00256                                      StoreInst *SI, DIBuilder &Builder);
00257 
00258 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
00259 /// that has an associated llvm.dbg.decl intrinsic.
00260 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
00261                                      LoadInst *LI, DIBuilder &Builder);
00262 
00263 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
00264 /// of llvm.dbg.value intrinsics.
00265 bool LowerDbgDeclare(Function &F);
00266 
00267 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic corresponding to
00268 /// an alloca, if any.
00269 DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
00270 
00271 /// replaceDbgDeclareForAlloca - Replaces llvm.dbg.declare instruction when
00272 /// alloca is replaced with a new value.
00273 bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
00274                                 DIBuilder &Builder);
00275 
00276 /// \brief Remove all blocks that can not be reached from the function's entry.
00277 ///
00278 /// Returns true if any basic block was removed.
00279 bool removeUnreachableBlocks(Function &F);
00280 
00281 } // End llvm namespace
00282 
00283 #endif