Fix bug: test/Regression/Transforms/InstCombine/2002-05-14-TouchDeletedInst.ll
[oota-llvm.git] / lib / Transforms / Scalar / DecomposeMultiDimRefs.cpp
1 //===- llvm/Transforms/DecomposeMultiDimRefs.cpp - Lower array refs to 1D -===//
2 //
3 // DecomposeMultiDimRefs - Convert multi-dimensional references consisting of
4 // any combination of 2 or more array and structure indices into a sequence of
5 // instructions (using getelementpr and cast) so that each instruction has at
6 // most one index (except structure references, which need an extra leading
7 // index of [0]).
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "llvm/Transforms/Scalar.h"
12 #include "llvm/DerivedTypes.h"
13 #include "llvm/Constant.h"
14 #include "llvm/iMemory.h"
15 #include "llvm/iOther.h"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/Pass.h"
18 #include "Support/StatisticReporter.h"
19
20 static Statistic<> NumAdded("lowerrefs\t\t- New instructions added");
21
22 namespace {
23   struct DecomposePass : public BasicBlockPass {
24     const char *getPassName() const { return "Decompose Subscripting Exps"; }
25
26     virtual bool runOnBasicBlock(BasicBlock *BB);
27
28   private:
29     static void decomposeArrayRef(BasicBlock::iterator &BBI);
30   };
31 }
32
33 Pass *createDecomposeMultiDimRefsPass() {
34   return new DecomposePass();
35 }
36
37
38 // runOnBasicBlock - Entry point for array or structure references with multiple
39 // indices.
40 //
41 bool DecomposePass::runOnBasicBlock(BasicBlock *BB) {
42   bool Changed = false;
43   for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ) {
44     if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*II)) {
45       if (MAI->getNumOperands() > MAI->getFirstIndexOperandNumber()+1) {
46         decomposeArrayRef(II);
47         Changed = true;
48       } else {
49         ++II;
50       }
51     } else {
52       ++II;
53     }
54   }
55   
56   return Changed;
57 }
58
59 // 
60 // For any combination of 2 or more array and structure indices,
61 // this function repeats the foll. until we have a one-dim. reference: {
62 //      ptr1 = getElementPtr [CompositeType-N] * lastPtr, uint firstIndex
63 //      ptr2 = cast [CompositeType-N] * ptr1 to [CompositeType-N] *
64 // }
65 // Then it replaces the original instruction with an equivalent one that
66 // uses the last ptr2 generated in the loop and a single index.
67 // If any index is (uint) 0, we omit the getElementPtr instruction.
68 // 
69 void DecomposePass::decomposeArrayRef(BasicBlock::iterator &BBI) {
70   MemAccessInst *MAI = cast<MemAccessInst>(*BBI);
71   BasicBlock *BB = MAI->getParent();
72   Value *LastPtr = MAI->getPointerOperand();
73
74   // Remove the instruction from the stream
75   BB->getInstList().remove(BBI);
76
77   vector<Instruction*> NewInsts;
78   
79   // Process each index except the last one.
80   // 
81   User::const_op_iterator OI = MAI->idx_begin(), OE = MAI->idx_end();
82   for (; OI+1 != OE; ++OI) {
83     assert(isa<PointerType>(LastPtr->getType()));
84       
85     // Check for a zero index.  This will need a cast instead of
86     // a getElementPtr, or it may need neither.
87     bool indexIsZero = isa<Constant>(*OI) && 
88                        cast<Constant>(*OI)->isNullValue() &&
89                        (*OI)->getType() == Type::UIntTy;
90       
91     // Extract the first index.  If the ptr is a pointer to a structure
92     // and the next index is a structure offset (i.e., not an array offset), 
93     // we need to include an initial [0] to index into the pointer.
94     //
95     vector<Value*> Indices;
96     PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
97     if (isa<StructType>(PtrTy->getElementType())
98         && !PtrTy->indexValid(*OI))
99       Indices.push_back(Constant::getNullValue(Type::UIntTy));
100     Indices.push_back(*OI);
101
102     // Get the type obtained by applying the first index.
103     // It must be a structure or array.
104     const Type *NextTy = MemAccessInst::getIndexedType(LastPtr->getType(),
105                                                        Indices, true);
106     assert(isa<CompositeType>(NextTy));
107     
108     // Get a pointer to the structure or to the elements of the array.
109     const Type *NextPtrTy =
110       PointerType::get(isa<StructType>(NextTy) ? NextTy
111                        : cast<ArrayType>(NextTy)->getElementType());
112       
113     // Instruction 1: nextPtr1 = GetElementPtr LastPtr, Indices
114     // This is not needed if the index is zero.
115     if (!indexIsZero) {
116       LastPtr = new GetElementPtrInst(LastPtr, Indices, "ptr1");
117       NewInsts.push_back(cast<Instruction>(LastPtr));
118       ++NumAdded;
119     }
120       
121     // Instruction 2: nextPtr2 = cast nextPtr1 to NextPtrTy
122     // This is not needed if the two types are identical.
123     //
124     if (LastPtr->getType() != NextPtrTy) {
125       LastPtr = new CastInst(LastPtr, NextPtrTy, "ptr2");
126       NewInsts.push_back(cast<Instruction>(LastPtr));
127       ++NumAdded;
128     }
129   }
130   
131   // 
132   // Now create a new instruction to replace the original one
133   //
134   PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
135
136   // First, get the final index vector.  As above, we may need an initial [0].
137   vector<Value*> Indices;
138   if (isa<StructType>(PtrTy->getElementType())
139       && !PtrTy->indexValid(*OI))
140     Indices.push_back(Constant::getNullValue(Type::UIntTy));
141
142   Indices.push_back(*OI);
143
144   Instruction *NewI = 0;
145   switch(MAI->getOpcode()) {
146   case Instruction::Load:
147     NewI = new LoadInst(LastPtr, Indices, MAI->getName());
148     break;
149   case Instruction::Store:
150     NewI = new StoreInst(MAI->getOperand(0), LastPtr, Indices);
151     break;
152   case Instruction::GetElementPtr:
153     NewI = new GetElementPtrInst(LastPtr, Indices, MAI->getName());
154     break;
155   default:
156     assert(0 && "Unrecognized memory access instruction");
157   }
158   NewInsts.push_back(NewI);
159   
160   // Replace all uses of the old instruction with the new
161   MAI->replaceAllUsesWith(NewI);
162
163   // Now delete the old instruction...
164   delete MAI;
165
166   // Insert all of the new instructions...
167   BBI = BB->getInstList().insert(BBI, NewInsts.begin(), NewInsts.end());
168   
169   // Advance the iterator to the instruction following the one just inserted...
170   BBI += NewInsts.size();
171 }