Index: lib/Transforms/Vectorize/SLPVectorizer.cpp
===================================================================
--- lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -785,9 +785,10 @@
           break;
         case ReorderingMode::Opcode:
           // We accept both Instructions and Undefs, but with different scores.
-          if ((isa<Instruction>(Op) &&
+          if ((isa<Instruction>(Op) && isa<Instruction>(OpLastLane) &&
                cast<Instruction>(Op)->getOpcode() ==
                    cast<Instruction>(OpLastLane)->getOpcode()) ||
+              (isa<UndefValue>(OpLastLane) && isa<Instruction>(Op)) ||
               isa<UndefValue>(Op)) {
             // An instruction has a higher score than an undef.
             unsigned Score = (isa<UndefValue>(Op)) ? GoodScore : BestScore;
Index: test/Transforms/SLPVectorizer/X86/crash_reordering_undefs.ll
===================================================================
--- /dev/null
+++ test/Transforms/SLPVectorizer/X86/crash_reordering_undefs.ll
@@ -0,0 +1,25 @@
+; RUN: opt -slp-vectorizer -S < %s -mtriple=x86_64-unknown-linux -mcpu=corei7-avx
+target triple = "x86_64-unknown-linux-gnu"
+
+define i32 @crash_reordering_undefs() {
+entry:
+  %or0 = or i64 undef, undef
+  %cmp0 = icmp eq i64 undef, %or0
+  %add0 = select i1 %cmp0, i32 65536, i32 65537
+  %add1 = add i32 undef, %add0
+  %cmp1 = icmp eq i64 undef, undef
+  %add2 = select i1 %cmp1, i32 65536, i32 65537
+  %add3 = add i32 %add1, %add2
+  %cmp2 = icmp eq i64 undef, undef
+  %add4 = select i1 %cmp2, i32 65536, i32 65537
+  %add5 = add i32 %add3, %add4
+  %add6 = add i32 %add5, undef
+  %add7 = add i32 %add6, undef
+  %add8 = add i32 %add7, undef
+  %or1 = or i64 undef, undef
+  %cmp3 = icmp eq i64 undef, %or1
+  %add9 = select i1 %cmp3, i32 65536, i32 65537
+  %add10 = add i32 %add8, %add9
+  %add11 = add i32 %add10, undef
+  ret i32 %add11
+}