Merge pull request #12246 from linux-on-ibm-z/swift40-URBPTest-fix

[stdlib] Fix for initFromArray test on big endian (4.0)
diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp
index 4bb5870..98a37ba 100644
--- a/lib/ClangImporter/ImportDecl.cpp
+++ b/lib/ClangImporter/ImportDecl.cpp
@@ -4341,9 +4341,10 @@
       SmallVector<TypeLoc, 4> inheritedTypes;
       Type superclassType;
       if (decl->getSuperClass()) {
-        auto clangSuperclassType =
-          Impl.getClangASTContext().getObjCObjectPointerType(
-              clang::QualType(decl->getSuperClassType(), 0));
+        clang::QualType clangSuperclassType =
+          decl->getSuperClassType()->stripObjCKindOfTypeAndQuals(clangCtx);
+        clangSuperclassType =
+          clangCtx.getObjCObjectPointerType(clangSuperclassType);
         superclassType = Impl.importType(clangSuperclassType,
                                          ImportTypeKind::Abstract,
                                          isInSystemModule(dc),
diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp
index 13514b9..fd06a97 100644
--- a/lib/IRGen/GenDecl.cpp
+++ b/lib/IRGen/GenDecl.cpp
@@ -1416,7 +1416,8 @@
 
   case SILLinkage::Shared:
   case SILLinkage::SharedExternal:
-    return RESULT(LinkOnceODR, Hidden, Default);
+    return isDefinition ? RESULT(LinkOnceODR, Hidden, Default)
+                        : RESULT(External, Hidden, Default);
 
   case SILLinkage::Hidden:
     return RESULT(External, Hidden, Default);
diff --git a/lib/Migrator/APIDiffMigratorPass.cpp b/lib/Migrator/APIDiffMigratorPass.cpp
index 9308bde..a0dacc4 100644
--- a/lib/Migrator/APIDiffMigratorPass.cpp
+++ b/lib/Migrator/APIDiffMigratorPass.cpp
@@ -684,14 +684,19 @@
           StringRef NewArg = View.args()[Index++];
           auto ArgLoc = PD->getArgumentNameLoc();
 
+          // Represent empty label with underscore.
+          if (NewArg.empty())
+            NewArg = "_";
+
           // If the argument name is not specified, add the argument name before
           // the parameter name.
           if (ArgLoc.isInvalid())
             Editor.insertBefore(PD->getNameLoc(),
                                 (llvm::Twine(NewArg) + " ").str());
-          else
+          else {
             // Otherwise, replace the argument name directly.
             Editor.replaceToken(ArgLoc, NewArg);
+          }
         }
       }
     }
diff --git a/lib/SIL/SILBuilder.cpp b/lib/SIL/SILBuilder.cpp
index 499e852..db5bfec 100644
--- a/lib/SIL/SILBuilder.cpp
+++ b/lib/SIL/SILBuilder.cpp
@@ -403,10 +403,19 @@
   if (I && I->getNumTypeDependentOperands() > 0)
     return;
 
+  // Keep track of already visited instructions to avoid infinite loops.
+  SmallPtrSet<SILInstruction *, 8> Visited;
+
   while (I && I->getNumOperands() == 1 &&
          I->getNumTypeDependentOperands() == 0) {
     I = dyn_cast<SILInstruction>(I->getOperand(0));
-    if (!I)
+    // Within SimplifyCFG this function may be called for an instruction
+    // within unreachable code. And within an unreachable block it can happen
+    // that defs do not dominate uses (because there is no dominance defined).
+    // To avoid the infinite loop when following the chain of instructions via
+    // their operands, bail if the operand is not an instruction or this
+    // instruction was seen already.
+    if (!I || !Visited.insert(I).second)
       return;
     // If it is a definition of an opened archetype,
     // register it and exit.
diff --git a/lib/SIL/SILFunctionType.cpp b/lib/SIL/SILFunctionType.cpp
index 30a2279..65406a3 100644
--- a/lib/SIL/SILFunctionType.cpp
+++ b/lib/SIL/SILFunctionType.cpp
@@ -765,9 +765,14 @@
     for (auto capture : loweredCaptures.getCaptures()) {
       if (capture.isDynamicSelfMetadata()) {
         ParameterConvention convention = ParameterConvention::Direct_Unowned;
+        auto dynamicSelfInterfaceType = GenericEnvironment::mapTypeOutOfContext(
+          function->getGenericEnvironment(),
+          loweredCaptures.getDynamicSelfType());
+        
         auto selfMetatype = MetatypeType::get(
-            loweredCaptures.getDynamicSelfType(),
+            dynamicSelfInterfaceType,
             MetatypeRepresentation::Thick);
+        
         auto canSelfMetatype = getCanonicalType(selfMetatype);
         SILParameterInfo param(canSelfMetatype, convention);
         inputs.push_back(param);
diff --git a/lib/SILGen/SILGenExpr.cpp b/lib/SILGen/SILGenExpr.cpp
index 3d32374..2f97a61 100644
--- a/lib/SILGen/SILGenExpr.cpp
+++ b/lib/SILGen/SILGenExpr.cpp
@@ -2140,15 +2140,19 @@
   
   auto fnRef = ManagedValue::forUnmanaged(emitGlobalFunctionRef(loc,generator));
   auto fnType = fnRef.getType().castTo<SILFunctionType>();
-  auto substFnType = fnType->substGenericArgs(SGM.M,
-                                          defaultArgsOwner.getSubstitutions());
+
+  SubstitutionList subs;
+  if (fnType->isPolymorphic())
+    subs = defaultArgsOwner.getSubstitutions();
+
+  auto substFnType = fnType->substGenericArgs(SGM.M, subs);
+
   CalleeTypeInfo calleeTypeInfo(substFnType, origResultType, resultType);
   ResultPlanPtr resultPtr =
       ResultPlanBuilder::computeResultPlan(*this, calleeTypeInfo, loc, C);
   ArgumentScope argScope(*this, loc);
   return emitApply(std::move(resultPtr), std::move(argScope), loc, fnRef,
-                   defaultArgsOwner.getSubstitutions(), {}, calleeTypeInfo,
-                   ApplyOptions::None, C);
+                   subs, {}, calleeTypeInfo, ApplyOptions::None, C);
 }
 
 RValue SILGenFunction::emitApplyOfStoredPropertyInitializer(
diff --git a/lib/SILOptimizer/LoopTransforms/COWArrayOpt.cpp b/lib/SILOptimizer/LoopTransforms/COWArrayOpt.cpp
index 359dec8..0a8d4f2 100644
--- a/lib/SILOptimizer/LoopTransforms/COWArrayOpt.cpp
+++ b/lib/SILOptimizer/LoopTransforms/COWArrayOpt.cpp
@@ -2213,6 +2213,24 @@
   C.removeCall();
 }
 
+/// Collects all loop dominated blocks outside the loop that are immediately
+/// dominated by the loop.
+static void
+collectImmediateLoopDominatedBlocks(const SILLoop *Lp, DominanceInfoNode *Node,
+                                    SmallVectorImpl<SILBasicBlock *> &Blocks) {
+  SILBasicBlock *BB = Node->getBlock();
+
+  // Base case: First loop dominated block outside of loop.
+  if (!Lp->contains(BB)) {
+    Blocks.push_back(BB);
+    return;
+  }
+
+  // Loop contains the basic block. Look at immediately dominated nodes.
+  for (auto *Child : *Node)
+    collectImmediateLoopDominatedBlocks(Lp, Child, Blocks);
+}
+
 void ArrayPropertiesSpecializer::specializeLoopNest() {
   auto *Lp = getLoop();
   assert(Lp);
@@ -2225,22 +2243,19 @@
   auto *CheckBlock = splitBasicBlockAndBranch(B,
       HoistableLoopPreheader->getTerminator(), DomTree, nullptr);
 
-  // Get the exit blocks of the original loop.
   auto *Header = CheckBlock->getSingleSuccessorBlock();
   assert(Header);
 
-  // Our loop info is not really completely valid anymore since the cloner does
-  // not update it. However, exit blocks of the original loop are still valid.
+  // Collect all loop dominated blocks (e.g exit blocks could be among them). We
+  // need to update their dominator.
+  SmallVector<SILBasicBlock *, 16> LoopDominatedBlocks;
+  collectImmediateLoopDominatedBlocks(Lp, DomTree->getNode(Header),
+                                      LoopDominatedBlocks);
+
+  // Collect all exit blocks.
   SmallVector<SILBasicBlock *, 16> ExitBlocks;
   Lp->getExitBlocks(ExitBlocks);
 
-  // Collect the exit blocks dominated by the loop - they will be dominated by
-  // the check block.
-  SmallVector<SILBasicBlock *, 16> ExitBlocksDominatedByPreheader;
-  for (auto *ExitBlock: ExitBlocks)
-    if (DomTree->dominates(CheckBlock, ExitBlock))
-      ExitBlocksDominatedByPreheader.push_back(ExitBlock);
-
   // Split the preheader before the first instruction.
   SILBasicBlock *NewPreheader =
     splitBasicBlockAndBranch(B, &*CheckBlock->begin(), DomTree, nullptr);
@@ -2269,8 +2284,8 @@
                      IsFastNativeArray, ClonedPreheader, NewPreheader);
   CheckBlock->getTerminator()->eraseFromParent();
 
-  // Fixup the exit blocks. They are now dominated by the check block.
-  for (auto *BB : ExitBlocksDominatedByPreheader)
+  // Fixup the loop dominated blocks. They are now dominated by the check block.
+  for (auto *BB : LoopDominatedBlocks)
     DomTree->changeImmediateDominator(DomTree->getNode(BB),
                                       DomTree->getNode(CheckBlock));
 
diff --git a/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp b/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
index d393dae..29b50e9 100644
--- a/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
+++ b/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
@@ -417,6 +417,12 @@
   if (SubstCalleeTy->hasArchetype() || ConvertCalleeTy->hasArchetype())
     return nullptr;
 
+  // Bail if the result type of the converted callee is different from the callee's
+  // result type of the apply instruction.
+  if (SubstCalleeTy->getAllResultsType() != ConvertCalleeTy->getAllResultsType()) {
+    return nullptr;
+  }
+
   // Ok, we can now perform our transformation. Grab AI's operands and the
   // relevant types from the ConvertFunction function type and AI.
   Builder.setCurrentDebugScope(AI.getDebugScope());
@@ -461,9 +467,13 @@
     NAI = Builder.createTryApply(AI.getLoc(), FRI, 
                                  SubstitutionList(), Args,
                                  TAI->getNormalBB(), TAI->getErrorBB());
-  else
+  else {
     NAI = Builder.createApply(AI.getLoc(), FRI, SubstitutionList(), Args,
                               cast<ApplyInst>(AI)->isNonThrowing());
+    assert(FullApplySite::isa(NAI).getSubstCalleeType()->getAllResultsType() ==
+           AI.getSubstCalleeType()->getAllResultsType() &&
+           "Function types should be the same");
+  }
   return NAI;
 }
 
