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