Fix a corner case hit by redundant phi elimination running after LSR.

Fixes PR11761: bad IR w/ redundant Phi elim


git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@148177 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Analysis/ScalarEvolutionExpander.cpp b/lib/Analysis/ScalarEvolutionExpander.cpp
index 8dc8eb6..e2f75aa 100644
--- a/lib/Analysis/ScalarEvolutionExpander.cpp
+++ b/lib/Analysis/ScalarEvolutionExpander.cpp
@@ -1541,6 +1541,13 @@
 /// general code-insertion helper.
 bool SCEVExpander::hoistStep(Instruction *IncV, Instruction *InsertPos,
                              const DominatorTree *DT) {
+  // Phi nodes are strangely positional but don't follow normal rules for
+  // instruction dominance. Handle them immediately.
+  if (isa<PHINode>(InsertPos))
+    return isa<PHINode>(IncV);
+  else if (isa<PHINode>(IncV))
+    return false;
+
   if (DT->dominates(IncV, InsertPos))
     return true;
 
@@ -1648,7 +1655,10 @@
                         << *IsomorphicInc << '\n');
         Value *NewInc = OrigInc;
         if (OrigInc->getType() != IsomorphicInc->getType()) {
-          IRBuilder<> Builder(OrigInc->getNextNode());
+          Instruction *IP = isa<PHINode>(OrigInc)
+            ? (Instruction*)L->getHeader()->getFirstInsertionPt()
+            : OrigInc->getNextNode();
+          IRBuilder<> Builder(IP);
           Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
           NewInc = Builder.
             CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);