Merge pull request #11807 from eeckstein/fix-capture-promotion-4.0

CapturePromotion: fix a crash in case the partial_apply has type dependent operands.
diff --git a/lib/SILOptimizer/IPO/CapturePromotion.cpp b/lib/SILOptimizer/IPO/CapturePromotion.cpp
index b8aa3f4..c82273e 100644
--- a/lib/SILOptimizer/IPO/CapturePromotion.cpp
+++ b/lib/SILOptimizer/IPO/CapturePromotion.cpp
@@ -1209,6 +1209,7 @@
   // Initialize a SILBuilder and create a function_ref referencing the cloned
   // closure.
   SILBuilderWithScope B(PAI);
+  B.addOpenedArchetypeOperands(PAI);
   SILValue FnVal = B.createFunctionRef(PAI->getLoc(), ClonedFn);
 
   // Populate the argument list for a new partial_apply instruction, taking into
@@ -1222,7 +1223,8 @@
   auto CalleePInfo = SubstCalleeFunctionTy->getParameters();
   SILFunctionConventions paConv(PAI->getType().castTo<SILFunctionType>(), M);
   unsigned FirstIndex = paConv.getNumSILArguments();
-  unsigned OpNo = 1, OpCount = PAI->getNumOperands();
+  unsigned OpNo = 1;
+  unsigned OpCount = PAI->getNumOperands() - PAI->getNumTypeDependentOperands();
   SmallVector<SILValue, 16> Args;
   auto NumIndirectResults = calleeConv.getNumIndirectSILResults();
   for (; OpNo != OpCount; ++OpNo) {
diff --git a/test/SILOptimizer/capture_promotion.sil b/test/SILOptimizer/capture_promotion.sil
index ceaab34..50f17a4 100644
--- a/test/SILOptimizer/capture_promotion.sil
+++ b/test/SILOptimizer/capture_promotion.sil
@@ -305,4 +305,24 @@
   return %16 : $()
 }
 
+// CHECK-LABEL: sil @test_with_dynamic_self
+// CHECK: %{{[0-9]+}} = partial_apply %{{[0-9]+}}(%{{[0-9]+}}, %{{[0-9]+}}) : $@convention(thin) (Int, @thick @dynamic_self Bar.Type) -> () // type-defs: %1
+// CHECK: return
+sil @test_with_dynamic_self : $@convention(method) (Int, @guaranteed Bar) -> () {
+bb0(%0 : $Int, %1 : $Bar):
+  %4 = alloc_box ${ var Int }, var, name "item"
+  %5 = project_box %4 : ${ var Int }, 0
+  store %0 to %5 : $*Int
+  %17 = function_ref @closure_with_dynamic_self : $@convention(thin) (@owned { var Int }, @thick @dynamic_self Bar.Type) -> ()
+  %21 = metatype $@thick @dynamic_self Bar.Type
+  %26 = partial_apply %17(%4, %21) : $@convention(thin) (@owned { var Int }, @thick @dynamic_self Bar.Type) -> ()
+  %39 = tuple ()
+  return %39 : $()
+}
 
+sil private @closure_with_dynamic_self : $@convention(thin) (@owned { var Int }, @thick @dynamic_self Bar.Type) -> () {
+bb0(%1 : ${ var Int }, %2 : $@thick @dynamic_self Bar.Type):
+  strong_release %1 : ${ var Int }
+  %39 = tuple ()
+  return %39 : $()
+}