Add cannonicalization of shl X, 1 -> add X, X
[oota-llvm.git] / lib / Transforms / Scalar / DecomposeMultiDimRefs.cpp
index f4bb51a02d1fbac66a7a64d1a03c6a8fd3183731..a6d7e37cdb6f34235480d70ee9aab35059cbe797 100644 (file)
@@ -1,32 +1,39 @@
 //===- llvm/Transforms/DecomposeMultiDimRefs.cpp - Lower array refs to 1D -===//
 //
-// DecomposeMultiDimRefs - 
-// Convert multi-dimensional references consisting of any combination
-// of 2 or more array and structure indices into a sequence of
-// instructions (using getelementpr and cast) so that each instruction
-// has at most one index (except structure references,
-// which need an extra leading index of [0]).
+// DecomposeMultiDimRefs - Convert multi-dimensional references consisting of
+// any combination of 2 or more array and structure indices into a sequence of
+// instructions (using getelementpr and cast) so that each instruction has at
+// most one index (except structure references, which need an extra leading
+// index of [0]).
 //
 //===----------------------------------------------------------------------===//
 
-#include "llvm/Transforms/Scalar/DecomposeMultiDimRefs.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/DerivedTypes.h"
 #include "llvm/Constants.h"
+#include "llvm/Constant.h"
 #include "llvm/iMemory.h"
 #include "llvm/iOther.h"
 #include "llvm/BasicBlock.h"
-#include "llvm/Function.h"
 #include "llvm/Pass.h"
