ConstantProp.cpp revision a6275ccdf5e1aa208afde56c498e2b13e16442f0
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 "Support/StatisticReporter.h"
21#include <set>
22
23static Statistic<> NumInstKilled("constprop - Number of instructions killed");
24
25namespace {
26  struct ConstantPropogation : public FunctionPass {
27    bool runOnFunction(Function &F);
28
29    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
30      AU.preservesCFG();
31    }
32  };
33
34  RegisterOpt<ConstantPropogation> X("constprop","Simple constant propogation");
35}
36
37Pass *createConstantPropogationPass() {
38  return new ConstantPropogation();
39}
40
41
42bool ConstantPropogation::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 propogatable 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}
69