@@ -557,8 +567,11 @@
 /// initialized. This is either a init_existential_addr or the source of a
 /// copy_addr. Returns a null value if the address does not dominate the
 /// alloc_stack user \p ASIUser.
+/// If the value is copied from another stack location, \p isCopied is set to
+/// true.
 static SILValue getAddressOfStackInit(AllocStackInst *ASI,
-                                      SILInstruction *ASIUser) {
+                                      SILInstruction *ASIUser,
+                                      bool &isCopied) {
   SILInstruction *SingleWrite = nullptr;
   // Check that this alloc_stack is initialized only once.
   for (auto Use : ASI->getUses()) {
@@ -578,6 +591,7 @@
         if (SingleWrite)
           return SILValue();
         SingleWrite = CAI;
+        isCopied = true;
       }
       continue;
     }
@@ -611,9 +625,10 @@
   if (auto *CAI = dyn_cast<CopyAddrInst>(SingleWrite)) {
     // Try to derive the type from the copy_addr that was used to
     // initialize the alloc_stack.
+    assert(isCopied && "isCopied not set for a copy_addr");
     SILValue CAISrc = CAI->getSrc();
     if (auto *ASI = dyn_cast<AllocStackInst>(CAISrc))
-      return getAddressOfStackInit(ASI, CAI);
+      return getAddressOfStackInit(ASI, CAI, isCopied);
     return CAISrc;
   }
   return SingleWrite;
@@ -621,13 +636,18 @@
 
 /// Find the init_existential, which could be used to determine a concrete
 /// type of the \p Self.
+/// If the value is copied from another stack location, \p isCopied is set to
+/// true.
 static SILInstruction *findInitExistential(FullApplySite AI, SILValue Self,
                                            ArchetypeType *&OpenedArchetype,
-                                           SILValue &OpenedArchetypeDef) {
+                                           SILValue &OpenedArchetypeDef,
+                                           bool &isCopied) {
+  isCopied = false;
   if (auto *Instance = dyn_cast<AllocStackInst>(Self)) {
     // In case the Self operand is an alloc_stack where a copy_addr copies the
     // result of an open_existential_addr to this stack location.
-    if (SILValue Src = getAddressOfStackInit(Instance, AI.getInstruction()))
+    if (SILValue Src = getAddressOfStackInit(Instance, AI.getInstruction(),
+                                             isCopied))
       Self = Src;
   }
 
@@ -637,7 +657,7 @@
     if (!ASI)
       return nullptr;
 
-    SILValue StackWrite = getAddressOfStackInit(ASI, Open);
+    SILValue StackWrite = getAddressOfStackInit(ASI, Open, isCopied);
     if (!StackWrite)
       return nullptr;
 
@@ -843,8 +863,10 @@
   // determine a concrete type of the self.
   ArchetypeType *OpenedArchetype = nullptr;
   SILValue OpenedArchetypeDef;
+  bool isCopied = false;
   SILInstruction *InitExistential =
-    findInitExistential(AI, Self, OpenedArchetype, OpenedArchetypeDef);
+    findInitExistential(AI, Self, OpenedArchetype, OpenedArchetypeDef,
+                        isCopied);
   if (!InitExistential)
     return nullptr;
 
@@ -878,6 +900,18 @@
   // Propagate the concrete type into the callee-operand if required.
   Propagate(ConcreteType, Conformance);
 
+  if (isCopied) {
+    // If the witness method is mutating self, we cannot replace self with
+    // the source of a copy. Otherwise the call would modify another value than
+    // the original self.
+    switch (AI.getArgumentConvention(AI.getNumArguments() - 1)) {
+      case SILArgumentConvention::ConventionType::Indirect_Inout:
+      case SILArgumentConvention::ConventionType::Indirect_InoutAliasable:
+        return nullptr;
+      default:
+        break;
+    }
+  }
   // Create a new apply instruction that uses the concrete type instead
   // of the existential type.
   auto *NewAI = createApplyWithConcreteType(AI, NewSelf, Self, ConcreteType,
diff --git a/lib/SILOptimizer/Transforms/SimplifyCFG.cpp b/lib/SILOptimizer/Transforms/SimplifyCFG.cpp
index acb568d..f719fdc 100644
--- a/lib/SILOptimizer/Transforms/SimplifyCFG.cpp
+++ b/lib/SILOptimizer/Transforms/SimplifyCFG.cpp
@@ -67,10 +67,9 @@
     llvm::SmallDenseMap<SILBasicBlock*, unsigned, 32> WorklistMap;
     // Keep track of loop headers - we don't want to jump-thread through them.
     SmallPtrSet<SILBasicBlock *, 32> LoopHeaders;
-    // The number of times jump threading was done through a switch_enum in
-    // a loop header. Used to limit that to prevent an infinite jump threading
-    // loop.
-    llvm::SmallDenseMap<SILBasicBlock*, unsigned, 8> JumpThreadedLoopHeaders;
+    // The number of times jump threading was done through a block.
+    // Used to prevent infinite jump threading loops.
+    llvm::SmallDenseMap<SILBasicBlock*, unsigned, 8> JumpThreadedBlocks;
 
     // Dominance and post-dominance info for the current function
     DominanceInfo *DT = nullptr;
@@ -1009,15 +1008,14 @@
   if (DestIsLoopHeader) {
     if (!isa<SwitchEnumInst>(DestBB->getTerminator()))
       return false;
-
-    // Limit the number we jump-thread through an switch_enum loop header.
-    // In case the CFG contains an infinite loop through such a header we
-    // otherwise may end up with jump-threading indefinitely.
-    unsigned &NumThreaded = JumpThreadedLoopHeaders[DestBB];
-    if (++NumThreaded > 8)
-      return false;
   }
 
+  // Limit the number we jump-thread through a block.
+  // Otherwise we may end up with jump-threading indefinitely.
+  unsigned &NumThreaded = JumpThreadedBlocks[DestBB];
+  if (++NumThreaded > 16)
+    return false;
+
   DEBUG(llvm::dbgs() << "jump thread from bb" << SrcBB->getDebugID() <<
         " to bb" << DestBB->getDebugID() << '\n');
 
diff --git a/lib/Sema/CSDiag.cpp b/lib/Sema/CSDiag.cpp
index 27c281b..85d3cc1 100644
--- a/lib/Sema/CSDiag.cpp
+++ b/lib/Sema/CSDiag.cpp
@@ -6034,11 +6034,15 @@
 
   auto result = TC.checkGenericArguments(
       dc, callExpr->getLoc(), fnExpr->getLoc(), AFD->getInterfaceType(),
-      env->getGenericSignature(), QueryTypeSubstitutionMap{substitutions},
+      env->getGenericSignature(), substitutionFn,
       LookUpConformanceInModule{dc->getParentModule()}, nullptr,
       ConformanceCheckFlags::SuppressDependencyTracking, &genericReqListener);
 
-  return result != RequirementCheckResult::Success;
+  assert(result != RequirementCheckResult::UnsatisfiedDependency);
+
+  // Note: If result is RequirementCheckResult::SubstitutionFailure, we did
+  // not emit a diagnostic, so we must return false in that case.
+  return result == RequirementCheckResult::Failure;
 }
 
 /// When initializing Unsafe[Mutable]Pointer<T> from Unsafe[Mutable]RawPointer,
diff --git a/stdlib/public/SDK/ARKit/ARKit.swift b/stdlib/public/SDK/ARKit/ARKit.swift
index 47863e6..a2baa6a 100644
--- a/stdlib/public/SDK/ARKit/ARKit.swift
+++ b/stdlib/public/SDK/ARKit/ARKit.swift
@@ -78,3 +78,30 @@
         return Array(buffer)
     }
 }
+
+@available(iOS, introduced: 11.0)
+extension ARFaceGeometry {
+    /**
+     The mesh vertices of the geometry.
+     */
+    @nonobjc public var vertices: [vector_float3] {
+        let buffer = UnsafeBufferPointer(start: __vertices, count: Int(__vertexCount))
+        return Array(buffer)
+    }
+
+    /**
+     The texture coordinates of the geometry.
+     */
+    @nonobjc public var textureCoordinates: [vector_float2] {
+        let buffer = UnsafeBufferPointer(start: __textureCoordinates, count: Int(__textureCoordinateCount))
+        return Array(buffer)
+    }
+
+    /**
+     The triangle indices of the geometry.
+     */
+    @nonobjc public var triangleIndices: [Int16] {
+        let buffer = UnsafeBufferPointer(start: __triangleIndices, count: Int(triangleCount * 3))
+        return Array(buffer)
+    }
+}
diff --git a/stdlib/public/SDK/Accelerate/CMakeLists.txt b/stdlib/public/SDK/Accelerate/CMakeLists.txt
index 2ad8736..fe4cdfa 100644
--- a/stdlib/public/SDK/Accelerate/CMakeLists.txt
+++ b/stdlib/public/SDK/Accelerate/CMakeLists.txt
@@ -5,9 +5,10 @@
   LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
   TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
   SWIFT_COMPILE_FLAGS ${STDLIB_SIL_SERIALIZE_ALL} -parse-stdlib
-  SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit ObjectiveC os XPC # auto-updated
-  SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC os # auto-updated
-  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC os # auto-updated
+  SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit Metal ObjectiveC XPC # auto-updated
+    os
+  SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation Metal ObjectiveC os # auto-updated
+  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation Metal ObjectiveC os # auto-updated
   SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreFoundation CoreGraphics Dispatch ObjectiveC os # auto-updated
 
   DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_OSX}
diff --git a/stdlib/public/SDK/CMakeLists.txt b/stdlib/public/SDK/CMakeLists.txt
index eb0cb2c..aad77ac 100644
--- a/stdlib/public/SDK/CMakeLists.txt
+++ b/stdlib/public/SDK/CMakeLists.txt
@@ -10,7 +10,7 @@
 
 list(APPEND SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS "${STDLIB_SIL_SERIALIZE_WITNESS_TABLES}")
 