+#include "Support/StatisticReporter.h"
 
 namespace {
-  struct DecomposePass : public BasicBlockPass {
-    virtual bool runOnBasicBlock(BasicBlock *BB);
+  Statistic<> NumAdded("lowerrefs\t\t- # of getelementptr instructions added");
 
-  private:
-    static void decomposeArrayRef(BasicBlock::iterator &BBI);
+  class DecomposePass : public BasicBlockPass {
+    static bool decomposeArrayRef(GetElementPtrInst &GEP);
+  public:
+    virtual bool runOnBasicBlock(BasicBlock &BB);
   };
+
+  RegisterOpt<DecomposePass> X("lowerrefs", "Decompose multi-dimensional "
+                               "structure/array references");
 }
 
-Pass *createDecomposeMultiDimRefsPass() {
+Pass
+*createDecomposeMultiDimRefsPass()
+{
   return new DecomposePass();
 }
 
@@ -34,138 +41,85 @@ Pass *createDecomposeMultiDimRefsPass() {
 // runOnBasicBlock - Entry point for array or structure references with multiple
 // indices.
 //
-bool DecomposePass::runOnBasicBlock(BasicBlock *BB) {
+bool
+DecomposePass::runOnBasicBlock(BasicBlock &BB)
+{
   bool Changed = false;
-  
-  for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ) {
-    if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*II)) {
-      if (MAI->getNumOperands() > MAI->getFirstIndexOperandNumber()+1) {
-        decomposeArrayRef(II);
-        Changed = true;
-      } else {
-        ++II;
-      }
-    } else {
-      ++II;
-    }
+  for (BasicBlock::iterator II = BB.begin(); II != BB.end(); ) {
+    Instruction *I = II;
+    ++II;
+    if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
+      if (GEP->getNumIndices() >= 2)
+        Changed |= decomposeArrayRef(*GEP); // always modifies II
   }
-  
   return Changed;
 }
 
+// For any GetElementPtrInst with 2 or more array and structure indices:
 // 
-// For any combination of 2 or more array and structure indices,
-// this function repeats the foll. until we have a one-dim. reference: {
-//      ptr1 = getElementPtr [CompositeType-N] * lastPtr, uint firstIndex
-//      ptr2 = cast [CompositeType-N] * ptr1 to [CompositeType-N] *
-// }
-// Then it replaces the original instruction with an equivalent one that
-// uses the last ptr2 generated in the loop and a single index.
-// If any index is (uint) 0, we omit the getElementPtr instruction.
+//      opCode CompositeType* P, [uint|ubyte] idx1, ..., [uint|ubyte] idxN
 // 
-void DecomposePass::decomposeArrayRef(BasicBlock::iterator &BBI){
-  MemAccessInst *memI = cast<MemAccessInst>(*BBI);
-  BasicBlock* BB = memI->getParent();
-  Value* lastPtr = memI->getPointerOperand();
-
-  // Remove the instruction from the stream
-  BB->getInstList().remove(BBI);
+// this function generates the foll sequence:
+// 
+//      ptr1   = getElementPtr P,         idx1
+//      ptr2   = getElementPtr ptr1,   0, idx2
+//      ...
+//      ptrN-1 = getElementPtr ptrN-2, 0, idxN-1
+//      opCode                 ptrN-1, 0, idxN  // New-MAI
+// 
+// Then it replaces the original instruction with this sequence,
+// and replaces all uses of the original instruction with New-MAI.
+// If idx1 is 0, we simply omit the first getElementPtr instruction.
+// 
+// On return: BBI points to the instruction after the current one
+//            (whether or not *BBI was replaced).
+// 
+// Return value: true if the instruction was replaced; false otherwise.
+// 
+bool
+DecomposePass::decomposeArrayRef(GetElementPtrInst &GEP)
+{
+  BasicBlock *BB = GEP.getParent();
+  Value *LastPtr = GEP.getPointerOperand();
+  Instruction *InsertPoint = GEP.getNext(); // Insert before the next insn
 
-  vector<Instruction*> newIvec;
-  
   // Process each index except the last one.
-  // 
-  User::const_op_iterator OI = memI->idx_begin(), OE = memI->idx_end();
-  for (; OI != OE && OI+1 != OE; ++OI) {
-    assert(isa<PointerType>(lastPtr->getType()));
-      
-    // Check for a zero index.  This will need a cast instead of
-    // a getElementPtr, or it may need neither.
-    bool indexIsZero = isa<ConstantUInt>(*OI) && 
-                       cast<Constant>(*OI)->isNullValue();
-      
-    // Extract the first index.  If the ptr is a pointer to a structure
-    // and the next index is a structure offset (i.e., not an array offset), 
-    // we need to include an initial [0] to index into the pointer.
-    vector<Value*> idxVec(1, *OI);
-    PointerType* ptrType = cast<PointerType>(lastPtr->getType());
-    if (isa<StructType>(ptrType->getElementType())
-        && ! ptrType->indexValid(*OI))
-      idxVec.insert(idxVec.begin(), ConstantUInt::get(Type::UIntTy, 0));
-    
-    // Get the type obtained by applying the first index.
-    // It must be a structure or array.
-    const Type* nextType = MemAccessInst::getIndexedType(lastPtr->getType(),
-                                                         idxVec, true);
-    assert(isa<StructType>(nextType) || isa<ArrayType>(nextType));
+  User::const_op_iterator OI = GEP.idx_begin(), OE = GEP.idx_end();
+  for (; OI+1 != OE; ++OI) {
+    std::vector<Value*> Indices;
     
-    // Get a pointer to the structure or to the elements of the array.
-    const Type* nextPtrType =
-      PointerType::get(isa<StructType>(nextType) ? nextType
-                       : cast<ArrayType>(nextType)->getElementType());
-      
-    // Instruction 1: nextPtr1 = GetElementPtr lastPtr, idxVec
-    // This is not needed if the index is zero.
-    Value *gepValue;
-    if (indexIsZero)
-      gepValue = lastPtr;
-    else {
-      gepValue = new GetElementPtrInst(lastPtr, idxVec,"ptr1");
-      newIvec.push_back(cast<Instruction>(gepValue));
-    }
-      
-    // Instruction 2: nextPtr2 = cast nextPtr1 to nextPtrType
-    // This is not needed if the two types are identical.
-    Value *castInst;
-    if (gepValue->getType() == nextPtrType)
-      castInst = gepValue;
-    else {
-      castInst = new CastInst(gepValue, nextPtrType, "ptr2");
-      newIvec.push_back(cast<Instruction>(castInst));
+    // If this is the first index and is 0, skip it and move on!
+    if (OI == GEP.idx_begin()) {
+      if (*OI == ConstantInt::getNullValue((*OI)->getType()))
+        continue;
+    } else {
+      // Not the first index: include initial [0] to deref the last ptr
+      Indices.push_back(Constant::getNullValue(Type::UIntTy));
     }
-      
-    lastPtr = castInst;
+
+    Indices.push_back(*OI);
+
+    // New Instruction: nextPtr1 = GetElementPtr LastPtr, Indices
+    LastPtr = new GetElementPtrInst(LastPtr, Indices, "ptr1", InsertPoint);
+    ++NumAdded;
   }
-  
-  // 
+
   // Now create a new instruction to replace the original one
   //
-  PointerType *ptrType = cast<PointerType>(lastPtr->getType());
-
-  // First, get the final index vector.  As above, we may need an initial [0].
-  vector<Value*> idxVec(1, *OI);
-  if (isa<StructType>(ptrType->getElementType())
-      && !ptrType->indexValid(*OI))
-    idxVec.insert(idxVec.begin(), Constant::getNullValue(Type::UIntTy));
-  
-  Instruction* newInst = NULL;
-  switch(memI->getOpcode()) {
-  case Instruction::Load:
-    newInst = new LoadInst(lastPtr, idxVec, memI->getName());
-    break;
-  case Instruction::Store:
-    newInst = new StoreInst(memI->getOperand(0), lastPtr, idxVec);
-    break;
-  case Instruction::GetElementPtr:
-    newInst = new GetElementPtrInst(lastPtr, idxVec, memI->getName());
-    break;
-  default:
-    assert(0 && "Unrecognized memory access instruction");
-  }
-  newIvec.push_back(newInst);
-  
-  // Replace all uses of the old instruction with the new
-  memI->replaceAllUsesWith(newInst);
+  const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
 
-  // Now delete the old instruction...
-  delete memI;
+  // Get the final index vector, including an initial [0] as before.
+  std::vector<Value*> Indices;
+  Indices.push_back(Constant::getNullValue(Type::UIntTy));
+  Indices.push_back(*OI);
 
-  // Convert our iterator into an index... that cannot get invalidated
-  unsigned ItOffs = BBI-BB->begin();
+  Value *NewVal = new GetElementPtrInst(LastPtr, Indices, GEP.getName(),
+                                        InsertPoint);
+
+  // Replace all uses of the old instruction with the new
+  GEP.replaceAllUsesWith(NewVal);
 
-  // Insert all of the new instructions...
-  BB->getInstList().insert(BBI, newIvec.begin(), newIvec.end());
-  
-  // Advance the iterator to the instruction following the one just inserted...
-  BBI = BB->begin() + (ItOffs+newIvec.size());
+  // Now remove and delete the old instruction...
+  BB->getInstList().erase(&GEP);
+  return true;
 }