* We were forgetting to pass varargs arguments through a call
[oota-llvm.git] / lib / Transforms / Scalar / IndVarSimplify.cpp
index acd1deb711030bb10c963696891d5f29d42b4b68..1744fe41b2df4b1dad83da77c42fedeea2328c2a 100644 (file)
@@ -1,35 +1,42 @@
 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
+// 
+//                     The LLVM Compiler Infrastructure
 //
-// InductionVariableSimplify - Transform induction variables in a program
-//   to all use a single cannonical induction variable per loop.
+// 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.
+// 
+//===----------------------------------------------------------------------===//
+//
+// Guarantees that all loops with identifiable, linear, induction variables will
+// be transformed to have a single, canonical, induction variable.  After this
+// pass runs, it guarantees the the first PHI node of the header block in the
+// loop is the canonical induction variable if there is one.
 //
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Transforms/Scalar.h"
 #include "llvm/Analysis/InductionVariable.h"
 #include "llvm/Analysis/LoopInfo.h"
-#include "llvm/Analysis/Writer.h"
 #include "llvm/iPHINode.h"
 #include "llvm/iOther.h"
 #include "llvm/Type.h"
 #include "llvm/Constants.h"
 #include "llvm/Support/CFG.h"
+#include "Support/Debug.h"
+#include "Support/Statistic.h"
 #include "Support/STLExtras.h"
-#include "Support/StatisticReporter.h"
-
-static Statistic<> NumRemoved ("indvars\t\t- Number of aux indvars removed");
-static Statistic<> NumInserted("indvars\t\t- Number of cannonical indvars added");
 
+namespace {
+  Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
+  Statistic<> NumInserted("indvars", "Number of canonical indvars added");
+}
 
 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
 // name...
 //
-static Instruction *InsertCast(Instruction *Val, const Type *Ty,
-                               BasicBlock::iterator It) {
-  Instruction *Cast = new CastInst(Val, Ty);
-  if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
-  Val->getParent()->getInstList().insert(It, Cast);
-  return Cast;
+static Instruction *InsertCast(Value *Val, const Type *Ty,
+                               Instruction *InsertBefore) {
+  return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore);
 }
 
 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
@@ -40,7 +47,7 @@ static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
   // Get the header node for this loop.  All of the phi nodes that could be
   // induction variables must live in this basic block.
   //
-  BasicBlock *Header = Loop->getBlocks().front();
+  BasicBlock *Header = Loop->getHeader();
   
   // Loop over all of the PHI nodes in the basic block, calculating the
   // induction variables that they represent... stuffing the induction variable
@@ -48,45 +55,41 @@ static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
   //
   std::vector<InductionVariable> IndVars;    // Induction variables for block
   BasicBlock::iterator AfterPHIIt = Header->begin();
-  for (; PHINode *PN = dyn_cast<PHINode>(&*AfterPHIIt); ++AfterPHIIt)
+  for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
     IndVars.push_back(InductionVariable(PN, Loops));
-  // AfterPHIIt now points to first nonphi instruction...
+  // AfterPHIIt now points to first non-phi instruction...
 
   // If there are no phi nodes in this basic block, there can't be indvars...
   if (IndVars.empty()) return Changed;
   
-  // Loop over the induction variables, looking for a cannonical induction
+  // Loop over the induction variables, looking for a canonical induction
   // variable, and checking to make sure they are not all unknown induction
   // variables.
   //
   bool FoundIndVars = false;
-  InductionVariable *Cannonical = 0;
+  InductionVariable *Canonical = 0;
   for (unsigned i = 0; i < IndVars.size(); ++i) {
-    if (IndVars[i].InductionType == InductionVariable::Cannonical)
-      Cannonical = &IndVars[i];
+    if (IndVars[i].InductionType == InductionVariable::Canonical &&
+        !isa<PointerType>(IndVars[i].Phi->getType()))
+      Canonical = &IndVars[i];
     if (IndVars[i].InductionType != InductionVariable::Unknown)
       FoundIndVars = true;
   }
 
-  // No induction variables, bail early... don't add a cannonnical indvar
+  // No induction variables, bail early... don't add a canonical indvar
   if (!FoundIndVars) return Changed;
 
-  // Okay, we want to convert other induction variables to use a cannonical
+  // Okay, we want to convert other induction variables to use a canonical
   // indvar.  If we don't have one, add one now...
-  if (!Cannonical) {
-    // Create the PHI node for the new induction variable
-    PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
-
-    // Insert the phi node at the end of the other phi nodes...
-    AfterPHIIt = ++Header->getInstList().insert(AfterPHIIt, PN);
+  if (!Canonical) {
+    // Create the PHI node for the new induction variable, and insert the phi
+    // node at the start of the PHI nodes...
+    PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", Header->begin());
 
     // Create the increment instruction to add one to the counter...
     Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
                                               ConstantUInt::get(Type::UIntTy,1),
-                                              "add1-indvar");
-
-    // Insert the add instruction after all of the PHI nodes...
-    Header->getInstList().insert(AfterPHIIt, Add);
+                                              "add1-indvar", AfterPHIIt);
 
     // Figure out which block is incoming and which is the backedge for the loop
     BasicBlock *Incoming, *BackEdgeBlock;