-set(all_overlays "Accelerate;AppKit;ARKit;AssetsLibrary;AVFoundation;CallKit;CloudKit;Contacts;CoreAudio;CoreData;CoreFoundation;CoreGraphics;CoreImage;CoreLocation;CoreMedia;CryptoTokenKit;Dispatch;Foundation;GameplayKit;GLKit;HomeKit;IOKit;Intents;MapKit;MediaPlayer;ModelIO;ObjectiveC;OpenCL;os;Photos;QuartzCore;SafariServices;SceneKit;simd;SpriteKit;UIKit;Vision;WatchKit;XCTest;XPC")
+set(all_overlays "Accelerate;AppKit;ARKit;AssetsLibrary;AVFoundation;CallKit;CloudKit;Contacts;CoreAudio;CoreData;CoreFoundation;CoreGraphics;CoreImage;CoreLocation;CoreMedia;CryptoTokenKit;Dispatch;Foundation;GameplayKit;GLKit;HomeKit;IOKit;Intents;MapKit;MediaPlayer;Metal;MetalKit;ModelIO;ObjectiveC;OpenCL;os;Photos;QuartzCore;SafariServices;SceneKit;simd;SpriteKit;UIKit;Vision;WatchKit;XCTest;XPC")
 
 if(DEFINED SWIFT_OVERLAY_TARGETS)
   set(overlays_to_build ${SWIFT_OVERLAY_TARGETS})
diff --git a/stdlib/public/SDK/CoreImage/CMakeLists.txt b/stdlib/public/SDK/CoreImage/CMakeLists.txt
index 0d6deee..2fe1a7c 100644
--- a/stdlib/public/SDK/CoreImage/CMakeLists.txt
+++ b/stdlib/public/SDK/CoreImage/CMakeLists.txt
@@ -7,9 +7,9 @@
   SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
   LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
   TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
-  SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit ObjectiveC XPC # auto-updated
-  SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
-  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
+  SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit Metal ObjectiveC XPC # auto-updated
+  SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation Metal ObjectiveC # auto-updated
+  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation Metal ObjectiveC # auto-updated
   FRAMEWORK_DEPENDS_OSX QuartzCore
   FRAMEWORK_DEPENDS_IOS_TVOS CoreImage
 
diff --git a/stdlib/public/SDK/CoreMedia/CMakeLists.txt b/stdlib/public/SDK/CoreMedia/CMakeLists.txt
index c848124..4a6f013 100644
--- a/stdlib/public/SDK/CoreMedia/CMakeLists.txt
+++ b/stdlib/public/SDK/CoreMedia/CMakeLists.txt
@@ -8,9 +8,9 @@
   SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
   LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
   TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
-  SWIFT_MODULE_DEPENDS_OSX Darwin AppKit CoreAudio CoreData CoreGraphics CoreImage Dispatch Foundation IOKit ObjectiveC QuartzCore XPC # auto-updated
-  SWIFT_MODULE_DEPENDS_IOS Darwin CoreAudio CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
-  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreAudio CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
+  SWIFT_MODULE_DEPENDS_OSX Darwin AppKit CoreAudio CoreData CoreGraphics CoreImage Dispatch Foundation IOKit Metal ObjectiveC QuartzCore XPC # auto-updated
+  SWIFT_MODULE_DEPENDS_IOS Darwin CoreAudio CoreGraphics Dispatch Foundation Metal ObjectiveC # auto-updated
+  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreAudio CoreGraphics Dispatch Foundation Metal ObjectiveC # auto-updated
   FRAMEWORK_DEPENDS CoreMedia
 
   DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_COREMEDIA_OSX}
diff --git a/stdlib/public/SDK/MediaPlayer/CMakeLists.txt b/stdlib/public/SDK/MediaPlayer/CMakeLists.txt
index 8334da5..8d28d4d 100644
--- a/stdlib/public/SDK/MediaPlayer/CMakeLists.txt
+++ b/stdlib/public/SDK/MediaPlayer/CMakeLists.txt
@@ -8,7 +8,7 @@
   LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
   TARGET_SDKS IOS IOS_SIMULATOR
 
-  SWIFT_MODULE_DEPENDS_IOS Darwin AVFoundation CoreAudio CoreFoundation CoreGraphics CoreImage CoreMedia Dispatch Foundation ObjectiveC QuartzCore simd UIKit os CoreData # auto-updated
+  SWIFT_MODULE_DEPENDS_IOS Darwin AVFoundation CoreAudio CoreFoundation CoreGraphics CoreImage CoreMedia Dispatch Foundation Metal ObjectiveC QuartzCore simd UIKit os CoreData # auto-updated
   FRAMEWORK_DEPENDS_WEAK MediaPlayer
 
   DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_MEDIAPLAYER_IOS}
