4b8e9513c823db7fce1d7022dab0226c05c17685
[oota-llvm.git] / lib / Transforms / Scalar / ConstantProp.cpp
1 //===- ConstantProp.cpp - Code to perform Simple Constant Propagation -----===//
2 //
3 // This file implements constant propagation 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 "Support/Statistic.h"
21 #include <set>
22
23 namespace {
24   Statistic<> NumInstKilled("constprop", "Number of instructions killed");
25
26   struct ConstantPropagation : public FunctionPass {
27     bool runOnFunction(Function &F);
28
29     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
30       AU.setPreservesCFG();
31     }
32   };
33
34   RegisterOpt<ConstantPropagation> X("constprop","Simple constant propagation");
35 }
36
37 Pass *createConstantPropagationPass() {
38   return new ConstantPropagation();
39 }
40
41
42 bool ConstantPropagation::runOnFunction(Function &F) {
43   // Initialize the worklist to all of the instructions ready to process...
44   std::set<Instruction*> WorkList(inst_begin(F), inst_end(F));
45   bool Changed = false;
46
47   while (!WorkList.empty()) {
48     Instruction *I = *WorkList.begin();
49     WorkList.erase(WorkList.begin());    // Get an element from the worklist...
50
51     if (!I->use_empty())                 // Don't muck with dead instructions...
52       if (Constant *C = ConstantFoldInstruction(I)) {
53         // Add all of the users of this instruction to the worklist, they might
54         // be constant propagatable now...
55         for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
56              UI != UE; ++UI)
57           WorkList.insert(cast<Instruction>(*UI));
58         
59         // Replace all of the uses of a variable with uses of the constant.
60         I->replaceAllUsesWith(C);
61
62         // We made a change to the function...
63         Changed = true;
64         ++NumInstKilled;
65       }
66   }
67   return Changed;
68 }