* Standardize how analysis results/passes as printed with the print() virtual
[oota-llvm.git] / lib / Transforms / Scalar / DecomposeMultiDimRefs.cpp
index a2d49c86c2541133700459984d69e3d692f67dda..f0a807497a77e76cd4f9ed4ad09e7fe620f0b178 100644 (file)
-//===- llvm/Transforms/DecomposeArrayRefs.cpp - Lower array refs to 1D -----=//
+//===- llvm/Transforms/DecomposeMultiDimRefs.cpp - Lower array refs to 1D -===//
 //
-// DecomposeArrayRefs - 
-// Convert multi-dimensional array references into a sequence of
-// instructions (using getelementpr and cast) so that each instruction
-// has at most one array offset.
+// 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/DecomposeArrayRefs.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/Constant.h"
 #include "llvm/iMemory.h"
 #include "llvm/iOther.h"
 #include "llvm/BasicBlock.h"
-#include "llvm/Method.h"
 #include "llvm/Pass.h"
+#include "Support/StatisticReporter.h"
 
+static Statistic<> NumAdded("lowerrefs\t\t- New instructions added");
+
+namespace {
+  struct DecomposePass : public BasicBlockPass {
+    virtual bool runOnBasicBlock(BasicBlock &BB);
+
+  private:
+    static void decomposeArrayRef(BasicBlock::iterator &BBI);
+  };
+
+  RegisterOpt<DecomposePass> X("lowerrefs", "Decompose multi-dimensional "
+                               "structure/array references");
+}
+
+Pass *createDecomposeMultiDimRefsPass() {
+  return new DecomposePass();
+}
+
+
+// runOnBasicBlock - Entry point for array or structure references with multiple
+// indices.
+//
+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;
+    }
+  }
+  
+  return Changed;
+}
 
 // 
-// This function repeats until we have a one-dim. reference: {
-//      // For an N-dim array ref, where N > 1, insert:
-//      aptr1 = getElementPtr [N-dim array] * lastPtr, uint firstIndex
-//      aptr2 = cast [N-dim-arry] * aptr to [<N-1>-dim-array] *
+// 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 aptr2 generated in the loop and a single index.
+// uses the last ptr2 generated in the loop and a single index.
+// If any index is (uint) 0, we omit the getElementPtr instruction.
 // 