diff --git a/stdlib/public/SDK/Metal/CMakeLists.txt b/stdlib/public/SDK/Metal/CMakeLists.txt
new file mode 100644
index 0000000..f3fe951
--- /dev/null
+++ b/stdlib/public/SDK/Metal/CMakeLists.txt
@@ -0,0 +1,22 @@
+cmake_minimum_required(VERSION 3.4.3)
+include("../../../../cmake/modules/StandaloneOverlay.cmake")
+
+add_swift_library(swiftMetal ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY
+    Metal.swift
+
+  SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
+  LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
+  TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
+  SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit ObjectiveC XPC # auto-updated
+    os
+  SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation Dispatch Foundation ObjectiveC # auto-updated
+    os
+  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation Dispatch Foundation ObjectiveC # auto-updated
+    os
+
+  FRAMEWORK_DEPENDS_WEAK Metal
+
+  DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_METAL_OSX}
+  DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_METAL_IOS}
+  DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_METAL_TVOS}
+)
diff --git a/stdlib/public/SDK/Metal/Metal.swift b/stdlib/public/SDK/Metal/Metal.swift
new file mode 100644
index 0000000..802e902
--- /dev/null
+++ b/stdlib/public/SDK/Metal/Metal.swift
@@ -0,0 +1,231 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+
+@_exported import Metal // Clang module
+
+@available(swift 4)
+@available(macOS 10.11, iOS 8.0, tvOS 8.0, *)
+extension MTLBlitCommandEncoder {
+    
+    public func fill(buffer: MTLBuffer, range: Range<Int>, value: UInt8) {
+        fill(buffer: buffer, range: NSMakeRange(range.lowerBound, range.count), value: value)
+    }
+}
+
+@available(swift 4)
+@available(macOS 10.11, iOS 8.0, tvOS 8.0, *)
+extension MTLBuffer {
+    
+#if os(OSX)
+    @available(macOS, introduced: 10.11)
+    public func didModifyRange(_ range: Range<Int>) {
+        didModifyRange(NSMakeRange(range.lowerBound, range.count))
+    }
+#endif
+    
+    @available(macOS 10.12, iOS 10.0, tvOS 10.0, *)
+    public func addDebugMarker(_ marker: String, range: Range<Int>) {
+        addDebugMarker(marker, range: NSMakeRange(range.lowerBound, range.count))
+    }
+}
+
+@available(swift 4)
+@available(macOS 10.11, iOS 8.0, tvOS 8.0, *)
+extension MTLComputeCommandEncoder {
+    
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, *)
+    public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) {
+        useResources(resources, count: resources.count, usage: usage)
+    }
+    
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, *)
+    public func useHeaps(_ heaps: [MTLHeap]) {
+        useHeaps(heaps, count: heaps.count)
+    }
+    
+    public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) {
+        setBuffers(buffers, offsets: offsets, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setTextures(_ textures: [MTLTexture?], range: Range<Int>) {
+        setTextures(textures, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) {
+        setSamplerStates(samplers, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) {
+        setSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSMakeRange(range.lowerBound, range.count))
+    }
+}
+
+@available(swift 4)
+@available(macOS 10.11, iOS 8.0, tvOS 8.0, *)
+extension MTLDevice {
+    
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, *)
+    public func getDefaultSamplePositions(sampleCount: Int) -> [MTLSamplePosition] {
+        var positions = [MTLSamplePosition](repeating: MTLSamplePosition(x: 0,y: 0), count: sampleCount)
+        getDefaultSamplePositions(&positions, count: sampleCount)
+        return positions
+    }
+}
+
+#if os(OSX)
+@available(swift 4)
+@available(macOS 10.13, *)
+public func MTLCopyAllDevicesWithObserver(handler: @escaping MTLDeviceNotificationHandler) -> (devices:[MTLDevice], observer:NSObject) {
+    var resultTuple: (devices:[MTLDevice], observer:NSObject)
+    resultTuple.observer = NSObject()
+    resultTuple.devices = MTLCopyAllDevicesWithObserver(AutoreleasingUnsafeMutablePointer<NSObjectProtocol?>(&resultTuple.observer), handler)
+    return resultTuple
+}
+#endif
+
+@available(swift 4)
+@available(macOS 10.12, iOS 10.0, tvOS 10.0, *)
+extension MTLFunctionConstantValues {
+    
+    public func setConstantValues(_ values: UnsafeRawPointer, type: MTLDataType, range: Range<Int>) {
+        setConstantValues(values, type: type, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+}
+
+@available(swift 4)
+@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)
+extension MTLArgumentEncoder {
+    
+    public func setBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) {
+        setBuffers(buffers, offsets: offsets, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setTextures(_ textures: [MTLTexture?], range: Range<Int>) {
+        setTextures(textures, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) {
+        setSamplerStates(samplers, with: NSMakeRange(range.lowerBound, range.count))
+    }
+}
+
+@available(swift 4)
+@available(macOS 10.11, iOS 8.0, tvOS 8.0, *)
+extension MTLRenderCommandEncoder {
+    
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, *)
+    public func useResources(_ resources: [MTLResource], usage: MTLResourceUsage) {
+        useResources(resources, count: resources.count, usage: usage)
+    }
+    
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, *)
+    public func useHeaps(_ heaps: [MTLHeap]) {
+        useHeaps(heaps, count: heaps.count)
+    }
+    
+#if os(OSX)
+    @available(macOS 10.13, *)
+    public func setViewports(_ viewports: [MTLViewport]) {
+        setViewports(viewports, count: viewports.count)
+    }
+    
+    @available(macOS 10.13, *)
+    public func setScissorRects(_ scissorRects: [MTLScissorRect]) {
+        setScissorRects(scissorRects, count: scissorRects.count)
+    }
+#endif
+    
+    public func setVertexBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) {
+        setVertexBuffers(buffers, offsets: offsets, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setVertexTextures(_ textures: [MTLTexture?], range: Range<Int>) {
+        setVertexTextures(textures, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) {
+        setVertexSamplerStates(samplers, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setVertexSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) {
+        setVertexSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSMakeRange(range.lowerBound, range.count))
+    }
+
+    public func setFragmentBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) {
+        setFragmentBuffers(buffers, offsets: offsets, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setFragmentTextures(_ textures: [MTLTexture?], range: Range<Int>) {
+        setFragmentTextures(textures, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) {
+        setFragmentSamplerStates(samplers, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    public func setFragmentSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) {
+        setFragmentSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSMakeRange(range.lowerBound, range.count))
+    }
+
+#if os(iOS)
+
+    @available(iOS 11.0, *)
+    public func setTileBuffers(_ buffers: [MTLBuffer?], offsets: [Int], range: Range<Int>) {
+        __setTileBuffers(buffers, offsets: offsets, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    @available(iOS 11.0, *)
+    public func setTileTextures(_ textures: [MTLTexture?], range: Range<Int>) {
+        __setTileTextures(textures, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    @available(iOS 11.0, *)
+    public func setTileSamplerStates(_ samplers: [MTLSamplerState?], range: Range<Int>) {
+        __setTileSamplerStates(samplers, with: NSMakeRange(range.lowerBound, range.count))
+    }
+    
+    @available(iOS 11.0, *)
+    public func setTileSamplerStates(_ samplers: [MTLSamplerState?], lodMinClamps: [Float], lodMaxClamps: [Float], range: Range<Int>) {
+        __setTileSamplerStates(samplers, lodMinClamps: lodMinClamps, lodMaxClamps: lodMaxClamps, with: NSMakeRange(range.lowerBound, range.count))
+    }
+#endif
+}
+
+@available(swift 4)
+@available(macOS 10.11, iOS 8.0, tvOS 8.0, *)
+extension MTLRenderPassDescriptor {
+    
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, *)
+    public func setSamplePositions(_ positions: [MTLSamplePosition]) {
+        setSamplePositions(positions, count: positions.count)
+    }
+    
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, *)
+    public func getSamplePositions() -> [MTLSamplePosition] {
+        let numPositions = getSamplePositions(nil, count: 0)
+        var positions = [MTLSamplePosition](repeating: MTLSamplePosition(x: 0,y: 0), count: numPositions)
+        getSamplePositions(&positions, count: numPositions)
+        return positions
+    }
+    
+}
+
+@available(swift 4)
+@available(macOS 10.11, iOS 8.0, tvOS 8.0, *)
+extension MTLTexture {
+    
+    @available(macOS 10.11, iOS 9.0, tvOS 9.0, *)
+    public func makeTextureView(pixelFormat: MTLPixelFormat, textureType: MTLTextureType, levels levelRange: Range<Int>, slices sliceRange: Range<Int>) -> MTLTexture? {
+        return makeTextureView(pixelFormat: pixelFormat, textureType: textureType, levels: NSMakeRange(levelRange.lowerBound, levelRange.count), slices: NSMakeRange(sliceRange.lowerBound, sliceRange.count))
+    }
+}
diff --git a/stdlib/public/SDK/MetalKit/CMakeLists.txt b/stdlib/public/SDK/MetalKit/CMakeLists.txt
new file mode 100644
index 0000000..b0a2013
--- /dev/null
+++ b/stdlib/public/SDK/MetalKit/CMakeLists.txt
@@ -0,0 +1,20 @@
+cmake_minimum_required(VERSION 3.4.3)
+include("../../../../cmake/modules/StandaloneOverlay.cmake")
+
+add_swift_library(swiftMetalKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY
+    MetalKit.swift
+
+  SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
+  LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
+  TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
+  SWIFT_MODULE_DEPENDS_OSX Darwin AppKit CoreData CoreFoundation CoreGraphics CoreImage Dispatch Foundation IOKit Metal ModelIO ObjectiveC QuartzCore simd XPC # auto-updated
+  SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics CoreImage Dispatch Foundation Metal ModelIO ObjectiveC QuartzCore simd UIKit # auto-updated
+  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics CoreImage Dispatch Foundation Metal ModelIO ObjectiveC QuartzCore simd UIKit # auto-updated
+  
+  FRAMEWORK_DEPENDS_WEAK MetalKit
+  FRAMEWORK_DEPENDS_WEAK Metal
+
+  DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_METALKIT_OSX}
+  DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_METALKIT_IOS}
+  DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_METALKIT_TVOS}
+)
diff --git a/stdlib/public/SDK/MetalKit/MetalKit.swift b/stdlib/public/SDK/MetalKit/MetalKit.swift
new file mode 100644
index 0000000..cbbba22
--- /dev/null
+++ b/stdlib/public/SDK/MetalKit/MetalKit.swift
@@ -0,0 +1,46 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+
+@_exported import MetalKit // Clang module
+
+@available(swift 4)
+@available(macOS 10.11, iOS 9.0, tvOS 9.0, *)
+extension MTKMesh {
+    public class func newMeshes(asset: MDLAsset, device: MTLDevice) throws -> (modelIOMeshes: [MDLMesh], metalKitMeshes: [MTKMesh]) {
+        var resultTuple : (modelIOMeshes: [MDLMesh], metalKitMeshes: [MTKMesh])
+        resultTuple.modelIOMeshes = [MDLMesh]()
+        resultTuple.metalKitMeshes = try MTKMesh.newMeshes(from: asset, device: device, sourceMeshes: AutoreleasingUnsafeMutablePointer<NSArray?>(&resultTuple.modelIOMeshes))
+        return resultTuple
+    }
+}
+
+@available(swift 4)
+@available(macOS 10.12, iOS 10.0, tvOS 10.0, *)
+public func MTKModelIOVertexDescriptorFromMetalWithError(_ metalDescriptor: MTLVertexDescriptor) throws -> MDLVertexDescriptor {
+    var error: NSError? = nil
+    let result = MTKModelIOVertexDescriptorFromMetalWithError(metalDescriptor, &error)
+    if let error = error {
+        throw error
+    }
+    return result
+}
+
+@available(swift 4)
+@available(macOS 10.12, iOS 10.0, tvOS 10.0, *)
+public func MTKMetalVertexDescriptorFromModelIOWithError(_ modelIODescriptor: MDLVertexDescriptor) throws -> MTLVertexDescriptor? {
+    var error: NSError? = nil
+    let result = MTKMetalVertexDescriptorFromModelIOWithError(modelIODescriptor, &error)
+    if let error = error {
+        throw error
+    }
+    return result
+}
diff --git a/stdlib/public/SDK/QuartzCore/CMakeLists.txt b/stdlib/public/SDK/QuartzCore/CMakeLists.txt
index 0e08583..43b495e 100644
--- a/stdlib/public/SDK/QuartzCore/CMakeLists.txt
+++ b/stdlib/public/SDK/QuartzCore/CMakeLists.txt
@@ -7,9 +7,9 @@
   SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
   LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
   TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
-  SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics CoreImage Dispatch Foundation IOKit ObjectiveC XPC # auto-updated
-  SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
-  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
+  SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics CoreImage Dispatch Foundation IOKit Metal ObjectiveC XPC # auto-updated
+  SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation Metal ObjectiveC # auto-updated
+  SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation Metal ObjectiveC # auto-updated
   FRAMEWORK_DEPENDS QuartzCore
 
   DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_QUARTZCORE_OSX}
diff --git a/stdlib/public/runtime/SwiftObject.mm b/stdlib/public/runtime/SwiftObject.mm
index b8d2c82..54e3d73 100644
--- a/stdlib/public/runtime/SwiftObject.mm
+++ b/stdlib/public/runtime/SwiftObject.mm
@@ -407,13 +407,16 @@
 
 // Foundation collections expect these to be implemented.
 - (BOOL)isNSArray__      { return NO; }
-- (BOOL)isNSDictionary__ { return NO; }
-- (BOOL)isNSSet__        { return NO; }
-- (BOOL)isNSOrderedSet__ { return NO; }
-- (BOOL)isNSNumber__     { return NO; }
+- (BOOL)isNSCFConstantString__  { return NO; }
 - (BOOL)isNSData__       { return NO; }
 - (BOOL)isNSDate__       { return NO; }
+- (BOOL)isNSDictionary__ { return NO; }
+- (BOOL)isNSObject__     { return NO; }
+- (BOOL)isNSOrderedSet__ { return NO; }
+- (BOOL)isNSNumber__     { return NO; }
+- (BOOL)isNSSet__        { return NO; }
 - (BOOL)isNSString__     { return NO; }
+- (BOOL)isNSTimeZone__   { return NO; }
 - (BOOL)isNSValue__      { return NO; }
 
 @end
diff --git a/test/ClangImporter/Inputs/custom-modules/SubclassExistentialsExtra.h b/test/ClangImporter/Inputs/custom-modules/SubclassExistentialsExtra.h
new file mode 100644
index 0000000..0ff6e95
--- /dev/null
+++ b/test/ClangImporter/Inputs/custom-modules/SubclassExistentialsExtra.h
@@ -0,0 +1,12 @@
+@import Foundation;
+
+@interface SomeSpecificSubclass : NSObject
+@end
+
+typedef NSObject <NSCopying> CopyableNSObjectBase;
+typedef SomeSpecificSubclass <NSCopying> CopyableSpecificBase;
+
+@interface CompositionSubObject : CopyableNSObjectBase
+@end
+@interface CompositionSubSpecific : CopyableSpecificBase
+@end
diff --git a/test/ClangImporter/Inputs/custom-modules/module.map b/test/ClangImporter/Inputs/custom-modules/module.map
index 9177b5c..9b5c8c4 100644
--- a/test/ClangImporter/Inputs/custom-modules/module.map
+++ b/test/ClangImporter/Inputs/custom-modules/module.map
@@ -140,6 +140,11 @@
   export *
 }
 
+module SubclassExistentialsExtra {
+  header "SubclassExistentialsExtra.h"
+  export *
+}
+
 module SwiftPrivateAttr {
   header "SwiftPrivateAttr.h"
 }
diff --git a/test/ClangImporter/subclass_existentials.swift b/test/ClangImporter/subclass_existentials.swift
index 690d30c..15a085f 100644
--- a/test/ClangImporter/subclass_existentials.swift
+++ b/test/ClangImporter/subclass_existentials.swift
@@ -1,8 +1,9 @@
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify -o - -primary-file %s -swift-version 4
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify -o - -primary-file %s -swift-version 4 -I %S/Inputs/custom-modules/
 
 // REQUIRES: objc_interop
 
 import Foundation
+import SubclassExistentialsExtra
 
 class SwiftLaundryService : NSLaundry {
   var g: (Garment & Coat)? = nil
@@ -39,3 +40,12 @@
 // Make sure the method lookup is not ambiguous
 
 _ = Coat.fashionStatement.wear()
+
+
+func testInheritanceFromComposition(_ object: CompositionSubObject, _ specific: CompositionSubSpecific) {
+  let _: NSObject = object
+  let _: NSCopying = object
+
+  let _: SomeSpecificSubclass = specific
+  let _: NSCopying = specific
+}
diff --git a/test/ClangImporter/subclass_existentials_swift3.swift b/test/ClangImporter/subclass_existentials_swift3.swift
index 7b1c955..4e24b33 100644
--- a/test/ClangImporter/subclass_existentials_swift3.swift
+++ b/test/ClangImporter/subclass_existentials_swift3.swift
@@ -1,8 +1,9 @@
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify -o - -primary-file %s -swift-version 3
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify -o - -primary-file %s -swift-version 3 -I %S/Inputs/custom-modules/
 
 // REQUIRES: objc_interop
 
 import Foundation
+import SubclassExistentialsExtra
 
 // FIXME: Consider better diagnostics here.
 
@@ -34,3 +35,11 @@
     return g!
   }
 }
+
+func testInheritanceFromComposition(_ object: CompositionSubObject, _ specific: CompositionSubSpecific) {
+  let _: NSObject = object
+  let _: NSCopying = object
+
+  let _: SomeSpecificSubclass = specific
+  let _: NSCopying = specific
+}
diff --git a/test/Constraints/diagnostics.swift b/test/Constraints/diagnostics.swift
index a0077d5..82724a0 100644
--- a/test/Constraints/diagnostics.swift
+++ b/test/Constraints/diagnostics.swift
@@ -1080,3 +1080,12 @@
 
 func f_31849281(x: Int, y: Int, z: Int) {}
 f_31849281(42, y: 10, x: 20) // expected-error {{argument 'x' must precede unnamed argument #1}} {{12-12=x: 20, }} {{21-28=}}
+
+// https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad
+// generic constraints
+func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {}
+// expected-note@-1 {{in call to function 'elephant'}}
+
+func platypus<T>(a: [T]) {
+    _ = elephant(a) // expected-error {{generic parameter 'U' could not be inferred}}
+}
diff --git a/test/IRGen/Inputs/usr/include/NSOption.h b/test/IRGen/Inputs/usr/include/NSOption.h
new file mode 100644
index 0000000..aec8045
--- /dev/null
+++ b/test/IRGen/Inputs/usr/include/NSOption.h
@@ -0,0 +1,7 @@
+#define CF_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type
+#define NS_OPTIONS(_type, _name) CF_OPTIONS(_type, _name)
+
+typedef NS_OPTIONS(int, SomeOptions) {
+  SomeOptionsFoo = 1,
+  SomeOptionsBar = 2,
+};
diff --git a/test/IRGen/objc_shared_imported_decl.sil b/test/IRGen/objc_shared_imported_decl.sil
new file mode 100644
index 0000000..eab941f
--- /dev/null
+++ b/test/IRGen/objc_shared_imported_decl.sil
@@ -0,0 +1,16 @@
+// RUN: %target-swift-frontend -primary-file %s -import-objc-header %S/Inputs/usr/include/NSOption.h -emit-ir | %FileCheck %s
+
+// REQUIRES: objc_interop
+
+import Swift
+
+sil public @use_witness : $@convention(thin) () -> () {
+  %0 = witness_method $SomeOptions, #Equatable."=="!1 : <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : $@convention(witness_method) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0, @thick τ_0_0.Type) -> Bool
+  %1 = tuple ()
+  return %1: $()
+}
+
+// We used to emit linkonce_odr llvm linkage for this declaration.
+sil_witness_table shared SomeOptions : Equatable module __ObjC
+
+// CHECK: @_T0SC11SomeOptionsVs9EquatableSoWP = external hidden global
diff --git a/test/Migrator/Inputs/API.json b/test/Migrator/Inputs/API.json
index 8749acd..822b318 100644
--- a/test/Migrator/Inputs/API.json
+++ b/test/Migrator/Inputs/API.json
@@ -449,6 +449,17 @@
   {
     "DiffItemKind": "CommonDiffItem",
     "NodeKind": "Function",
+    "NodeAnnotation": "Rename",
+    "ChildIndex": "0",
+    "LeftUsr": "s:6Cities04MoreA0P8addZooAtySi_Si1ySi1ztF",
+    "LeftComment": "",
+    "RightUsr": "",
+    "RightComment": "addNewZooAt(_:newY:newZ:)",
+    "ModuleName": "Cities"
+  },
+  {
+    "DiffItemKind": "CommonDiffItem",
+    "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "1:0",
     "LeftUsr": "s:6CitiesAAC8maroochyySiSg1x_AD1ytF",
diff --git a/test/Migrator/Inputs/Cities.swift b/test/Migrator/Inputs/Cities.swift
index 62da790..76dcf4f 100644
--- a/test/Migrator/Inputs/Cities.swift
+++ b/test/Migrator/Inputs/Cities.swift
@@ -22,6 +22,7 @@
 
 public protocol MoreCities {
   func setZooLocation(x: Int, y: Int, z: Int)
+  func addZooAt(_ x: Int, y: Int, z: Int)
 }
 
 public func setCityProperty1(_ c : Cities, _ p : Int) {}
diff --git a/test/Migrator/rename-func-decl.swift b/test/Migrator/rename-func-decl.swift
index 5d4c25a..fef4e79 100644
--- a/test/Migrator/rename-func-decl.swift
+++ b/test/Migrator/rename-func-decl.swift
@@ -8,4 +8,5 @@
 
 class MyCities : MoreCities {
   func setZooLocation(x ix: Int, y iy: Int, z iz: Int) {}
+  func addZooAt(_ x: Int, y: Int, z: Int) {}
 }
diff --git a/test/Migrator/rename-func-decl.swift.expected b/test/Migrator/rename-func-decl.swift.expected
index 0b42bc8..ca6796b 100644
--- a/test/Migrator/rename-func-decl.swift.expected
+++ b/test/Migrator/rename-func-decl.swift.expected
@@ -8,4 +8,5 @@
 
 class MyCities : MoreCities {
   func setZooLocationNew(newX ix: Int, newY iy: Int, newZ iz: Int) {}
+  func addNewZooAt(_ x: Int, newY y: Int, newZ z: Int) {}
 }
diff --git a/test/SILGen/default_arguments_generic.swift b/test/SILGen/default_arguments_generic.swift
index f311f89..b2909f0 100644
--- a/test/SILGen/default_arguments_generic.swift
+++ b/test/SILGen/default_arguments_generic.swift
@@ -46,3 +46,20 @@
   // CHECK: function_ref @_T025default_arguments_generic7GenericVACyxGxcfcfA_ : $@convention(thin) <τ_0_0 where τ_0_0 : Initializable> () -> @out τ_0_0
   // CHECK: apply [[INIT]]<InitializableImpl>({{%.+}}, {{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : Initializable> (@in τ_0_0, @thin Generic<τ_0_0>.Type) -> Generic<τ_0_0>
 } // CHECK: end sil function '_T025default_arguments_generic17testInitializableyyF'
+
+// Local generic functions with default arguments
+
+// CHECK-LABEL: sil hidden @_T025default_arguments_generic5outeryx1t_tlF : $@convention(thin) <T> (@in T) -> ()
+func outer<T>(t: T) {
+  func inner1(x: Int = 0) {}
+
+  // CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outeryx1t_tlF6inner1L_ySi1x_tlFfA_ : $@convention(thin) () -> Int
+  // CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]() : $@convention(thin) () -> Int
+  _ = inner1()
+
+  func inner2(x: Int = 0) { _ = T.self }
+
+  // CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outeryx1t_tlF6inner2L_ySi1x_tlFfA_ : $@convention(thin) <τ_0_0> () -> Int
+  // CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]<T>() : $@convention(thin) <τ_0_0> () -> Int
+  _ = inner2()
+}
diff --git a/test/SILGen/dynamic_self.swift b/test/SILGen/dynamic_self.swift
index 6d8574d..ddd4d18 100644
--- a/test/SILGen/dynamic_self.swift
+++ b/test/SILGen/dynamic_self.swift
@@ -363,6 +363,28 @@
   }
 }
 
