ConstantProp.cpp revision 022103b3f33febb7e54b8fdf2c9bc461eea78cba
1//===- ConstantProp.cpp - Code to perform Simple Constant Propogation -----===// 2// 3// This file implements constant propogation and merging: 4// 5// Specifically, this: 6// * Converts instructions like "add int 1, 2" into 3 7// 8// Notice that: 9// * This pass has a habit of making definitions be dead. It is a good idea 10// to to run a DIE pass sometime after running this pass. 11// 12//===----------------------------------------------------------------------===// 13 14#include "llvm/Transforms/Scalar.h" 15#include "llvm/Transforms/Utils/Local.h" 16#include "llvm/ConstantHandling.h" 17#include "llvm/Instruction.h" 18#include "llvm/Pass.h" 19#include "llvm/Support/InstIterator.h" 20#include <set> 21 22namespace { 23 struct ConstantPropogation : public FunctionPass { 24 const char *getPassName() const { return "Simple Constant Propogation"; } 25 26 inline bool runOnFunction(Function *F); 27 28 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 29 AU.preservesCFG(); 30 } 31 }; 32} 33 34Pass *createConstantPropogationPass() { 35 return new ConstantPropogation(); 36} 37 38 39bool ConstantPropogation::runOnFunction(Function *F) { 40 // Initialize the worklist to all of the instructions ready to process... 41 std::set<Instruction*> WorkList(inst_begin(F), inst_end(F)); 42 bool Changed = false; 43 44 while (!WorkList.empty()) { 45 Instruction *I = *WorkList.begin(); 46 WorkList.erase(WorkList.begin()); // Get an element from the worklist... 47 48 if (!I->use_empty()) // Don't muck with dead instructions... 49 if (Constant *C = ConstantFoldInstruction(I)) { 50 // Add all of the users of this instruction to the worklist, they might 51 // be constant propogatable now... 52 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); 53 UI != UE; ++UI) 54 WorkList.insert(cast<Instruction>(*UI)); 55 56 // Replace all of the uses of a variable with uses of the constant. 57 I->replaceAllUsesWith(C); 58 59 // We made a change to the function... 60 Changed = true; 61 } 62 } 63 return Changed; 64} 65