Updates to move some header files out of include/llvm/Transforms into
[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/DecomposeMultiDimRefs.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
19 namespace {
20   struct DecomposePass : public BasicBlockPass {
21     const char *getPassName() const { return "Decompose Subscripting Exps"; }
22
23     virtual bool runOnBasicBlock(BasicBlock *BB);
24
25   private:
26     static void decomposeArrayRef(BasicBlock::iterator &BBI);
27   };
28 }
29
30 Pass *createDecomposeMultiDimRefsPass() {
31   return new DecomposePass();
32 }
33
34
35 // runOnBasicBlock - Entry point for array or structure references with multiple
36 // indices.
37 //
38 bool DecomposePass::runOnBasicBlock(BasicBlock *BB) {
39   bool Changed = false;
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 *MAI = cast<MemAccessInst>(*BBI);
68   BasicBlock *BB = MAI->getParent();
69   Value *LastPtr = MAI->getPointerOperand();
70
71   // Remove the instruction from the stream
72   BB->getInstList().remove(BBI);
73
74   vector<Instruction*> NewInsts;
75   
76   // Process each index except the last one.
77   // 
78   User::const_op_iterator OI = MAI->idx_begin(), OE = MAI->idx_end();
79   for (; 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<Constant>(*OI) && 
85                        cast<Constant>(*OI)->isNullValue() &&
86                        (*OI)->getType() == Type::UIntTy;
87       
88     // Extract the first index.  If the ptr is a pointer to a structure
89     // and the next index is a structure offset (i.e., not an array offset), 
90     // we need to include an initial [0] to index into the pointer.
91     //
92     vector<Value*> Indices;
93     PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
94     if (isa<StructType>(PtrTy->getElementType())
95         && !PtrTy->indexValid(*OI))
96       Indices.push_back(Constant::getNullValue(Type::UIntTy));
97     Indices.push_back(*OI);
98
99     // Get the type obtained by applying the first index.
100     // It must be a structure or array.
101     const Type *NextTy = MemAccessInst::getIndexedType(LastPtr->getType(),
102                                                        Indices, true);
103     assert(isa<CompositeType>(NextTy));
104     
105     // Get a pointer to the structure or to the elements of the array.
106     const Type *NextPtrTy =
107       PointerType::get(isa<StructType>(NextTy) ? NextTy
108                        : cast<ArrayType>(NextTy)->getElementType());
109       
110     // Instruction 1: nextPtr1 = GetElementPtr LastPtr, Indices
111     // This is not needed if the index is zero.
112     if (!indexIsZero) {
113       LastPtr = new GetElementPtrInst(LastPtr, Indices, "ptr1");
114       NewInsts.push_back(cast<Instruction>(LastPtr));
115     }
116       
117     // Instruction 2: nextPtr2 = cast nextPtr1 to NextPtrTy
118     // This is not needed if the two types are identical.
119     //
120     if (LastPtr->getType() != NextPtrTy) {
121       LastPtr = new CastInst(LastPtr, NextPtrTy, "ptr2");
122       NewInsts.push_back(cast<Instruction>(LastPtr));
123     }
124   }
125   
126   // 
127   // Now create a new instruction to replace the original one
128   //
129   PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
130
131   // First, get the final index vector.  As above, we may need an initial [0].
132   vector<Value*> Indices;
133   if (isa<StructType>(PtrTy->getElementType())
134       && !PtrTy->indexValid(*OI))
135     Indices.push_back(Constant::getNullValue(Type::UIntTy));
136
137   Indices.push_back(*OI);
138
139   Instruction *NewI = 0;
140   switch(MAI->getOpcode()) {
141   case Instruction::Load:
142     NewI = new LoadInst(LastPtr, Indices, MAI->getName());
143     break;
144   case Instruction::Store:
145     NewI = new StoreInst(MAI->getOperand(0), LastPtr, Indices);
146     break;
147   case Instruction::GetElementPtr:
148     NewI = new GetElementPtrInst(LastPtr, Indices, MAI->getName());
149     break;
150   default:
151     assert(0 && "Unrecognized memory access instruction");
152   }
153   NewInsts.push_back(NewI);
154   
155   // Replace all uses of the old instruction with the new
156   MAI->replaceAllUsesWith(NewI);
157
158   // Now delete the old instruction...
159   delete MAI;
160
161   // Insert all of the new instructions...
162   BBI = BB->getInstList().insert(BBI, NewInsts.begin(), NewInsts.end());
163   
164   // Advance the iterator to the instruction following the one just inserted...
165   BBI += NewInsts.size();
166 }