+class Generic<T> {
+  // Examples where we have to add a special argument to capture Self's metadata
+  func t1() -> Self {
+    // CHECK-LABEL: sil private @_T012dynamic_self7GenericC2t1ACyxGXDyFAEXDSgycfU_ : $@convention(thin) <T> (@owned <τ_0_0> { var @sil_weak Optional<Generic<τ_0_0>> } <T>, @thick @dynamic_self Generic<T>.Type) -> @owned Optional<Generic<T>>
+    _ = {[weak self] in self }
+    return self
+  }
+
+  func t2() -> Self {
+    // CHECK-LABEL: sil private @_T012dynamic_self7GenericC2t2ACyxGXDyFAEXD_AEXDtycfU_ : $@convention(thin) <T> (@owned (Generic<T>, Generic<T>), @thick @dynamic_self Generic<T>.Type) -> (@owned Generic<T>, @owned Generic<T>)
+    let selves = (self, self)
+    _ = { selves }
+    return self
+  }
+
+  func t3() -> Self {
+    // CHECK-LABEL: sil private @_T012dynamic_self7GenericC2t3ACyxGXDyFAEXDycfU_ : $@convention(thin) <T> (@owned @sil_unowned Generic<T>, @thick @dynamic_self Generic<T>.Type) -> @owned Generic<T> 
+    _ = {[unowned self] in self }
+    return self
+  }
+}
+
 // CHECK-LABEL: sil_witness_table hidden X: P module dynamic_self {
 // CHECK: method #P.f!1: {{.*}} : @_T012dynamic_self1XCAA1PA2aDP1f{{[_0-9a-zA-Z]*}}FTW
 
