Various cleanups and efficiency improvements
[oota-llvm.git] / lib / Transforms / Scalar / IndVarSimplify.cpp
index 814f452497ed3d9267952d21d351603a5fbf3995..1744fe41b2df4b1dad83da77c42fedeea2328c2a 100644 (file)
@@ -1,4 +1,11 @@
 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
+// 
+//                     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.
+// 
+//===----------------------------------------------------------------------===//
 //
 // Guarantees that all loops with identifiable, linear, induction variables will
 // be transformed to have a single, canonical, induction variable.  After this
@@ -50,7 +57,7 @@ static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
   BasicBlock::iterator AfterPHIIt = Header->begin();
   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;
@@ -76,8 +83,8 @@ static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
   // indvar.  If we don't have one, add one now...
   if (!Canonical) {
     // Create the PHI node for the new induction variable, and insert the phi
-    // node at the end of the other phi nodes...
-    PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", AfterPHIIt);
+    // 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,
@@ -108,6 +115,12 @@ static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
     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");
@@ -193,7 +206,7 @@ namespace {
     
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequired<LoopInfo>();
-      AU.addRequiredID(LoopPreheadersID);
+      AU.addRequiredID(LoopSimplifyID);
       AU.setPreservesCFG();
     }
   };