LLVM API Documentation

IPConstantPropagation.cpp
Go to the documentation of this file.
00001 //===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
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 pass implements an _extremely_ simple interprocedural constant
00011 // propagation pass.  It could certainly be improved in many different ways,
00012 // like using a worklist.  This pass makes arguments dead, but does not remove
00013 // them.  The existing dead argument elimination pass should be run after this
00014 // to clean up the mess.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #define DEBUG_TYPE "ipconstprop"
00019 #include "llvm/Transforms/IPO.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/ValueTracking.h"
00023 #include "llvm/IR/Constants.h"
00024 #include "llvm/IR/Instructions.h"
00025 #include "llvm/IR/Module.h"
00026 #include "llvm/Pass.h"
00027 #include "llvm/Support/CallSite.h"
00028 using namespace llvm;
00029 
00030 STATISTIC(NumArgumentsProped, "Number of args turned into constants");
00031 STATISTIC(NumReturnValProped, "Number of return values turned into constants");
00032 
00033 namespace {
00034   /// IPCP - The interprocedural constant propagation pass
00035   ///
00036   struct IPCP : public ModulePass {
00037     static char ID; // Pass identification, replacement for typeid
00038     IPCP() : ModulePass(ID) {
00039       initializeIPCPPass(*PassRegistry::getPassRegistry());
00040     }
00041 
00042     bool runOnModule(Module &M);
00043   private:
00044     bool PropagateConstantsIntoArguments(Function &F);
00045     bool PropagateConstantReturn(Function &F);
00046   };
00047 }
00048 
00049 char IPCP::ID = 0;
00050 INITIALIZE_PASS(IPCP, "ipconstprop",
00051                 "Interprocedural constant propagation", false, false)
00052 
00053 ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
00054 
00055 bool IPCP::runOnModule(Module &M) {
00056   bool Changed = false;
00057   bool LocalChange = true;
00058 
00059   // FIXME: instead of using smart algorithms, we just iterate until we stop
00060   // making changes.
00061   while (LocalChange) {
00062     LocalChange = false;
00063     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00064       if (!I->isDeclaration()) {
00065         // Delete any klingons.
00066         I->removeDeadConstantUsers();
00067         if (I->hasLocalLinkage())
00068           LocalChange |= PropagateConstantsIntoArguments(*I);
00069         Changed |= PropagateConstantReturn(*I);
00070       }
00071     Changed |= LocalChange;
00072   }
00073   return Changed;
00074 }
00075 
00076 /// PropagateConstantsIntoArguments - Look at all uses of the specified
00077 /// function.  If all uses are direct call sites, and all pass a particular
00078 /// constant in for an argument, propagate that constant in as the argument.
00079 ///
00080 bool IPCP::PropagateConstantsIntoArguments(Function &F) {
00081   if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
00082 
00083   // For each argument, keep track of its constant value and whether it is a
00084   // constant or not.  The bool is driven to true when found to be non-constant.
00085   SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
00086   ArgumentConstants.resize(F.arg_size());
00087 
00088   unsigned NumNonconstant = 0;
00089   for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
00090     User *U = *UI;
00091     // Ignore blockaddress uses.
00092     if (isa<BlockAddress>(U)) continue;
00093     
00094     // Used by a non-instruction, or not the callee of a function, do not
00095     // transform.
00096     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
00097       return false;
00098     
00099     CallSite CS(cast<Instruction>(U));
00100     if (!CS.isCallee(UI))
00101       return false;
00102 
00103     // Check out all of the potentially constant arguments.  Note that we don't
00104     // inspect varargs here.
00105     CallSite::arg_iterator AI = CS.arg_begin();
00106     Function::arg_iterator Arg = F.arg_begin();
00107     for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
00108          ++i, ++AI, ++Arg) {
00109       
00110       // If this argument is known non-constant, ignore it.
00111       if (ArgumentConstants[i].second)
00112         continue;
00113       
00114       Constant *C = dyn_cast<Constant>(*AI);
00115       if (C && ArgumentConstants[i].first == 0) {
00116         ArgumentConstants[i].first = C;   // First constant seen.
00117       } else if (C && ArgumentConstants[i].first == C) {
00118         // Still the constant value we think it is.
00119       } else if (*AI == &*Arg) {
00120         // Ignore recursive calls passing argument down.
00121       } else {
00122         // Argument became non-constant.  If all arguments are non-constant now,
00123         // give up on this function.
00124         if (++NumNonconstant == ArgumentConstants.size())
00125           return false;
00126         ArgumentConstants[i].second = true;
00127       }
00128     }
00129   }
00130 
00131   // If we got to this point, there is a constant argument!
00132   assert(NumNonconstant != ArgumentConstants.size());
00133   bool MadeChange = false;
00134   Function::arg_iterator AI = F.arg_begin();
00135   for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
00136     // Do we have a constant argument?
00137     if (ArgumentConstants[i].second || AI->use_empty() ||
00138         (AI->hasByValAttr() && !F.onlyReadsMemory()))
00139       continue;
00140   
00141     Value *V = ArgumentConstants[i].first;
00142     if (V == 0) V = UndefValue::get(AI->getType());
00143     AI->replaceAllUsesWith(V);
00144     ++NumArgumentsProped;
00145     MadeChange = true;
00146   }
00147   return MadeChange;
00148 }
00149 
00150 
00151 // Check to see if this function returns one or more constants. If so, replace
00152 // all callers that use those return values with the constant value. This will
00153 // leave in the actual return values and instructions, but deadargelim will
00154 // clean that up.
00155 //
00156 // Additionally if a function always returns one of its arguments directly,
00157 // callers will be updated to use the value they pass in directly instead of
00158 // using the return value.
00159 bool IPCP::PropagateConstantReturn(Function &F) {
00160   if (F.getReturnType()->isVoidTy())
00161     return false; // No return value.
00162 
00163   // If this function could be overridden later in the link stage, we can't
00164   // propagate information about its results into callers.
00165   if (F.mayBeOverridden())
00166     return false;
00167     
00168   // Check to see if this function returns a constant.
00169   SmallVector<Value *,4> RetVals;
00170   StructType *STy = dyn_cast<StructType>(F.getReturnType());
00171   if (STy)
00172     for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i) 
00173       RetVals.push_back(UndefValue::get(STy->getElementType(i)));
00174   else
00175     RetVals.push_back(UndefValue::get(F.getReturnType()));
00176 
00177   unsigned NumNonConstant = 0;
00178   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00179     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
00180       for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
00181         // Already found conflicting return values?
00182         Value *RV = RetVals[i];
00183         if (!RV)
00184           continue;
00185 
00186         // Find the returned value
00187         Value *V;
00188         if (!STy)
00189           V = RI->getOperand(0);
00190         else
00191           V = FindInsertedValue(RI->getOperand(0), i);
00192 
00193         if (V) {
00194           // Ignore undefs, we can change them into anything
00195           if (isa<UndefValue>(V))
00196             continue;
00197           
00198           // Try to see if all the rets return the same constant or argument.
00199           if (isa<Constant>(V) || isa<Argument>(V)) {
00200             if (isa<UndefValue>(RV)) {
00201               // No value found yet? Try the current one.
00202               RetVals[i] = V;
00203               continue;
00204             }
00205             // Returning the same value? Good.
00206             if (RV == V)
00207               continue;
00208           }
00209         }
00210         // Different or no known return value? Don't propagate this return
00211         // value.
00212         RetVals[i] = 0;
00213         // All values non constant? Stop looking.
00214         if (++NumNonConstant == RetVals.size())
00215           return false;
00216       }
00217     }
00218 
00219   // If we got here, the function returns at least one constant value.  Loop
00220   // over all users, replacing any uses of the return value with the returned
00221   // constant.
00222   bool MadeChange = false;
00223   for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
00224     CallSite CS(*UI);
00225     Instruction* Call = CS.getInstruction();
00226 
00227     // Not a call instruction or a call instruction that's not calling F
00228     // directly?
00229     if (!Call || !CS.isCallee(UI))
00230       continue;
00231     
00232     // Call result not used?
00233     if (Call->use_empty())
00234       continue;
00235 
00236     MadeChange = true;
00237 
00238     if (STy == 0) {
00239       Value* New = RetVals[0];
00240       if (Argument *A = dyn_cast<Argument>(New))
00241         // Was an argument returned? Then find the corresponding argument in
00242         // the call instruction and use that.
00243         New = CS.getArgument(A->getArgNo());
00244       Call->replaceAllUsesWith(New);
00245       continue;
00246     }
00247    
00248     for (Value::use_iterator I = Call->use_begin(), E = Call->use_end();
00249          I != E;) {
00250       Instruction *Ins = cast<Instruction>(*I);
00251 
00252       // Increment now, so we can remove the use
00253       ++I;
00254 
00255       // Find the index of the retval to replace with
00256       int index = -1;
00257       if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
00258         if (EV->hasIndices())
00259           index = *EV->idx_begin();
00260 
00261       // If this use uses a specific return value, and we have a replacement,
00262       // replace it.
00263       if (index != -1) {
00264         Value *New = RetVals[index];
00265         if (New) {
00266           if (Argument *A = dyn_cast<Argument>(New))
00267             // Was an argument returned? Then find the corresponding argument in
00268             // the call instruction and use that.
00269             New = CS.getArgument(A->getArgNo());
00270           Ins->replaceAllUsesWith(New);
00271           Ins->eraseFromParent();
00272         }
00273       }
00274     }
00275   }
00276 
00277   if (MadeChange) ++NumReturnValProped;
00278   return MadeChange;
00279 }