diff --git a/test/SILOptimizer/array_specialize.sil b/test/SILOptimizer/array_specialize.sil
index c39d77d..fdab0ed 100644
--- a/test/SILOptimizer/array_specialize.sil
+++ b/test/SILOptimizer/array_specialize.sil
@@ -109,3 +109,70 @@
 bb5(%9 : $Error):
   throw %9 : $Error
 }
+
+sil @dominator_update_outside_non_exit_block : $@convention(thin) (@inout MyArray<MyClass>, @inout Builtin.Int1) -> Builtin.Int1 {
+bb0(%0 : $*MyArray<MyClass>, %1 : $*Builtin.Int1):
+  %3 = load %0 : $*MyArray<MyClass>
+  br bb1
+
+bb1:
+  %2 = function_ref @arrayPropertyIsNative : $@convention(method) (@owned MyArray<MyClass>) -> Bool
+  %4 = load %1 : $*Builtin.Int1
+  retain_value %3 : $MyArray<MyClass>
+  %5 = apply %2(%3) : $@convention(method) (@owned MyArray<MyClass>) -> Bool
+  cond_br %4, bb2, bb4
+
+bb2:
+ cond_br undef, bb3, bb5
+
+bb3:
+ %6 = integer_literal $Builtin.Int1, -1
+ cond_br %6, bb1, bb7
+
+bb4: // Exit block; b1 dom b4
+ cond_br undef, bb5, bb6
+
+bb5: // Exit Block; b1 dom b4
+ br bb6
+
+bb6: // Non-exit Dominated by bb1
+ br bb7
+
+bb7:
+  return %4 : $Builtin.Int1
+}
+
+sil @dominator_update_outside_non_exit_block_2 : $@convention(thin) (@inout MyArray<MyClass>, @inout Builtin.Int1) -> Builtin.Int1 {
+bb0(%0 : $*MyArray<MyClass>, %1 : $*Builtin.Int1):
+  %3 = load %0 : $*MyArray<MyClass>
+  br bb1
+
+bb1:
+  %2 = function_ref @arrayPropertyIsNative : $@convention(method) (@owned MyArray<MyClass>) -> Bool
+  %4 = load %1 : $*Builtin.Int1
+  retain_value %3 : $MyArray<MyClass>
+  %5 = apply %2(%3) : $@convention(method) (@owned MyArray<MyClass>) -> Bool
+  cond_br %4, bb2, bb4
+
+bb2:
+ cond_br undef, bb3, bb5
+
+bb3:
+ %6 = integer_literal $Builtin.Int1, -1
+ cond_br %6, bb1, bb7
+
+bb4: // Exit block; b1 dom b4
+ cond_br undef, bb5, bb6
+
+bb5: // Exit Block; b1 dom b4
+ br bb6
+
+bb6: // Non-exit Dominated by bb1
+ br bb8
+
+bb7: // Exit dominated by bb3
+ br bb8
+
+bb8: // Non-exit dominated by bb1
+  return %4 : $Builtin.Int1
+}
diff --git a/test/SILOptimizer/opened_archetype_operands_tracking.sil b/test/SILOptimizer/opened_archetype_operands_tracking.sil
index 5e9d3ae..2226f1b 100644
--- a/test/SILOptimizer/opened_archetype_operands_tracking.sil
+++ b/test/SILOptimizer/opened_archetype_operands_tracking.sil
@@ -1,4 +1,5 @@
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -sil-inline-generics -enable-sil-verify-all %s -O | %FileCheck %s
+// RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -simplify-cfg -enable-sil-verify-all %s -O | %FileCheck --check-prefix=CHECK-SIMPLIFY-CFG %s
 
 // Check some corner cases related to tracking of opened archetypes.
 // For example, the compiler used to crash compiling the "process" function (rdar://28024272)
@@ -262,3 +263,53 @@
   return %8 : $()
 } // end sil function 'check_removal_of_unregistered_archetype_def'
 
+// Check that even in case of unreacheable blocks the compiler does not hang
+// in SILBuilder::addOpenedArchetypeOperands. rdar://problem/34602036
+
+enum MyOptional<T> {
+  case none
+  case some(T)
+}
+
+class C {
+  var this : MyOptional<C>
+  init()
+}
+
+// CHECK-SIMPLIFY-CFG-LABEL: sil @test_infinite_loop_in_unreachable_block
+// CHECK-SIMPLIFY-CFG: bb0
+// CHECK-SIMPLIFY-CFG-NOT: bb1
+// CHECK-SIMPLIFY-CFG: end sil function 'test_infinite_loop_in_unreachable_block'
+sil @test_infinite_loop_in_unreachable_block : $@convention(method) (@guaranteed C) -> () {
+bb0(%0 : $C):
+  %1 = enum $MyOptional<C>, #MyOptional.some!enumelt.1, %0 : $C
+  %2 = integer_literal $Builtin.Int64, 0 
+  strong_retain %0 : $C
+  release_value %1 : $MyOptional<C>
+  %6 = integer_literal $Builtin.Int1, -1
+  cond_br %6, bb5, bb1
+
+bb1:
+  %8 = enum $MyOptional<C>, #MyOptional.some!enumelt.1, %0 : $C
+  strong_retain %0 : $C
+  br bb2(%8 : $MyOptional<C>)
+
+bb2(%11 : $MyOptional<C>):
+  %12 = unchecked_enum_data %11 : $MyOptional<C>, #MyOptional.some!enumelt.1
+  %13 = ref_element_addr %12 : $C, #C.this
+  %14 = load %13 : $*MyOptional<C>
+  switch_enum %14 : $MyOptional<C>, case #MyOptional.some!enumelt.1: bb3, case #MyOptional.none!enumelt: bb4
+
+bb3(%16 : $C):
+  retain_value %14 : $MyOptional<C>
+  release_value %11 : $MyOptional<C>
+  br bb2(%14 : $MyOptional<C>)
+
+bb4:
+  release_value %11 : $MyOptional<C>
+  br bb5
+
+bb5:
+  %22 = tuple ()
+  return %22 : $()
+} // end sil function 'test_infinite_loop_in_unreachable_block'
diff --git a/test/SILOptimizer/sil_combine.sil b/test/SILOptimizer/sil_combine.sil
index 38343bc..7824a85 100644
--- a/test/SILOptimizer/sil_combine.sil
+++ b/test/SILOptimizer/sil_combine.sil
@@ -1215,6 +1215,52 @@
   return %6 : $()
 }
 
+// Check that convert_function simplifications are not applied in certain cases.
+@objc class MyNSObj { }
+
+class AnotherClass : MyNSObj { }
+
+sil @MyNSObj_self : $@convention(method) (@guaranteed MyNSObj) -> @owned MyNSObj
+
+sil shared [transparent] [serializable] [reabstraction_thunk] @reabstraction_thunk1 : $@convention(thin) (@in (), @owned @callee_owned () -> @owned AnotherClass) -> @out AnotherClass {
+bb0(%0 : $*AnotherClass, %1 : $*(), %2 : $@callee_owned () -> @owned AnotherClass):
+  %3 = apply %2() : $@callee_owned () -> @owned AnotherClass
+  store %3 to %0 : $*AnotherClass
+  %5 = tuple ()
+  return %5 : $()
+}
+
+// @nonobjc curry thunk of MyNSObj.self()
+sil shared [serializable] [thunk] @curry_thunk_for_MyNSObj_self : $@convention(thin) (@owned MyNSObj) -> @owned @callee_owned () -> @owned MyNSObj {
+bb0(%0 : $MyNSObj):
+  // function_ref @nonobjc MyNSObj.self()
+  %1 = function_ref @MyNSObj_self : $@convention(method) (@guaranteed MyNSObj) -> @owned MyNSObj
+  %2 = partial_apply %1(%0) : $@convention(method) (@guaranteed MyNSObj) -> @owned MyNSObj
+  return %2 : $@callee_owned () -> @owned MyNSObj
+}
+
+// Check that convert_function is not eliminated if the result type of the converted function is different from the apply result type.
+// CHECK-LABEL: sil {{.*}} @do_not_peephole_convert_function : $@convention(thin) (@in AnotherClass) -> @out @callee_owned (@in ()) -> @out AnotherClass {
+// CHECK: [[CF:%[0-9]+]] = convert_function
+// CHECK: [[APPLY:%[0-9]+]] = apply
+// CHECK: [[FUN:%[0-9]+]] = function_ref
+// CHECK: [[CF:%[0-9]+]] = partial_apply [[FUN]]([[APPLY]])
+// CHECK: // end sil function 'do_not_peephole_convert_function'
+sil shared [transparent] [reabstraction_thunk] @do_not_peephole_convert_function : $@convention(thin) (@in AnotherClass) -> @out @callee_owned (@in ()) -> @out AnotherClass {
+bb0(%0 : $*@callee_owned (@in ()) -> @out AnotherClass, %1 : $*AnotherClass):
+  // function_ref @nonobjc curry thunk of MyNSObj.self()
+  %2 = function_ref @curry_thunk_for_MyNSObj_self : $@convention(thin) (@owned MyNSObj) -> @owned @callee_owned () -> @owned MyNSObj
+  %3 = convert_function %2 : $@convention(thin) (@owned MyNSObj) -> @owned @callee_owned () -> @owned MyNSObj to $@convention(thin) (@owned AnotherClass) -> @owned @callee_owned () -> @owned AnotherClass
+  %5 = load %1 : $*AnotherClass
+  %6 = apply %3(%5) : $@convention(thin) (@owned AnotherClass) -> @owned @callee_owned () -> @owned AnotherClass
+  // function_ref thunk for @callee_owned () -> (@owned AnotherClass)
+  %7 = function_ref @reabstraction_thunk1 : $@convention(thin) (@in (), @owned @callee_owned () -> @owned AnotherClass) -> @out AnotherClass
+  %8 = partial_apply %7(%6) : $@convention(thin) (@in (), @owned @callee_owned () -> @owned AnotherClass) -> @out AnotherClass
+  store %8 to %0 : $*@callee_owned (@in ()) -> @out AnotherClass
+  %10 = tuple ()
+  return %10 : $()
+} // end sil function 'do_not_peephole_convert_function'
+
 // CHECK-LABEL: sil @upcast_formation : $@convention(thin) (@inout E, E, @inout B) -> B {
 // CHECK: bb0
 // CHECK-NEXT: upcast
