1 //===- ConstantProp.cpp - Code to perform Simple Constant Propogation -----===//
3 // This file implements constant propogation and merging:
6 // * Converts instructions like "add int 1, 2" into 3
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.
12 //===----------------------------------------------------------------------===//
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"
23 struct ConstantPropogation : public FunctionPass {
24 const char *getPassName() const { return "Simple Constant Propogation"; }
26 inline bool runOnFunction(Function *F);
28 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
34 Pass *createConstantPropogationPass() {
35 return new ConstantPropogation();
39 bool 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));
44 while (!WorkList.empty()) {
45 Instruction *I = *WorkList.begin();
46 WorkList.erase(WorkList.begin()); // Get an element from the worklist...
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();
54 WorkList.insert(cast<Instruction>(*UI));
56 // Replace all of the uses of a variable with uses of the constant.
57 I->replaceAllUsesWith(C);
59 // We made a change to the function...