1 //===- llvm/Transforms/HoistPHIConstants.h - Normalize PHI nodes ------------=//
3 // HoistPHIConstants - Remove literal constants that are arguments of PHI nodes
4 // by inserting cast instructions in the preceeding basic blocks, and changing
5 // constant references into references of the casted value.
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/HoistPHIConstants.h"
10 #include "llvm/iPHINode.h"
11 #include "llvm/iOther.h"
12 #include "llvm/BasicBlock.h"
13 #include "llvm/Method.h"
14 #include "llvm/Pass.h"
18 typedef std::pair<BasicBlock *, Value*> BBConstTy;
19 typedef std::map<BBConstTy, CastInst *> CachedCopyMap;
21 static Value *NormalizePhiOperand(PHINode *PN, Value *CPV,
22 BasicBlock *Pred, CachedCopyMap &CopyCache) {
23 // Check if we've already inserted a copy for this constant in Pred
24 // Note that `copyCache[Pred]' will create an empty vector the first time
26 CachedCopyMap::iterator CCI = CopyCache.find(BBConstTy(Pred, CPV));
27 if (CCI != CopyCache.end()) return CCI->second;
29 // Create a copy instruction and add it to the cache...
30 CastInst *Inst = new CastInst(CPV, CPV->getType());
31 CopyCache.insert(std::make_pair(BBConstTy(Pred, CPV), Inst));
33 // Insert the copy just before the terminator inst of the predecessor BB
34 assert(Pred->getTerminator() && "Degenerate BB encountered!");
35 Pred->getInstList().insert(Pred->getInstList().end()-1, Inst);
41 //---------------------------------------------------------------------------
42 // Entry point for normalizing constant args in PHIs
43 //---------------------------------------------------------------------------
45 static bool doHoistPHIConstants(Method *M) {
49 for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
50 std::vector<PHINode*> phis; // normalizing invalidates BB iterator
52 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II) {
53 if (PHINode *PN = dyn_cast<PHINode>(*II))
56 break; // All PHIs occur at top of BB!
59 for (std::vector<PHINode*>::iterator PI=phis.begin(); PI != phis.end();++PI)
60 for (unsigned i = 0; i < (*PI)->getNumIncomingValues(); ++i) {
61 Value *Op = (*PI)->getIncomingValue(i);
63 if (isa<Constant>(Op)) {
64 (*PI)->setIncomingValue(i,
65 NormalizePhiOperand((*PI),
66 (*PI)->getIncomingValue(i),
67 (*PI)->getIncomingBlock(i), Cache));
77 struct HoistPHIConstants : public MethodPass {
78 virtual bool runOnMethod(Method *M) { return doHoistPHIConstants(M); }
82 Pass *createHoistPHIConstantsPass() { return new HoistPHIConstants(); }