diff --git a/test/SILOptimizer/sil_combine_apply.sil b/test/SILOptimizer/sil_combine_apply.sil
index 2bf1e6f..cd09acd 100644
--- a/test/SILOptimizer/sil_combine_apply.sil
+++ b/test/SILOptimizer/sil_combine_apply.sil
@@ -308,4 +308,38 @@
   %4 = apply %3() : $@callee_owned () -> ()
   %9999 = tuple()
   return %9999 : $()
-}
\ No newline at end of file
+}
+
+protocol MutatingProto {
+    mutating func mutatingMethod()
+}
+
+struct MStruct : MutatingProto { 
+
+    var somevar: Builtin.Int32
+
+    mutating func mutatingMethod()
+}
+
+// CHECK-LABEL: sil @dont_replace_copied_self_in_mutating_method_call
+sil @dont_replace_copied_self_in_mutating_method_call : $@convention(thin) (MStruct) -> (@out MutatingProto) {
+bb0(%0 : $*MutatingProto, %1 : $MStruct):
+  %2 = alloc_stack $MutatingProto
+  %4 = init_existential_addr %2 : $*MutatingProto, $MStruct
+  store %1 to %4 : $*MStruct
+  %9 = alloc_stack $MutatingProto
+  copy_addr %2 to [initialization] %9 : $*MutatingProto
+  // CHECK: [[E:%[0-9]+]] = open_existential_addr
+  %11 = open_existential_addr mutable_access %9 : $*MutatingProto to $*@opened("FC5F3CFA-A7A4-11E7-911F-685B35C48C83") MutatingProto
+  // CHECK: [[M:%[0-9]+]] = witness_method $MStruct,
+  %12 = witness_method $@opened("FC5F3CFA-A7A4-11E7-911F-685B35C48C83") MutatingProto, #MutatingProto.mutatingMethod!1 : <Self where Self : MutatingProto> (inout Self) -> () -> (), %11 : $*@opened("FC5F3CFA-A7A4-11E7-911F-685B35C48C83") MutatingProto : $@convention(witness_method) <τ_0_0 where τ_0_0 : MutatingProto> (@inout τ_0_0) -> ()
+  // CHECK: apply [[M]]<@opened("{{.*}}") MutatingProto>([[E]]) :
+  %13 = apply %12<@opened("FC5F3CFA-A7A4-11E7-911F-685B35C48C83") MutatingProto>(%11) : $@convention(witness_method) <τ_0_0 where τ_0_0 : MutatingProto> (@inout τ_0_0) -> ()
+  copy_addr [take] %9 to [initialization] %0 : $*MutatingProto
+  dealloc_stack %9 : $*MutatingProto
+  destroy_addr %2 : $*MutatingProto
+  dealloc_stack %2 : $*MutatingProto
+  %27 = tuple ()
+  return %27 : $()
+}
+
diff --git a/test/SILOptimizer/simplify_cfg_jump_thread_crash.sil b/test/SILOptimizer/simplify_cfg_jump_thread_crash.sil
index d9c7a68..c38ac1d 100644
--- a/test/SILOptimizer/simplify_cfg_jump_thread_crash.sil
+++ b/test/SILOptimizer/simplify_cfg_jump_thread_crash.sil
@@ -107,3 +107,51 @@
   return %65 : $()
 }
 
+sil @some_function : $@convention(thin) (AA) -> Optional<AA>
+
+// Another test for checking that SimplifyCFG does not hang.
+// CHECK-LABEL: test_other_infinite_loop
+sil hidden @test_other_infinite_loop : $@convention(method) (@owned AA) -> () {
+bb0(%5 : $AA):
+  strong_retain %5 : $AA
+  %6 = enum $Optional<AA>, #Optional.some!enumelt.1, %5 : $AA
+  br bb1(%6 : $Optional<AA>)
+
+bb1(%8 : $Optional<AA>):
+  retain_value %8 : $Optional<AA>
+  switch_enum %8 : $Optional<AA>, case #Optional.some!enumelt.1: bb3, default bb2
+
+bb2:
+  release_value %8 : $Optional<AA>
+  br bb6
+
+bb3:
+  cond_br undef, bb4, bb5
+
+bb4:
+  %85 = tuple ()
+  return %85 : $()
+
+bb5:
+  br bb6
+
+bb6:
+  switch_enum %8 : $Optional<AA>, case #Optional.none!enumelt: bb7, default bb8
+
+bb7:
+  br bb9(%8 : $Optional<AA>)
+
+bb8:
+  %23 = unchecked_enum_data %8 : $Optional<AA>, #Optional.some!enumelt.1
+  strong_retain %23 : $AA
+  %25 = function_ref @some_function : $@convention(thin) (AA) -> Optional<AA>
+  %26 = apply %25(%23) : $@convention(thin) (AA) -> Optional<AA>
+  strong_release %23 : $AA
+  br bb9(%26 : $Optional<AA>)
+
+bb9(%29 : $Optional<AA>):
+  release_value %8 : $Optional<AA>
+  br bb1(%29 : $Optional<AA>)
+
+}
+
diff --git a/test/lit.cfg b/test/lit.cfg
index 33a5680..f29b64e 100644
--- a/test/lit.cfg
+++ b/test/lit.cfg
@@ -100,7 +100,7 @@
         else:
             return "simctl spawn 'iPhone 6'"
     elif run_os == 'tvos':
-        return "simctl spawn 'Apple TV 1080p'"
+        return "simctl spawn 'Apple TV 4K'"
     elif run_os == 'watchos':
         return "simctl spawn 'Apple Watch - 42mm'"
     else:
diff --git a/test/stdlib/Inputs/SwiftObjectNSObject/SwiftObjectNSObject.m b/test/stdlib/Inputs/SwiftObjectNSObject/SwiftObjectNSObject.m
index a99fd9e..170ee43 100644
--- a/test/stdlib/Inputs/SwiftObjectNSObject/SwiftObjectNSObject.m
+++ b/test/stdlib/Inputs/SwiftObjectNSObject/SwiftObjectNSObject.m
@@ -405,6 +405,12 @@
   expectTrue ([[C_meta description] isEqual:@"SwiftObjectNSObject.C"]);
   expectTrue ([[S_meta description] isEqual:@"SwiftObject"]);
 
+  // NSLog() calls -description and also some private methods.
+  // This output is checked by FileCheck in SwiftObjectNSObject.swift.
+  NSLog(@"c ##%@##", c);
+  NSLog(@"d ##%@##", d);
+  NSLog(@"S ##%@##", S);
+
 
   printf("NSObjectProtocol.debugDescription\n");
 
