-//===- llvm/Transforms/DecomposeArrayRefs.cpp - Lower array refs to 1D -----=//
+//===- llvm/Transforms/DecomposeMultiDimRefs.cpp - Lower array refs to 1D -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
//
-// 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/Constants.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/Statistic.h"
+namespace {
+ Statistic<> NumAdded("lowerrefs", "# of getelementptr instructions added");
-//
-// 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] *
-// }
-// Then it replaces the original instruction with an equivalent one that
-// uses the last aptr2 generated in the loop and a single index.
-//
-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;
-
- 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;
-
- 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());
- // }
-
- Instruction* gepInst = new GetElementPtrInst(lastPtr, idxVec, "aptr1");
- Instruction* castInst = new CastInst(gepInst, nextPtrType, "aptr2");
- lastPtr = castInst;
-
- newIvec.push_back(gepInst);
- newIvec.push_back(castInst);
- }
-
- // 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
+ struct DecomposePass : public BasicBlockPass {
+ virtual bool runOnBasicBlock(BasicBlock &BB);
+ };
}
+RegisterOpt<DecomposePass> X("lowerrefs", "Decompose multi-dimensional "
+ "structure/array references");
-//---------------------------------------------------------------------------
-// Entry point for decomposing multi-dimensional array references
-//---------------------------------------------------------------------------
+FunctionPass
+*createDecomposeMultiDimRefsPass()
+{
+ return new DecomposePass();
+}
-static bool
-doDecomposeArrayRefs(Method *M)
+
+// runOnBasicBlock - Entry point for array or structure references with multiple
+// indices.
+//
+bool
+DecomposePass::runOnBasicBlock(BasicBlock &BB)
{
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;
- }
- }
- }
-
+ for (BasicBlock::iterator II = BB.begin(); II != BB.end(); )
+ if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(II++)) // pre-inc
+ if (gep->getNumIndices() >= 2)
+ changed |= DecomposeArrayRef(gep); // always modifies II
return changed;
}
-namespace {
- struct DecomposeArrayRefsPass : public MethodPass {
- virtual bool runOnMethod(Method *M) { return doDecomposeArrayRefs(M); }
- };
-}
+// Function: DecomposeArrayRef()
+//
+// For any GetElementPtrInst with 2 or more array and structure indices:
+//
+// opCode CompositeType* P, [uint|ubyte] idx1, ..., [uint|ubyte] idxN
+//
+// 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
+DecomposeArrayRef(GetElementPtrInst* GEP)
+{
+ if (GEP->getNumIndices() < 2)
+ return false;
+
+ BasicBlock *BB = GEP->getParent();
+ Value *LastPtr = GEP->getPointerOperand();
+ Instruction *InsertPoint = GEP->getNext(); // Insert before the next insn
+
+ // The vector of new instructions to be created
+ std::vector<Instruction*> NewInsts;
+
+ // Process each index except the last one.
+ User::const_op_iterator OI = GEP->idx_begin(), OE = GEP->idx_end();
+ for (; OI+1 != OE; ++OI) {
+ std::vector<Value*> Indices;
+
+ // 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::LongTy));
-Pass *createDecomposeArrayRefsPass() { return new DecomposeArrayRefsPass(); }
+ 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
+ //
+ const PointerType *PtrTy = cast<PointerType>(LastPtr->getType());
+
+ // Get the final index vector, including an initial [0] as before.
+ std::vector<Value*> Indices;
+ Indices.push_back(Constant::getNullValue(Type::LongTy));
+ Indices.push_back(*OI);
+
+ Value *NewVal = new GetElementPtrInst(LastPtr, Indices, GEP->getName(),
+ InsertPoint);
+
+ // Replace all uses of the old instruction with the new
+ GEP->replaceAllUsesWith(NewVal);
+
+ // Now remove and delete the old instruction...
+ BB->getInstList().erase(GEP);
+
+ return true;
+}