-static BasicBlock::reverse_iterator
-decomposeArrayRef(BasicBlock::reverse_iterator& BBI)
-{
-  MemAccessInst *memI = cast<MemAccessInst>(*BBI);
-  BasicBlock* BB = memI->getParent();
-  Value* lastPtr = memI->getPointerOperand();
-  vector<Instruction*> newIvec;
+
+void DecomposePass::decomposeArrayRef(BasicBlock::iterator &BBI) {
+  MemAccessInst &MAI = cast<MemAccessInst>(*BBI);
+  BasicBlock *BB = MAI.getParent();
+  Value *LastPtr = MAI.getPointerOperand();
+
+  // Remove the instruction from the stream
+  BB->getInstList().remove(BBI);
+
+  std::vector<Instruction*> NewInsts;
   
-  MemAccessInst::const_op_iterator OI = memI->idx_begin();
-  for (MemAccessInst::const_op_iterator OE = memI->idx_end(); OI != OE; ++OI)
-    {
-      if (OI+1 == OE)                     // skip the last operand
-        break;
+  // Process each index except the last one.
+  // 
+
+  User::const_op_iterator OI = MAI.idx_begin(), OE = MAI.idx_end();
+  for (; 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<Constant>(*OI) && 
+                       cast<Constant>(OI->get())->isNullValue() &&
+                       OI->get()->getType() == Type::UIntTy;
       
-      assert(isa<PointerType>(lastPtr->getType()));
-      vector<Value*> idxVec(1, *OI);
-
-      // The first index does not change the type of the pointer
-      // since all pointers are treated as potential arrays (i.e.,
-      // int *X is either a scalar X[0] or an array at X[i]).
-      // 
-      const Type* nextPtrType;
-      // if (OI == memI->idx_begin())
-      //   nextPtrType = lastPtr->getType();
-      // else
-      //   {
-             const Type* nextArrayType =  
-               MemAccessInst::getIndexedType(lastPtr->getType(), idxVec,
-                                             /*allowCompositeLeaf*/ true);
-             nextPtrType = PointerType::get(cast<SequentialType>(nextArrayType)
-                                            ->getElementType());
-      //   }
+    // 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.
+    //
+
+    std::vector<Value*> Indices;
+    const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
+
+    if (isa<StructType>(PtrTy->getElementType())
+        && !PtrTy->indexValid(*OI))
+      Indices.push_back(Constant::getNullValue(Type::UIntTy));
+    Indices.push_back(*OI);
+
+    // Get the type obtained by applying the first index.
+    // It must be a structure or array.
+    const Type *NextTy = MemAccessInst::getIndexedType(LastPtr->getType(),
+                                                       Indices, true);
+    assert(isa<CompositeType>(NextTy));
+    
+    // Get a pointer to the structure or to the elements of the array.
+    const Type *NextPtrTy =
+      PointerType::get(isa<StructType>(NextTy) ? NextTy
+                       : cast<ArrayType>(NextTy)->getElementType());
       
-      Instruction* gepInst  = new GetElementPtrInst(lastPtr, idxVec, "aptr1");
-      Instruction* castInst = new CastInst(gepInst, nextPtrType, "aptr2");
-      lastPtr  = castInst;
+    // Instruction 1: nextPtr1 = GetElementPtr LastPtr, Indices
+    // This is not needed if the index is zero.
+    if (!indexIsZero) {
+      LastPtr = new GetElementPtrInst(LastPtr, Indices, "ptr1");
+      NewInsts.push_back(cast<Instruction>(LastPtr));
+      ++NumAdded;
+    }
+
       
-      newIvec.push_back(gepInst);
-      newIvec.push_back(castInst);
+    // Instruction 2: nextPtr2 = cast nextPtr1 to NextPtrTy
+    // This is not needed if the two types are identical.
+    //
+    if (LastPtr->getType() != NextPtrTy) {
+      LastPtr = new CastInst(LastPtr, NextPtrTy, "ptr2");
+      NewInsts.push_back(cast<Instruction>(LastPtr));
+      ++NumAdded;
     }
+  }
   
+  // 
   // Now create a new instruction to replace the original one
-  assert(lastPtr != memI->getPointerOperand() && "the above loop did not execute?");
-  assert(isa<PointerType>(lastPtr->getType()));
-  vector<Value*> idxVec(1, *OI);
-  const std::string newInstName = memI->hasName()? memI->getName()
-                                                 : string("oneDimRef");
-  Instruction* newInst = NULL;
-  
-  switch(memI->getOpcode())
-    {
-    case Instruction::Load:
-      newInst = new LoadInst(lastPtr, idxVec /*, newInstName */); break;
-    case Instruction::Store:
-      newInst = new StoreInst(memI->getOperand(0),
-                              lastPtr, idxVec /*, newInstName */); break;
-      break;
-    case Instruction::GetElementPtr:
-      newInst = new GetElementPtrInst(lastPtr, idxVec /*, newInstName */); break;
-    default:
-      assert(0 && "Unrecognized memory access instruction"); break;
-    }
-  
-  newIvec.push_back(newInst);
-  
-  // Replace all uses of the old instruction with the new
-  memI->replaceAllUsesWith(newInst);
-  
-  // Insert the instructions created in reverse order.  insert is destructive
-  // so we always have to use the new pointer returned by insert.
-  BasicBlock::iterator newI = BBI.base(); // gives ptr to instr. after memI
-  --newI;                                 // step back to memI
-  for (int i = newIvec.size()-1; i >= 0; i--)
-    newI = BB->getInstList().insert(newI, newIvec[i]);
-  
-  // Now delete the old instruction and return a pointer to the first new one
-  BB->getInstList().remove(memI);
-  delete memI;
-  
-  BasicBlock::reverse_iterator retI(newI); // reverse ptr to instr before newI
-  return --retI;                           // reverse pointer to newI
-}
+  //
+  const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
 
+  // First, get the final index vector.  As above, we may need an initial [0].
 
-//---------------------------------------------------------------------------
-// Entry point for decomposing multi-dimensional array references
-//---------------------------------------------------------------------------
+  std::vector<Value*> Indices;
+  if (isa<StructType>(PtrTy->getElementType())
+      && !PtrTy->indexValid(*OI))
+    Indices.push_back(Constant::getNullValue(Type::UIntTy));
+
+  Indices.push_back(*OI);
+
+  Instruction *NewI = 0;
+  switch(MAI.getOpcode()) {
+  case Instruction::Load:
+    NewI = new LoadInst(LastPtr, Indices, MAI.getName());
+    break;
+  case Instruction::Store:
+    NewI = new StoreInst(MAI.getOperand(0), LastPtr, Indices);
+    break;
+  case Instruction::GetElementPtr:
+    NewI = new GetElementPtrInst(LastPtr, Indices, MAI.getName());
+    break;
+  default:
+    assert(0 && "Unrecognized memory access instruction");
+  }
+  NewInsts.push_back(NewI);
 
-static bool
-doDecomposeArrayRefs(Method *M)
-{
-  bool changed = false;
-  
-  for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI)
-    for (BasicBlock::reverse_iterator newI, II=(*BI)->rbegin();
-         II != (*BI)->rend(); II = ++newI)
-      {
-        newI = II;
-        if (MemAccessInst *memI = dyn_cast<MemAccessInst>(*II))
-          { // Check for a multi-dimensional array access
-            const PointerType* ptrType =
-              cast<PointerType>(memI->getPointerOperand()->getType()); 
-            if (isa<ArrayType>(ptrType->getElementType()) &&
-                memI->getNumOperands() > 1+ memI->getFirstIndexOperandNumber())
-              {
-                newI = decomposeArrayRef(II);
-                changed = true;
-              }
-          }
-      }
   
-  return changed;
-}
+  // Replace all uses of the old instruction with the new
+  MAI.replaceAllUsesWith(NewI);
 
+  // Now delete the old instruction...
+  delete &MAI;
 
-namespace {
-  struct DecomposeArrayRefsPass : public MethodPass {
-    virtual bool runOnMethod(Method *M) { return doDecomposeArrayRefs(M); }
-  };
+  // Insert all of the new instructions...
+  BB->getInstList().insert(BBI, NewInsts.begin(), NewInsts.end());
+  
+  // Advance the iterator to the instruction following the one just inserted...
+  BBI = NewInsts.back();
+  ++BBI;
 }
-
-Pass *createDecomposeArrayRefsPass() { return new DecomposeArrayRefsPass(); }