diff --git a/test/stdlib/Metal.swift b/test/stdlib/Metal.swift
new file mode 100644
index 0000000..cbb2b19
--- /dev/null
+++ b/test/stdlib/Metal.swift
@@ -0,0 +1,243 @@
+// RUN: rm -rf %t ; mkdir -p %t
+// RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-run %t/a.out4
+// REQUIRES: objc_interop
+// UNSUPPORTED: OS=watchos
+
+import StdlibUnittest
+
+import Metal
+
+var MetalTests = TestSuite("Metal")
+
+if #available(OSX 10.13, iOS 11.0, tvOS 11.0, *) {
+
+  // Call each overlay to ensure nothing explodes
+
+  MetalTests.test("MTLArgumentEncoder") {
+    func apiAvailabilityTest() {
+      /* Setup */
+
+      let device = MTLCreateSystemDefaultDevice()!
+      let buf = device.makeBuffer(
+        length: 64, options: MTLResourceOptions.storageModeShared)!
+      let texDesc = MTLTextureDescriptor()
+      texDesc.usage = MTLTextureUsage.renderTarget
+      let tex = device.makeTexture(descriptor: texDesc)!
+      let smplr = device.makeSamplerState(descriptor: MTLSamplerDescriptor())
+
+      var arguments = [MTLArgumentDescriptor]()
+      arguments.append(MTLArgumentDescriptor())
+      arguments.append(MTLArgumentDescriptor())
+      arguments.append(MTLArgumentDescriptor())
+      arguments[0].dataType = MTLDataType.pointer
+      arguments[0].index = 0
+      arguments[1].dataType = MTLDataType.texture
+      arguments[1].index = 1
+      arguments[2].dataType = MTLDataType.sampler
+      arguments[2].index = 2
+
+      /* Call APIs */
+
+      let argEncoder = device.makeArgumentEncoder(arguments: arguments)!
+      argEncoder.setArgumentBuffer(buf, offset: 0)
+      argEncoder.setBuffers([buf], offsets: [0], range: 0..<1)
+      argEncoder.setTextures([tex], range: 1..<2)
+      argEncoder.setSamplerStates([smplr], range: 2..<3)
+    }
+  }
+
+  MetalTests.test("MTLBlitCommandEncoder") {
+    func apiAvailabilityTest() {
+
+      /* Setup */
+
+      let device = MTLCreateSystemDefaultDevice()!
+      let queue = device.makeCommandQueue()!
+      let cmdBuf = queue.makeCommandBuffer()!
+      let bltCmdEncdr = cmdBuf.makeBlitCommandEncoder()!
+
+      /* Call APIs */
+
+      let buf = device.makeBuffer(length: 4, options: MTLResourceOptions())!
+      bltCmdEncdr.fill(buffer: buf, range: 0..<buf.length, value: 0)
+      bltCmdEncdr.endEncoding()
+    }
+  }
+
+  MetalTests.test("MTLBuffer") {
+    func apiAvailabilityTest() {
+
+      /* Setup */
+
+      let device = MTLCreateSystemDefaultDevice()!
+      #if os(OSX)
+        let options = MTLResourceOptions.storageModeManaged
+      #else
+        let options = MTLResourceOptions.storageModePrivate
+      #endif
+      let buf = device.makeBuffer(length: 4, options: options)!
+
+      /* Call APIs */
+
+      #if os(OSX)
+        buf.didModifyRange(0..<4)
+      #endif
+      buf.addDebugMarker("test marker", range: 0..<4)
+    }
+  }
+
+  MetalTests.test("MTLComputeCommandEncoder") {
+    func apiAvailabilityTest(heapDesc: MTLHeapDescriptor) {
+
+      /* Setup */
+
+      let device = MTLCreateSystemDefaultDevice()!
+      let queue = device.makeCommandQueue()!
+      let cmdBuf = queue.makeCommandBuffer()!
+
+      #if os(OSX)
+        let options = MTLResourceOptions.storageModeManaged
+      #else
+        let options = MTLResourceOptions.storageModePrivate
+      #endif
+      let buf = device.makeBuffer(length: 4, options: options)!
+      let tex = device.makeTexture(descriptor: MTLTextureDescriptor())!
+      heapDesc.size = 4
+      let heap = device.makeHeap(descriptor: heapDesc)!
+      let smplr = device.makeSamplerState(descriptor: MTLSamplerDescriptor())
+
+      /* Call APIs */
+      
+      let encoder = cmdBuf.makeComputeCommandEncoder()!
+      encoder.useResources([buf], usage: MTLResourceUsage.read)
+      encoder.useHeaps([heap])
+      encoder.setBuffers([buf], offsets: [0], range: 0..<1)
+      encoder.setTextures([tex], range: 0..<1)
+      encoder.setSamplerStates([smplr], range: 0..<1)
+      encoder.setSamplerStates(
+        [smplr], lodMinClamps: [0], lodMaxClamps: [0], range: 0..<1)
+      encoder.endEncoding()
+    }
+  }
+
+  MetalTests.test("MTLDevice") {
+    func apiAvailabilityTest() {
+
+      /* Setup */
+
+      let device = MTLCreateSystemDefaultDevice()!
+
+      /* Call APIs */
+
+      var samplePositions : [MTLSamplePosition]
+      if (device.supportsTextureSampleCount(2)) {
+        samplePositions = device.getDefaultSamplePositions(sampleCount: 2)
+      }
+      else if (device.supportsTextureSampleCount(4)) {
+        samplePositions = device.getDefaultSamplePositions(sampleCount: 4)
+      }
+      else {
+        expectUnreachable("device unexpectedly does not support sample count 2 or 4")
+      }
+    }
+  }
+
+  MetalTests.test("MTLFunctionConstantValues") {
+    func apiAvailabilityTest() {
+
+      /* Call APIs */
+
+      let vals = MTLFunctionConstantValues()
+      vals.setConstantValues([0], type: MTLDataType.float, range: 0..<1)
+    }
+  }
+
+  MetalTests.test("MTLRenderCommandEncoder") {
+    func apiAvailabilityTest(heapDesc: MTLHeapDescriptor) {
+
+      /* Setup */
+      let device = MTLCreateSystemDefaultDevice()!
+      let queue = device.makeCommandQueue()!
+      let cmdBuf = queue.makeCommandBuffer()!
+
+      #if os(OSX)
+        let options = MTLResourceOptions.storageModeManaged
+      #else
+        let options = MTLResourceOptions.storageModePrivate
+      #endif
+      let buf = device.makeBuffer(length: 4, options: options)!
+      let texDesc = MTLTextureDescriptor()
+      texDesc.usage = MTLTextureUsage.renderTarget
+      let tex = device.makeTexture(descriptor: texDesc)!
+      heapDesc.size = 4
+      let heap = device.makeHeap(descriptor: heapDesc)!
+      let smplr = device.makeSamplerState(descriptor: MTLSamplerDescriptor())
+      let rpDesc = MTLRenderPassDescriptor()
+      rpDesc.colorAttachments[0].texture = tex
+
+      /* Call APIs */
+
+      let encoder = cmdBuf.makeRenderCommandEncoder(descriptor: rpDesc)!
+      encoder.useResources([buf], usage: MTLResourceUsage.read)
+      encoder.useHeaps([heap])
+      #if os(OSX)
+        encoder.setViewports([MTLViewport()])
+        encoder.setScissorRects([MTLScissorRect(x:0, y:0, width:1, height:1)])
+      #endif
+      encoder.setVertexBuffers([buf], offsets: [0], range: 0..<1)
+      encoder.setVertexTextures([tex], range: 0..<1)
+      encoder.setVertexSamplerStates([smplr], range: 0..<1)
+      encoder.setVertexSamplerStates(
+        [smplr], lodMinClamps: [0], lodMaxClamps: [0], range: 0..<1)
+      encoder.setFragmentBuffers([buf], offsets: [0], range: 0..<1)
+      encoder.setFragmentTextures([tex], range: 0..<1)
+      encoder.setFragmentSamplerStates([smplr], range: 0..<1)
+      encoder.setFragmentSamplerStates(
+        [smplr], lodMinClamps: [0], lodMaxClamps: [0], range: 0..<1)
+     #if os(iOS)
+         encoder.setTileBuffers([buf], offsets: [0], range: 0..<1)
+         encoder.setTileTextures([tex], range: 0..<1)
+         encoder.setTileSamplerStates([smplr], range: 0..<1)
+         encoder.setTileSamplerStates(
+           [smplr], lodMinClamps: [0], lodMaxClamps: [0], range: 0..<1)
+     #endif
+      encoder.endEncoding()
+    }
+  }
+
+  MetalTests.test("MTLRenderPassDescriptor") {
+    func apiAvailabilityTest() {
+
+      /* Setup */
+
+      let rpDesc = MTLRenderPassDescriptor()
+
+      /* Call APIs */
+
+      rpDesc.setSamplePositions(
+        [MTLSamplePosition(x:0.25,y:0.75), MTLSamplePosition(x:0.75, y:0.25)])
+      _ = rpDesc.getSamplePositions()
+    }
+  }
+
+  MetalTests.test("MTLTexture") {
+    func apiAvailabilityTest() {
+      /* Setup */
+
+      let device = MTLCreateSystemDefaultDevice()!
+      let texDesc = MTLTextureDescriptor()
+      texDesc.usage = MTLTextureUsage.renderTarget
+      let tex = device.makeTexture(descriptor: texDesc)!
+
+      /* Call APIs */
+
+      let _ = tex.makeTextureView(
+        pixelFormat: texDesc.pixelFormat,
+        textureType: texDesc.textureType,
+        levels: 0..<1,
+        slices: 0..<1)
+    }
+  }
+}
+
+runAllTests()
diff --git a/test/stdlib/MetalKit.swift b/test/stdlib/MetalKit.swift
new file mode 100644
index 0000000..223121d
--- /dev/null
+++ b/test/stdlib/MetalKit.swift
@@ -0,0 +1,44 @@
+// RUN: rm -rf %t ; mkdir -p %t
+// RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-run %t/a.out4
+// REQUIRES: objc_interop
+// UNSUPPORTED: OS=watchos
+
+import StdlibUnittest
+
+import Metal
+import MetalKit
+
+var MetalKitTests = TestSuite("MetalKit")
+
+// Call each overlay to ensure nothing explodes
+
+if #available(macOS 10.12, iOS 10.0, tvOS 10.0, *) {
+  MetalKitTests.test("Globals") {
+
+    do {
+      let _ = try MTKModelIOVertexDescriptorFromMetalWithError(MTLVertexDescriptor())
+    } catch _ {
+      expectUnreachable("MTKModelIOVertexDescriptorFromMetalWithError has thrown an unexpected error")
+    }
+
+    do {
+      let _ = try MTKMetalVertexDescriptorFromModelIOWithError(MDLVertexDescriptor())
+    } catch _ {
+      expectUnreachable("MTKMetalVertexDescriptorFromModelIOWithError has thrown an unexpected error")
+    }
+  }
+}
+
+if #available(macOS 10.11, iOS 9.0, tvOS 9.0, *) {
+  MetalKitTests.test("MTKMesh") {
+    func apiAvailabilityTest(device: MTLDevice) {
+      do {
+        let _ = try MTKMesh.newMeshes(asset: MDLAsset(), device: device)
+      } catch _ {
+        expectUnreachable("MTKMesh.newMeshes has thrown an unexpected error")
+      }
+    }
+  }
+}
+
+runAllTests()
diff --git a/test/stdlib/SwiftObjectNSObject.swift b/test/stdlib/SwiftObjectNSObject.swift
index 56f348f..24680a8 100644
--- a/test/stdlib/SwiftObjectNSObject.swift
+++ b/test/stdlib/SwiftObjectNSObject.swift
@@ -14,7 +14,7 @@
 // 
 // RUN: %target-clang %S/Inputs/SwiftObjectNSObject/SwiftObjectNSObject.m -c -o %t/SwiftObjectNSObject.o -g
 // RUN: %target-build-swift %s -I %S/Inputs/SwiftObjectNSObject/ -Xlinker %t/SwiftObjectNSObject.o -o %t/SwiftObjectNSObject
-// RUN: %target-run %t/SwiftObjectNSObject
+// RUN: %target-run %t/SwiftObjectNSObject 2>&1 | %FileCheck %s
 // REQUIRES: executable_test
 
 // REQUIRES: objc_interop
@@ -34,5 +34,10 @@
 @_silgen_name("TestSwiftObjectNSObject") 
 func TestSwiftObjectNSObject(_ c: C, _ d: D)
 
+// This check is for NSLog() output from TestSwiftObjectNSObject().
+// CHECK: c ##SwiftObjectNSObject.C##
+// CHECK-NEXT: d ##SwiftObjectNSObject.D##
+// CHECK-NEXT: S ##SwiftObject##
+
 TestSwiftObjectNSObject(C(), D())
 // does not return
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftEditor.cpp b/tools/SourceKit/lib/SwiftLang/SwiftEditor.cpp
index 776124d..55f8851 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftEditor.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftEditor.cpp
@@ -1590,20 +1590,10 @@
     if (Length != 0 || Buf->getBufferSize() != 0) {
       updateSemaInfo();
 
-      if (auto Invok = Impl.SemanticInfo->getInvocation()) {
-        // Update semantic info for open editor documents of the same module.
-        // FIXME: Detect edits that don't affect other files, e.g. whitespace,
-        // comments, inside a function body, etc.
-        CompilerInvocation CI;
-        Invok->applyTo(CI);
-        auto &EditorDocs = Impl.LangSupport.getEditorDocuments();
-        for (auto &Input : CI.getInputFilenames()) {
-          if (auto EditorDoc = EditorDocs.findByPath(Input)) {
-            if (EditorDoc.get() != this)
-              EditorDoc->updateSemaInfo();
-          }
-        }
-      }
+      // FIXME: we should also update any "interesting" ASTs that depend on this
+      // document here, e.g. any ASTs for files visible in an editor. However,
+      // because our API conflates this with any file with unsaved changes we do
+      // not update all open documents, since there could be too many of them.
     }
   }