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