[InstCombine] Don't insert an instruction after a terminator

We tried to insert a cast of a phi in a block whose terminator is an
EHPad.  This is invalid.  Do not attempt the transform in these
circumstances.

llvm-svn: 252370
diff --git a/llvm/lib/Transforms/InstCombine/InstCombinePHI.cpp b/llvm/lib/Transforms/InstCombine/InstCombinePHI.cpp
index 1d3b837..a9f8f49 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombinePHI.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombinePHI.cpp
@@ -469,6 +469,12 @@
 /// only used by the PHI, PHI together their inputs, and do the operation once,
 /// to the result of the PHI.
 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
+  // We cannot create a new instruction after the PHI if the terminator is an
+  // EHPad because there is no valid insertion point.
+  if (TerminatorInst *TI = PN.getParent()->getTerminator())
+    if (TI->isEHPad())
+      return nullptr;
+
   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
 
   if (isa<GetElementPtrInst>(FirstInst))
diff --git a/llvm/test/Transforms/InstCombine/token.ll b/llvm/test/Transforms/InstCombine/token.ll
index bb35d15..c8f1dc1 100644
--- a/llvm/test/Transforms/InstCombine/token.ll
+++ b/llvm/test/Transforms/InstCombine/token.ll
@@ -4,7 +4,7 @@
 
 declare i32 @__CxxFrameHandler3(...)
 
-define i8* @f() personality i32 (...)* @__CxxFrameHandler3 {
+define void @test1() personality i32 (...)* @__CxxFrameHandler3 {
 bb:
   unreachable
 
@@ -13,9 +13,45 @@
   cleanupret %cl unwind to caller
 }
 
+; CHECK-LABEL: define void @test1(
 ; CHECK: unreachable:
 ; CHECK:   %cl = cleanuppad []
 ; CHECK:   cleanupret %cl unwind to caller
 
+define void @test2(i8 %A, i8 %B) personality i32 (...)* @__CxxFrameHandler3 {
+bb:
+  %X = zext i8 %A to i32
+  invoke void @g(i32 0)
+    to label %cont
+    unwind label %catch
 
-declare void @g(i8*)
+cont:
+  %Y = zext i8 %B to i32
+  invoke void @g(i32 0)
+    to label %unreachable
+    unwind label %catch
+
+catch:
+  %phi = phi i32 [ %X, %bb ], [ %Y, %cont ]
+  %cl = catchpad []
+   to label %doit
+   unwind label %endpad
+
+doit:
+  call void @g(i32 %phi)
+  unreachable
+
+unreachable:
+  unreachable
+
+endpad:
+  catchendpad unwind to caller
+}
+
+
+; CHECK-LABEL: define void @test2(
+; CHECK:  %X = zext i8 %A to i32
+; CHECK:  %Y = zext i8 %B to i32
+; CHECK:  %phi = phi i32 [ %X, %bb ], [ %Y, %cont ]
+
+declare void @g(i32)