@@ -107,57 +110,65 @@ static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
 
     // Analyze the new induction variable...
     IndVars.push_back(InductionVariable(PN, Loops));
-    assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
-           "Just inserted cannonical indvar that is not cannonical!");
-    Cannonical = &IndVars.back();
+    assert(IndVars.back().InductionType == InductionVariable::Canonical &&
+           "Just inserted canonical indvar that is not canonical!");
+    Canonical = &IndVars.back();
     ++NumInserted;
     Changed = true;
+  } else {
+    // If we have a canonical induction variable, make sure that it is the first
+    // one in the basic block.
+    if (&Header->front() != Canonical->Phi)
+      Header->getInstList().splice(Header->begin(), Header->getInstList(),
+                                   Canonical->Phi);
   }
 
   DEBUG(std::cerr << "Induction variables:\n");
 
   // Get the current loop iteration count, which is always the value of the
-  // cannonical phi node...
+  // canonical phi node...
   //
-  PHINode *IterCount = Cannonical->Phi;
+  PHINode *IterCount = Canonical->Phi;
 
-  // Loop through and replace all of the auxillary induction variables with
-  // references to the primary induction variable...
+  // Loop through and replace all of the auxiliary induction variables with
+  // references to the canonical induction variable...
   //
   for (unsigned i = 0; i < IndVars.size(); ++i) {
     InductionVariable *IV = &IndVars[i];
 
-    DEBUG(std::cerr << IV);
+    DEBUG(IV->print(std::cerr));
 
-    // Don't modify the cannonical indvar or unrecognized indvars...
-    if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
+    // Don't do math with pointers...
+    const Type *IVTy = IV->Phi->getType();
+    if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
+
+    // Don't modify the canonical indvar or unrecognized indvars...
+    if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
       Instruction *Val = IterCount;
       if (!isa<ConstantInt>(IV->Step) ||   // If the step != 1
           !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
-        std::string Name;   // Create a scale by the step value...
-        if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
 
         // If the types are not compatible, insert a cast now...
-        if (Val->getType() != IV->Step->getType())
-          Val = InsertCast(Val, IV->Step->getType(), AfterPHIIt);
+        if (Val->getType() != IVTy)
+          Val = InsertCast(Val, IVTy, AfterPHIIt);
+        if (IV->Step->getType() != IVTy)
+          IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
 
-        Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
-        // Insert the phi node at the end of the other phi nodes...
-        Header->getInstList().insert(AfterPHIIt, Val);
+        Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
+                                     IV->Phi->getName()+"-scale", AfterPHIIt);
       }
 
-      if (!isa<Constant>(IV->Start) ||   // If the start != 0
-          !cast<Constant>(IV->Start)->isNullValue()) {
-        std::string Name;   // Create a offset by the start value...
-        if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
-
+      // If the start != 0
+      if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
         // If the types are not compatible, insert a cast now...
-        if (Val->getType() != IV->Start->getType())
-          Val = InsertCast(Val, IV->Start->getType(), AfterPHIIt);
-
-        Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
-        // Insert the phi node at the end of the other phi nodes...
-        Header->getInstList().insert(AfterPHIIt, Val);
+        if (Val->getType() != IVTy)
+          Val = InsertCast(Val, IVTy, AfterPHIIt);
+        if (IV->Start->getType() != IVTy)
+          IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
+
+        // Insert the instruction after the phi nodes...
+        Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
+                                     IV->Phi->getName()+"-offset", AfterPHIIt);
       }
 
       // If the PHI node has a different type than val is, insert a cast now...
@@ -184,10 +195,6 @@ static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
 
 namespace {
   struct InductionVariableSimplify : public FunctionPass {
-    const char *getPassName() const {
-      return "Induction Variable Cannonicalize";
-    }
-
     virtual bool runOnFunction(Function &) {
       LoopInfo &LI = getAnalysis<LoopInfo>();
 
@@ -198,13 +205,15 @@ namespace {
     }
     
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
-      AU.addRequired(LoopInfo::ID);
-      AU.preservesCFG();
+      AU.addRequired<LoopInfo>();
+      AU.addRequiredID(LoopSimplifyID);
+      AU.setPreservesCFG();
     }
   };
+  RegisterOpt<InductionVariableSimplify> X("indvars",
+                                           "Canonicalize Induction Variables");
 }
 
 Pass *createIndVarSimplifyPass() {
   return new InductionVariableSimplify();
 }
-