From 250082df2521178ca8175d4f40ab2b90e28015fb Mon Sep 17 00:00:00 2001 From: Evan Wilde Date: Tue, 27 Jun 2023 08:15:30 -0700 Subject: [PATCH] [NFC] Reformat all the LLVMs Reformatting everything now that we have `llvm` namespaces. I've separated this from the main commit to help manage merge-conflicts and for making it a bit easier to read the mega-patch. --- .../swift/APIDigester/ModuleAnalyzerNodes.h | 5 +- include/swift/AST/ASTContext.h | 33 +- include/swift/AST/ASTDemangler.h | 29 +- include/swift/AST/ASTMangler.h | 16 +- include/swift/AST/ASTPrinter.h | 23 +- include/swift/AST/ASTScope.h | 2 +- include/swift/AST/ASTWalker.h | 13 +- .../AST/AbstractSourceFileDepGraphFactory.h | 8 +- include/swift/AST/AccessNotes.h | 2 +- include/swift/AST/AccessScope.h | 7 +- include/swift/AST/AnyFunctionRef.h | 10 +- include/swift/AST/ArgumentList.h | 27 +- include/swift/AST/Attr.h | 54 ++-- include/swift/AST/AutoDiff.h | 6 +- include/swift/AST/Availability.h | 4 +- include/swift/AST/Comment.h | 4 +- include/swift/AST/Decl.h | 41 +-- include/swift/AST/DeclContext.h | 2 +- include/swift/AST/DiagnosticConsumer.h | 4 +- include/swift/AST/Expr.h | 4 +- include/swift/AST/ExtInfo.h | 8 +- include/swift/AST/FileUnit.h | 16 +- include/swift/AST/FineGrainedDependencies.h | 26 +- include/swift/AST/ForeignAsyncConvention.h | 49 ++- include/swift/AST/IRGenOptions.h | 3 +- include/swift/AST/IRGenRequests.h | 15 +- include/swift/AST/Import.h | 10 +- include/swift/AST/Module.h | 5 +- include/swift/AST/ModuleDependencies.h | 4 +- include/swift/AST/ModuleLoader.h | 11 +- include/swift/AST/PackConformance.h | 4 +- include/swift/AST/PlatformKind.h | 2 +- include/swift/AST/PrettyStackTrace.h | 12 +- include/swift/AST/ProtocolConformance.h | 29 +- include/swift/AST/ProtocolConformanceRef.h | 25 +- include/swift/AST/Stmt.h | 121 ++++---- include/swift/AST/SubstitutionMap.h | 4 +- include/swift/AST/Type.h | 33 +- include/swift/AST/TypeCheckRequests.h | 51 ++- include/swift/AST/Types.h | 110 +++---- include/swift/AST/Witness.h | 9 +- include/swift/Basic/BlotMapVector.h | 3 +- include/swift/Basic/BlotSetVector.h | 3 +- include/swift/Basic/EditorPlaceholder.h | 4 +- include/swift/Basic/FrozenMultiMap.h | 57 ++-- include/swift/Basic/ImmutablePointerSet.h | 9 +- include/swift/Basic/JSONSerialization.h | 21 +- include/swift/Basic/LLVM.h | 3 +- include/swift/Basic/LangOptions.h | 7 +- include/swift/Basic/MultiMapCache.h | 19 +- include/swift/Basic/Platform.h | 2 +- include/swift/Basic/STLExtras.h | 2 +- include/swift/Basic/SourceManager.h | 9 +- include/swift/Basic/StringExtras.h | 19 +- include/swift/Basic/SuccessorMap.h | 6 +- include/swift/Basic/TaskQueue.h | 6 +- include/swift/Basic/TypeID.h | 4 +- include/swift/Basic/UUID.h | 2 +- include/swift/ClangImporter/ClangImporter.h | 8 +- include/swift/Demangling/TypeDecoder.h | 4 +- include/swift/Driver/Action.h | 3 +- include/swift/Driver/Compilation.h | 8 +- .../Driver/FineGrainedDependencyDriverGraph.h | 6 +- include/swift/Frontend/Frontend.h | 8 +- .../swift/Frontend/ModuleInterfaceLoader.h | 41 +-- include/swift/IDE/APIDigesterData.h | 20 +- include/swift/IDE/CompletionLookup.h | 12 +- include/swift/IDE/ModuleInterfacePrinting.h | 3 +- include/swift/IDE/Utils.h | 10 +- include/swift/IRGen/IRABIDetailsProvider.h | 8 +- include/swift/Markup/AST.h | 10 +- include/swift/Parse/IDEInspectionCallbacks.h | 4 +- include/swift/Parse/ParseVersion.h | 6 +- include/swift/Parse/Parser.h | 18 +- include/swift/Remote/MemoryReader.h | 2 +- include/swift/Remote/MetadataReader.h | 11 +- include/swift/SIL/AbstractionPattern.h | 66 ++-- include/swift/SIL/ApplySite.h | 3 +- include/swift/SIL/DynamicCasts.h | 3 +- .../swift/SIL/FieldSensitivePrunedLiveness.h | 11 +- include/swift/SIL/Projection.h | 2 +- include/swift/SIL/SILBuilder.h | 77 +++-- include/swift/SIL/SILConstants.h | 14 +- include/swift/SIL/SILDebugVariable.h | 3 +- include/swift/SIL/SILFunction.h | 3 +- include/swift/SIL/SILFunctionBuilder.h | 28 +- include/swift/SIL/SILGlobalVariable.h | 8 +- include/swift/SIL/SILInstruction.h | 47 +-- include/swift/SIL/SILModule.h | 3 +- include/swift/SIL/SILProperty.h | 15 +- include/swift/SIL/TypeLowering.h | 43 ++- .../swift/SILOptimizer/Analysis/ARCAnalysis.h | 14 +- .../Analysis/AccessStorageAnalysis.h | 4 +- .../Analysis/LoopRegionAnalysis.h | 9 +- .../SILOptimizer/Differentiation/ADContext.h | 3 +- .../Differentiation/AdjointValue.h | 20 +- .../Utils/CompileTimeInterpolationUtils.h | 3 +- include/swift/SILOptimizer/Utils/ConstExpr.h | 9 +- .../SILOptimizer/Utils/LoadStoreOptUtils.h | 9 +- include/swift/Sema/CSFix.h | 21 +- include/swift/Sema/ConstraintLocator.h | 3 +- include/swift/Sema/ConstraintSystem.h | 78 ++--- include/swift/Sema/IDETypeChecking.h | 16 +- include/swift/Sema/SourceLoader.h | 2 +- .../Serialization/ModuleDependencyScanner.h | 21 +- .../Serialization/SerializedModuleLoader.h | 12 +- .../swift/Serialization/SerializedSILLoader.h | 6 +- .../SymbolGraphGen/DocumentationCategory.h | 6 +- lib/APIDigester/ModuleAnalyzerNodes.cpp | 21 +- lib/AST/ASTContext.cpp | 108 +++---- lib/AST/ASTDemangler.cpp | 8 +- lib/AST/ASTMangler.cpp | 22 +- lib/AST/ASTScopeCreation.cpp | 13 +- lib/AST/AbstractSourceFileDepGraphFactory.cpp | 7 +- lib/AST/AccessNotes.cpp | 2 +- lib/AST/AccessRequests.cpp | 2 +- lib/AST/ArgumentList.cpp | 13 +- lib/AST/Attr.cpp | 9 +- lib/AST/AutoDiff.cpp | 32 +- lib/AST/Availability.cpp | 11 +- lib/AST/Builtins.cpp | 3 +- lib/AST/ClangTypeConverter.cpp | 12 +- lib/AST/ClangTypeConverter.h | 6 +- lib/AST/Decl.cpp | 104 +++---- lib/AST/DocComment.cpp | 8 +- lib/AST/ExistentialGeneralization.cpp | 13 +- lib/AST/ExtInfo.cpp | 8 +- lib/AST/FineGrainedDependencies.cpp | 3 +- lib/AST/FrontendSourceFileDepGraphFactory.cpp | 5 +- lib/AST/GenericEnvironment.cpp | 4 +- lib/AST/Identifier.cpp | 9 +- lib/AST/Module.cpp | 7 +- lib/AST/ModuleDependencies.cpp | 6 +- lib/AST/NameLookupRequests.cpp | 9 +- lib/AST/PlatformKind.cpp | 3 +- .../ConcreteContraction.cpp | 18 +- lib/AST/RequirementMachine/Diagnostics.h | 3 +- .../RequirementMachine/HomotopyReduction.cpp | 4 +- lib/AST/RequirementMachine/PropertyMap.h | 9 +- .../PropertyUnification.cpp | 3 +- .../RequirementMachine/RequirementBuilder.cpp | 8 +- lib/AST/RequirementMachine/RewriteContext.cpp | 50 +-- lib/AST/RequirementMachine/RewriteLoop.h | 1 - lib/AST/RequirementMachine/RewriteSystem.cpp | 3 +- lib/AST/RequirementMachine/RewriteSystem.h | 34 +- lib/AST/RequirementMachine/Rule.cpp | 3 +- lib/AST/RequirementMachine/RuleBuilder.h | 7 +- .../SimplifySubstitutions.cpp | 6 +- lib/AST/RequirementMachine/Symbol.h | 10 +- lib/AST/RequirementMachine/Term.cpp | 16 +- lib/AST/RequirementMachine/Term.h | 11 +- lib/AST/RequirementMachine/Trie.h | 7 +- lib/AST/RequirementMachine/TypeDifference.cpp | 8 +- lib/AST/Stmt.cpp | 37 +-- lib/AST/SubstitutionMap.cpp | 3 +- lib/AST/Type.cpp | 35 ++- lib/AST/TypeCheckRequests.cpp | 27 +- lib/AST/TypeSubstitution.cpp | 9 +- lib/Basic/FileSystem.cpp | 7 +- lib/Basic/JSONSerialization.cpp | 19 +- lib/Basic/LangOptions.cpp | 9 +- lib/Basic/ParseableOutput.cpp | 15 +- lib/Basic/Platform.cpp | 13 +- lib/Basic/SourceLoc.cpp | 5 +- lib/Basic/StringExtras.cpp | 26 +- lib/Basic/UUID.cpp | 2 +- lib/Basic/Version.cpp | 8 +- lib/ClangImporter/ClangAdapter.cpp | 3 +- lib/ClangImporter/ClangImporter.cpp | 27 +- lib/ClangImporter/ClangIncludePaths.h | 4 +- .../ClangModuleDependencyScanner.cpp | 11 +- lib/ClangImporter/ImportDecl.cpp | 153 +++++---- lib/ClangImporter/ImportMacro.cpp | 15 +- lib/ClangImporter/ImportName.cpp | 79 ++--- lib/ClangImporter/ImportName.h | 20 +- lib/ClangImporter/ImportType.cpp | 65 ++-- lib/ClangImporter/ImporterImpl.h | 48 ++- lib/ClangImporter/Serializability.cpp | 2 +- lib/ClangImporter/SwiftLookupTable.cpp | 8 +- lib/Demangling/ManglingUtils.cpp | 2 +- lib/Demangling/OldDemangler.cpp | 8 +- .../ModuleDependencyCacheSerialization.cpp | 6 +- lib/DependencyScan/ScanDependencies.cpp | 4 +- lib/Driver/Compilation.cpp | 3 +- lib/Driver/CompilationRecord.h | 8 +- lib/Driver/DarwinToolChains.cpp | 2 +- lib/Driver/Driver.cpp | 28 +- .../FineGrainedDependencyDriverGraph.cpp | 5 +- lib/Driver/ToolChains.h | 6 +- lib/DriverTool/sil_opt_main.cpp | 13 +- lib/DriverTool/swift_api_digester_main.cpp | 21 +- lib/DriverTool/swift_llvm_opt_main.cpp | 3 +- .../ArgsToFrontendInputsConverter.cpp | 2 +- lib/Frontend/ArgsToFrontendInputsConverter.h | 4 +- .../ArgsToFrontendOptionsConverter.cpp | 2 +- .../ArgsToFrontendOutputsConverter.cpp | 32 +- lib/Frontend/ArgsToFrontendOutputsConverter.h | 8 +- lib/Frontend/CompileJobCacheKey.cpp | 3 +- lib/Frontend/CompilerInvocation.cpp | 50 +-- lib/Frontend/Frontend.cpp | 8 +- lib/Frontend/ModuleInterfaceBuilder.cpp | 5 +- lib/Frontend/ModuleInterfaceSupport.cpp | 3 +- lib/FrontendTool/FrontendTool.cpp | 6 +- lib/IDE/APIDigesterData.cpp | 6 +- lib/IDE/CodeCompletion.cpp | 9 +- lib/IDE/CodeCompletionString.cpp | 3 +- lib/IDE/CodeCompletionStringPrinter.cpp | 3 +- lib/IDE/CompletionLookup.cpp | 11 +- lib/IDE/CompletionOverrideLookup.cpp | 4 +- lib/IDE/Formatting.cpp | 80 ++--- lib/IDE/IDERequests.cpp | 3 +- lib/IDE/ModuleInterfacePrinting.cpp | 27 +- lib/IDE/SourceEntityWalker.cpp | 32 +- lib/IDE/SwiftSourceDocInfo.cpp | 35 ++- lib/IDE/SyntaxModel.cpp | 6 +- lib/IDE/TypeContextInfo.cpp | 4 +- lib/IDETool/CompileInstance.cpp | 6 +- lib/IDETool/DependencyChecking.cpp | 7 +- lib/IDETool/IDEInspectionInstance.cpp | 3 +- lib/IDETool/SyntacticMacroExpansion.cpp | 8 +- lib/IRGen/Fulfillment.cpp | 6 +- lib/IRGen/GenCall.cpp | 5 +- lib/IRGen/GenCast.cpp | 16 +- lib/IRGen/GenCast.h | 12 +- lib/IRGen/GenClass.cpp | 8 +- lib/IRGen/GenDecl.cpp | 18 +- lib/IRGen/GenDiffFunc.cpp | 8 +- lib/IRGen/GenFunc.cpp | 44 +-- lib/IRGen/GenHeap.cpp | 13 +- lib/IRGen/GenKeyPath.cpp | 13 +- lib/IRGen/GenMeta.cpp | 19 +- lib/IRGen/GenProto.cpp | 15 +- lib/IRGen/GenReflection.cpp | 9 +- lib/IRGen/GenStruct.cpp | 14 +- lib/IRGen/GenTuple.cpp | 14 +- lib/IRGen/GenTuple.h | 8 +- lib/IRGen/GenType.h | 3 +- lib/IRGen/GenValueWitness.cpp | 23 +- lib/IRGen/IRABIDetailsProvider.cpp | 4 +- lib/IRGen/IRGen.cpp | 10 +- lib/IRGen/IRGenDebugInfo.cpp | 18 +- lib/IRGen/IRGenModule.h | 13 +- lib/IRGen/IRGenSIL.cpp | 17 +- lib/IRGen/ScalarPairTypeInfo.h | 20 +- lib/IRGen/SwiftTargetInfo.h | 2 +- lib/IRGen/TBDGen.cpp | 4 +- lib/IRGen/TypeLayout.cpp | 6 +- lib/IRGen/TypeLayout.h | 12 +- lib/IRGen/TypeLayoutDumper.cpp | 4 +- lib/Index/Index.cpp | 9 +- lib/Markup/AST.cpp | 7 +- lib/Markup/Markup.cpp | 11 +- lib/Option/SanitizerOptions.cpp | 6 +- lib/Parse/ParseDecl.cpp | 135 ++++---- lib/Parse/ParseExpr.cpp | 11 +- lib/Parse/ParseIfConfig.cpp | 15 +- lib/Parse/ParseStmt.cpp | 16 +- lib/Parse/ParseType.cpp | 5 +- lib/Parse/ParseVersion.cpp | 6 +- lib/Parse/Parser.cpp | 3 +- lib/PrintAsClang/ClangSyntaxPrinter.cpp | 3 +- lib/PrintAsClang/DeclAndTypePrinter.cpp | 86 +++--- lib/PrintAsClang/PrimitiveTypeMapping.cpp | 26 +- lib/PrintAsClang/PrintClangFunction.cpp | 60 ++-- lib/PrintAsClang/PrintClangFunction.h | 3 +- lib/Refactoring/Refactoring.cpp | 56 ++-- lib/SIL/IR/AbstractionPattern.cpp | 33 +- lib/SIL/IR/SILDeclRef.cpp | 3 +- lib/SIL/IR/SILFunction.cpp | 24 +- lib/SIL/IR/SILFunctionBuilder.cpp | 10 +- lib/SIL/IR/SILFunctionType.cpp | 33 +- lib/SIL/IR/SILGlobalVariable.cpp | 17 +- lib/SIL/IR/SILInstructions.cpp | 32 +- lib/SIL/IR/SILModule.cpp | 10 +- lib/SIL/IR/SILProfiler.cpp | 6 +- lib/SIL/IR/SILTypeSubstitution.cpp | 5 +- lib/SIL/IR/SILVTable.cpp | 4 +- lib/SIL/IR/TypeLowering.cpp | 17 +- lib/SIL/Parser/ParseSIL.cpp | 62 ++-- lib/SIL/Utils/Projection.cpp | 2 +- lib/SIL/Verifier/LinearLifetimeChecker.cpp | 25 +- lib/SILGen/Callee.h | 20 +- lib/SILGen/Condition.h | 2 +- lib/SILGen/Conversion.h | 3 +- lib/SILGen/LValue.h | 50 ++- lib/SILGen/ResultPlan.cpp | 16 +- lib/SILGen/ResultPlan.h | 7 +- lib/SILGen/SILGen.cpp | 33 +- lib/SILGen/SILGen.h | 41 ++- lib/SILGen/SILGenApply.cpp | 55 ++-- lib/SILGen/SILGenBridging.cpp | 72 ++--- lib/SILGen/SILGenBuilder.cpp | 5 +- lib/SILGen/SILGenBuiltin.cpp | 10 +- lib/SILGen/SILGenConstructor.cpp | 8 +- lib/SILGen/SILGenConvert.cpp | 4 +- lib/SILGen/SILGenDecl.cpp | 6 +- lib/SILGen/SILGenDynamicCast.cpp | 6 +- lib/SILGen/SILGenEpilog.cpp | 3 +- lib/SILGen/SILGenExpr.cpp | 106 +++---- lib/SILGen/SILGenForeignError.cpp | 27 +- lib/SILGen/SILGenFunction.cpp | 24 +- lib/SILGen/SILGenFunction.h | 111 ++++--- lib/SILGen/SILGenGlobalVariable.cpp | 7 +- lib/SILGen/SILGenLValue.cpp | 230 ++++++-------- lib/SILGen/SILGenPattern.cpp | 8 +- lib/SILGen/SILGenPoly.cpp | 13 +- lib/SILGen/SILGenProlog.cpp | 43 ++- lib/SILGen/SILGenThunk.cpp | 35 ++- lib/SILGen/SILGenType.cpp | 10 +- lib/SILGen/SpecializedEmitter.h | 4 +- lib/SILOptimizer/Analysis/ARCAnalysis.cpp | 17 +- .../Differentiation/PullbackCloner.cpp | 3 +- .../FunctionSignatureOpts.cpp | 9 +- .../LoopTransforms/LoopUnroll.cpp | 6 +- .../Mandatory/DefiniteInitialization.cpp | 13 +- .../Mandatory/DiagnoseStaticExclusivity.cpp | 2 +- lib/SILOptimizer/Mandatory/FlowIsolation.cpp | 3 +- .../MoveOnlyWrappedTypeEliminator.cpp | 3 +- .../Mandatory/PredictableMemOpt.cpp | 57 ++-- .../SILCombiner/SILCombinerApplyVisitors.cpp | 2 +- .../SemanticARC/SemanticARCOptVisitor.h | 3 +- .../Transforms/DeadStoreElimination.cpp | 3 +- lib/SILOptimizer/Transforms/Outliner.cpp | 12 +- .../Transforms/PartialApplySimplification.cpp | 10 +- .../Transforms/PerformanceInliner.cpp | 3 +- .../Transforms/PhiArgumentOptimizations.cpp | 2 +- lib/SILOptimizer/Transforms/SILMem2Reg.cpp | 4 +- .../Transforms/StringOptimization.cpp | 5 +- .../UtilityPasses/BugReducerTester.cpp | 5 +- .../Utils/CanonicalizeBorrowScope.cpp | 3 +- .../Utils/CompileTimeInterpolationUtils.cpp | 3 +- lib/SILOptimizer/Utils/ConstExpr.cpp | 19 +- lib/SILOptimizer/Utils/ConstantFolding.cpp | 10 +- lib/SILOptimizer/Utils/DistributedActor.cpp | 3 +- lib/SILOptimizer/Utils/InstOptUtils.cpp | 3 +- lib/SILOptimizer/Utils/KeyPathProjector.cpp | 15 +- .../Utils/LexicalDestroyFolding.cpp | 3 +- lib/SILOptimizer/Utils/SILInliner.cpp | 2 +- lib/SILOptimizer/Utils/StackNesting.cpp | 3 +- lib/Sema/BuilderTransform.cpp | 12 +- lib/Sema/CSApply.cpp | 20 +- lib/Sema/CSBindings.cpp | 3 +- lib/Sema/CSDiagnostics.cpp | 6 +- lib/Sema/CSDiagnostics.h | 6 +- lib/Sema/CSFix.cpp | 8 +- lib/Sema/CSSimplify.cpp | 290 ++++++++---------- lib/Sema/CSStep.h | 10 +- lib/Sema/CompletionContextFinder.cpp | 3 +- lib/Sema/Constraint.cpp | 3 +- lib/Sema/ConstraintSystem.cpp | 161 +++++----- lib/Sema/DerivedConformanceCodable.cpp | 7 +- .../DerivedConformanceRawRepresentable.cpp | 5 +- lib/Sema/InstrumenterSupport.cpp | 1 - lib/Sema/MiscDiagnostics.cpp | 19 +- lib/Sema/SourceLoader.cpp | 2 +- lib/Sema/TypeCheckAccess.cpp | 7 +- lib/Sema/TypeCheckAttr.cpp | 26 +- lib/Sema/TypeCheckAvailability.cpp | 108 +++---- lib/Sema/TypeCheckAvailability.h | 7 +- lib/Sema/TypeCheckCodeCompletion.cpp | 20 +- lib/Sema/TypeCheckConcurrency.cpp | 104 +++---- lib/Sema/TypeCheckConcurrency.h | 16 +- lib/Sema/TypeCheckDecl.cpp | 2 +- lib/Sema/TypeCheckDecl.h | 3 +- lib/Sema/TypeCheckDeclObjC.cpp | 17 +- lib/Sema/TypeCheckDeclPrimary.cpp | 14 +- lib/Sema/TypeCheckEffects.cpp | 40 +-- lib/Sema/TypeCheckExprObjC.cpp | 10 +- lib/Sema/TypeCheckMacros.cpp | 20 +- lib/Sema/TypeCheckMacros.h | 18 +- lib/Sema/TypeCheckObjC.h | 8 +- lib/Sema/TypeCheckPattern.cpp | 6 +- lib/Sema/TypeCheckProtocol.cpp | 88 +++--- lib/Sema/TypeCheckProtocol.h | 38 +-- lib/Sema/TypeCheckProtocolInference.cpp | 16 +- lib/Sema/TypeCheckStorage.cpp | 16 +- lib/Sema/TypeCheckSwitchStmt.cpp | 8 +- lib/Sema/TypeCheckType.cpp | 39 +-- lib/Sema/TypeChecker.cpp | 7 +- lib/Sema/TypeChecker.h | 12 +- lib/Serialization/Deserialization.cpp | 57 ++-- lib/Serialization/DeserializeSIL.cpp | 36 +-- lib/Serialization/DeserializeSIL.h | 7 +- lib/Serialization/ModuleDependencyScanner.cpp | 3 +- lib/Serialization/ModuleFile.cpp | 12 +- lib/Serialization/ModuleFile.h | 3 +- lib/Serialization/ModuleFileSharedCore.cpp | 3 +- lib/Serialization/SerializedModuleLoader.cpp | 7 +- lib/Serialization/SerializedSILLoader.cpp | 6 +- .../DeclarationFragmentPrinter.h | 15 +- lib/SymbolGraphGen/SymbolGraph.h | 7 +- stdlib/public/runtime/MetadataCache.h | 13 +- stdlib/public/runtime/MetadataLookup.cpp | 22 +- .../include/SourceKit/Core/Context.h | 5 +- tools/SourceKit/include/SourceKit/Core/LLVM.h | 6 +- .../include/SourceKit/Core/LangSupport.h | 25 +- tools/SourceKit/lib/Core/Context.cpp | 6 +- .../SourceKit/lib/SwiftLang/CodeCompletion.h | 4 +- .../SourceKit/lib/SwiftLang/SwiftCompile.cpp | 3 +- .../lib/SwiftLang/SwiftCompletion.cpp | 3 +- .../SwiftLang/SwiftConformingMethodList.cpp | 3 +- .../lib/SwiftLang/SwiftDocSupport.cpp | 25 +- tools/SourceKit/lib/SwiftLang/SwiftEditor.cpp | 31 +- .../lib/SwiftLang/SwiftEditorInterfaceGen.cpp | 64 ++-- .../lib/SwiftLang/SwiftInterfaceGenContext.h | 13 +- .../lib/SwiftLang/SwiftLangSupport.cpp | 3 +- .../lib/SwiftLang/SwiftLangSupport.h | 12 +- .../lib/SwiftLang/SwiftSourceDocInfo.cpp | 13 +- .../lib/SwiftLang/SwiftTypeContextInfo.cpp | 3 +- tools/swift-ast-script/ASTScriptParser.cpp | 3 +- tools/swift-ide-test/swift-ide-test.cpp | 22 +- unittests/AST/DiagnosticConsumerTests.cpp | 4 +- unittests/AST/TestContext.cpp | 6 +- .../MockingFineGrainedDependencyGraphs.h | 22 +- .../UnitTestSourceFileDepGraphFactory.cpp | 8 +- .../UnitTestSourceFileDepGraphFactory.h | 7 +- 416 files changed, 3777 insertions(+), 3734 deletions(-) diff --git a/include/swift/APIDigester/ModuleAnalyzerNodes.h b/include/swift/APIDigester/ModuleAnalyzerNodes.h index 6703ff8bc2b..d1a6ff350cd 100644 --- a/include/swift/APIDigester/ModuleAnalyzerNodes.h +++ b/include/swift/APIDigester/ModuleAnalyzerNodes.h @@ -180,6 +180,7 @@ class SDKContext { std::vector BreakingAttrs; // The common version of two ABI/API descriptors under comparison. llvm::Optional CommonVersion; + public: // Define the set of known identifiers. #define IDENTIFIER_WITH_NAME(Name, IdStr) StringRef Id_##Name = IdStr; @@ -586,11 +587,11 @@ public: return InheritsConvenienceInitializers; }; - llvm::Optional getSuperclass() const; + llvm::Optional getSuperclass() const; /// Finding the node through all children, including the inherited ones, /// whose printed name matches with the given name. - llvm::Optional lookupChildByPrintedName(StringRef Name) const; + llvm::Optional lookupChildByPrintedName(StringRef Name) const; SDKNodeType *getRawValueType() const; bool isConformingTo(KnownProtocolKind Kind) const; void jsonize(json::Output &out) override; diff --git a/include/swift/AST/ASTContext.h b/include/swift/AST/ASTContext.h index ad2c3920dc1..240860570a6 100644 --- a/include/swift/AST/ASTContext.h +++ b/include/swift/AST/ASTContext.h @@ -803,9 +803,9 @@ public: /// /// SIL analog of \c ASTContext::getClangFunctionType . const clang::Type * - getCanonicalClangFunctionType( - ArrayRef params, llvm::Optional result, - SILFunctionType::Representation trueRep); + getCanonicalClangFunctionType(ArrayRef params, + llvm::Optional result, + SILFunctionType::Representation trueRep); /// Instantiates "Impl.Converter" if needed, then translate Swift generic /// substitutions to equivalent C++ types using \p templateParams and \p @@ -1031,25 +1031,24 @@ public: /// Retrieve the module dependencies for the module with the given name. /// - llvm::Optional getModuleDependencies( - StringRef moduleName, - ModuleDependenciesCache &cache, + llvm::Optional getModuleDependencies( + StringRef moduleName, ModuleDependenciesCache &cache, InterfaceSubContextDelegate &delegate, - bool optionalDependencyLookup = false, - bool isTestableImport = false, - llvm::Optional> dependencyOf = llvm::None); + bool optionalDependencyLookup = false, bool isTestableImport = false, + llvm::Optional> + dependencyOf = llvm::None); /// Retrieve the module dependencies for the Clang module with the given name. - llvm::Optional getClangModuleDependencies( - StringRef moduleName, - ModuleDependenciesCache &cache, - InterfaceSubContextDelegate &delegate); + llvm::Optional + getClangModuleDependencies(StringRef moduleName, + ModuleDependenciesCache &cache, + InterfaceSubContextDelegate &delegate); /// Retrieve the module dependencies for the Swift module with the given name. - llvm::Optional getSwiftModuleDependencies( - StringRef moduleName, - ModuleDependenciesCache &cache, - InterfaceSubContextDelegate &delegate); + llvm::Optional + getSwiftModuleDependencies(StringRef moduleName, + ModuleDependenciesCache &cache, + InterfaceSubContextDelegate &delegate); /// Compute the extra implicit framework search paths on Apple platforms: /// $SDKROOT/System/Library/Frameworks/ and $SDKROOT/Library/Frameworks/. diff --git a/include/swift/AST/ASTDemangler.h b/include/swift/AST/ASTDemangler.h index 7e439bb2e3e..abe793f9056 100644 --- a/include/swift/AST/ASTDemangler.h +++ b/include/swift/AST/ASTDemangler.h @@ -22,13 +22,13 @@ #ifndef SWIFT_AST_ASTDEMANGLER_H #define SWIFT_AST_ASTDEMANGLER_H -#include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/ADT/Optional.h" #include "swift/AST/Types.h" #include "swift/Demangling/Demangler.h" #include "swift/Demangling/NamespaceMacros.h" #include "swift/Demangling/TypeDecoder.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/StringRef.h" namespace swift { @@ -124,11 +124,11 @@ public: FunctionMetadataDifferentiabilityKind diffKind, Type globalActor); Type createImplFunctionType( - Demangle::ImplParameterConvention calleeConvention, - ArrayRef> params, - ArrayRef> results, - llvm::Optional> errorResult, - ImplFunctionTypeFlags flags); + Demangle::ImplParameterConvention calleeConvention, + ArrayRef> params, + ArrayRef> results, + llvm::Optional> errorResult, + ImplFunctionTypeFlags flags); Type createProtocolCompositionType(ArrayRef protocols, Type superclass, @@ -143,11 +143,13 @@ public: Type createSymbolicExtendedExistentialType(NodePointer shapeNode, ArrayRef genArgs); - Type createExistentialMetatypeType(Type instance, - llvm::Optional repr=llvm::None); + Type createExistentialMetatypeType( + Type instance, + llvm::Optional repr = llvm::None); - Type createMetatypeType(Type instance, - llvm::Optional repr=llvm::None); + Type createMetatypeType( + Type instance, + llvm::Optional repr = llvm::None); Type createGenericTypeParameterType(unsigned depth, unsigned index); @@ -223,8 +225,7 @@ private: SynthesizedByImporter }; - llvm::Optional - getForeignModuleKind(NodePointer node); + llvm::Optional getForeignModuleKind(NodePointer node); GenericTypeDecl *findTypeDecl(DeclContext *dc, Identifier name, diff --git a/include/swift/AST/ASTMangler.h b/include/swift/AST/ASTMangler.h index b77308d1f33..6b8e7fc8305 100644 --- a/include/swift/AST/ASTMangler.h +++ b/include/swift/AST/ASTMangler.h @@ -13,10 +13,10 @@ #ifndef SWIFT_AST_ASTMANGLER_H #define SWIFT_AST_ASTMANGLER_H -#include "swift/Basic/Mangler.h" -#include "swift/AST/Types.h" #include "swift/AST/Decl.h" #include "swift/AST/FreestandingMacroExpansion.h" +#include "swift/AST/Types.h" +#include "swift/Basic/Mangler.h" #include "swift/Basic/TaggedUnion.h" #include "llvm/ADT/Optional.h" @@ -252,12 +252,10 @@ public: /// /// - If `predefined` is true, this mangles the symbol name of the completion handler /// predefined in the Swift runtime for the given type signature. - std::string mangleObjCAsyncCompletionHandlerImpl(CanSILFunctionType BlockType, - CanType ResultType, - CanGenericSignature Sig, - llvm::Optional FlagParamIsZeroOnError, - bool predefined); - + std::string mangleObjCAsyncCompletionHandlerImpl( + CanSILFunctionType BlockType, CanType ResultType, CanGenericSignature Sig, + llvm::Optional FlagParamIsZeroOnError, bool predefined); + /// Mangle the derivative function (JVP/VJP), or optionally its vtable entry /// thunk, for the given: /// - Mangled original function declaration. @@ -381,7 +379,7 @@ public: ObjCContext, ClangImporterContext, }; - + static llvm::Optional getSpecialManglingContext(const ValueDecl *decl, bool useObjCProtocolNames); diff --git a/include/swift/AST/ASTPrinter.h b/include/swift/AST/ASTPrinter.h index 643fd3ef279..630f3123a9c 100644 --- a/include/swift/AST/ASTPrinter.h +++ b/include/swift/AST/ASTPrinter.h @@ -133,7 +133,8 @@ public: /// Called before printing of a declaration. /// /// Callers should use callPrintDeclPre(). - virtual void printDeclPre(const Decl *D, llvm::Optional Bracket) {} + virtual void printDeclPre(const Decl *D, + llvm::Optional Bracket) {} /// Called before printing at the point which would be considered the location /// of the declaration (normally the name of the declaration). /// @@ -147,7 +148,8 @@ public: /// Called after finishing printing of a declaration. /// /// Callers should use callPrintDeclPost(). - virtual void printDeclPost(const Decl *D, llvm::Optional Bracket) {} + virtual void printDeclPost(const Decl *D, + llvm::Optional Bracket) {} /// Called before printing the result type of the declaration. Printer can /// replace \p TL to customize the input. @@ -174,15 +176,15 @@ public: virtual void printModuleRef(ModuleEntity Mod, Identifier Name); /// Called before printing a synthesized extension. - virtual void printSynthesizedExtensionPre(const ExtensionDecl *ED, - TypeOrExtensionDecl NTD, - llvm::Optional Bracket) {} + virtual void + printSynthesizedExtensionPre(const ExtensionDecl *ED, TypeOrExtensionDecl NTD, + llvm::Optional Bracket) {} /// Called after printing a synthesized extension. - virtual void printSynthesizedExtensionPost(const ExtensionDecl *ED, - TypeOrExtensionDecl TargetDecl, - llvm::Optional Bracket) { - } + virtual void + printSynthesizedExtensionPost(const ExtensionDecl *ED, + TypeOrExtensionDecl TargetDecl, + llvm::Optional Bracket) {} /// Called before printing a structured entity. /// @@ -307,7 +309,8 @@ public: void callPrintDeclPre(const Decl *D, llvm::Optional Bracket); /// Make a callback to printDeclPost(), performing any necessary bookkeeping. - void callPrintDeclPost(const Decl *D, llvm::Optional Bracket) { + void callPrintDeclPost(const Decl *D, + llvm::Optional Bracket) { printDeclPost(D, Bracket); } diff --git a/include/swift/AST/ASTScope.h b/include/swift/AST/ASTScope.h index dfd6a3457b1..5907660925b 100644 --- a/include/swift/AST/ASTScope.h +++ b/include/swift/AST/ASTScope.h @@ -36,10 +36,10 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/NullablePtr.h" #include "swift/Basic/SourceManager.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/Optional.h" /// In case there's a bug in the ASTScope lookup system, suggest that the user /// try disabling it. diff --git a/include/swift/AST/ASTWalker.h b/include/swift/AST/ASTWalker.h index d0e2efe8f6d..cf5abb9268f 100644 --- a/include/swift/AST/ASTWalker.h +++ b/include/swift/AST/ASTWalker.h @@ -53,13 +53,12 @@ struct ReferenceMetaData { /// When non-none, this is a custom attribute reference. llvm::Optional> CustomAttrRef; - ReferenceMetaData( - SemaReferenceKind Kind, llvm::Optional AccKind, - bool isImplicit = false, - llvm::Optional> customAttrRef - = llvm::None - ) : Kind(Kind), AccKind(AccKind), isImplicit(isImplicit), - CustomAttrRef(customAttrRef) {} + ReferenceMetaData(SemaReferenceKind Kind, llvm::Optional AccKind, + bool isImplicit = false, + llvm::Optional> + customAttrRef = llvm::None) + : Kind(Kind), AccKind(AccKind), isImplicit(isImplicit), + CustomAttrRef(customAttrRef) {} }; /// Specifies how the initialization expression of a \c lazy variable should be diff --git a/include/swift/AST/AbstractSourceFileDepGraphFactory.h b/include/swift/AST/AbstractSourceFileDepGraphFactory.h index 5ca4a1bc637..8668093b558 100644 --- a/include/swift/AST/AbstractSourceFileDepGraphFactory.h +++ b/include/swift/AST/AbstractSourceFileDepGraphFactory.h @@ -16,8 +16,8 @@ #include "swift/AST/Decl.h" #include "swift/AST/DeclContext.h" #include "swift/AST/FineGrainedDependencies.h" -#include "llvm/Support/VirtualOutputBackend.h" #include "llvm/ADT/Optional.h" +#include "llvm/Support/VirtualOutputBackend.h" namespace swift { class DiagnosticEngine; @@ -97,9 +97,9 @@ protected: /// Add an external dependency node to the graph. If the provided fingerprint /// is not \c None, it is added to the def key. - void addAnExternalDependency(const DependencyKey &def, - const DependencyKey &use, - llvm::Optional dependencyFingerprint); + void + addAnExternalDependency(const DependencyKey &def, const DependencyKey &use, + llvm::Optional dependencyFingerprint); static llvm::Optional getFingerprintIfAny(std::pair) { diff --git a/include/swift/AST/AccessNotes.h b/include/swift/AST/AccessNotes.h index e1877d521b6..853d200cd3d 100644 --- a/include/swift/AST/AccessNotes.h +++ b/include/swift/AST/AccessNotes.h @@ -21,10 +21,10 @@ #include "swift/AST/Identifier.h" #include "swift/AST/StorageImpl.h" #include "swift/Basic/NullablePtr.h" +#include "llvm/ADT/Optional.h" #include "llvm/Support/Error.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" -#include "llvm/ADT/Optional.h" #include #include #include diff --git a/include/swift/AST/AccessScope.h b/include/swift/AST/AccessScope.h index abeda25d3ef..d1da7b9d7a3 100644 --- a/include/swift/AST/AccessScope.h +++ b/include/swift/AST/AccessScope.h @@ -16,9 +16,9 @@ #include "swift/AST/AttrKind.h" #include "swift/AST/DeclContext.h" #include "swift/Basic/Debug.h" -#include "llvm/ADT/PointerIntPair.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/PointerIntPair.h" namespace swift { @@ -134,7 +134,8 @@ public: /// Returns the narrowest access scope if this and the specified access scope /// have common intersection, or None if scopes don't intersect. - const llvm::Optional intersectWith(AccessScope accessScope) const { + const llvm::Optional + intersectWith(AccessScope accessScope) const { if (hasEqualDeclContextWith(accessScope)) { if (isPrivate()) return *this; diff --git a/include/swift/AST/AnyFunctionRef.h b/include/swift/AST/AnyFunctionRef.h index 1ddd4a21532..ce2510a6194 100644 --- a/include/swift/AST/AnyFunctionRef.h +++ b/include/swift/AST/AnyFunctionRef.h @@ -13,17 +13,17 @@ #ifndef SWIFT_AST_ANY_FUNCTION_REF_H #define SWIFT_AST_ANY_FUNCTION_REF_H -#include "swift/Basic/Compiler.h" -#include "swift/Basic/Debug.h" -#include "swift/Basic/LLVM.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/ParameterList.h" #include "swift/AST/Types.h" +#include "swift/Basic/Compiler.h" +#include "swift/Basic/Debug.h" +#include "swift/Basic/LLVM.h" #include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/PointerUnion.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/PointerUnion.h" namespace swift { class CaptureInfo; diff --git a/include/swift/AST/ArgumentList.h b/include/swift/AST/ArgumentList.h index a870dfb4536..6afb050d390 100644 --- a/include/swift/AST/ArgumentList.h +++ b/include/swift/AST/ArgumentList.h @@ -20,8 +20,8 @@ #include "swift/AST/ASTAllocated.h" #include "swift/AST/Types.h" #include "swift/Basic/Debug.h" -#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/Support/TrailingObjects.h" namespace swift { @@ -221,8 +221,9 @@ public: /// \param arena The arena to allocate the ArgumentList in. static ArgumentList * create(ASTContext &ctx, SourceLoc lParenLoc, ArrayRef args, - SourceLoc rParenLoc, llvm::Optional firstTrailingClosureIndex, - bool isImplicit, ArgumentList *originalArgs = nullptr, + SourceLoc rParenLoc, + llvm::Optional firstTrailingClosureIndex, bool isImplicit, + ArgumentList *originalArgs = nullptr, AllocationArena arena = AllocationArena::Permanent); /// Create a new explicit parsed ArgumentList. @@ -255,17 +256,17 @@ public: /// \param rParenLoc The location of the closing ')'. Note that for a /// subscript argument list, this will be for the closing ']'. /// \param arena The arena to allocate the ArgumentList in. - static ArgumentList * - createImplicit(ASTContext &ctx, SourceLoc lParenLoc, ArrayRef args, - SourceLoc rParenLoc, - llvm::Optional firstTrailingClosureIndex = llvm::None, - AllocationArena arena = AllocationArena::Permanent); + static ArgumentList *createImplicit( + ASTContext &ctx, SourceLoc lParenLoc, ArrayRef args, + SourceLoc rParenLoc, + llvm::Optional firstTrailingClosureIndex = llvm::None, + AllocationArena arena = AllocationArena::Permanent); /// Create a new implicit ArgumentList with a set of \p args. - static ArgumentList * - createImplicit(ASTContext &ctx, ArrayRef args, - llvm::Optional firstTrailingClosureIndex = llvm::None, - AllocationArena arena = AllocationArena::Permanent); + static ArgumentList *createImplicit( + ASTContext &ctx, ArrayRef args, + llvm::Optional firstTrailingClosureIndex = llvm::None, + AllocationArena arena = AllocationArena::Permanent); /// Create a new implicit ArgumentList with a single labeled argument /// expression. @@ -527,7 +528,7 @@ public: /// will match against semantic sub-expressions, but that may be disabled by /// passing \c false for \c allowSemantic. llvm::Optional findArgumentExpr(Expr *expr, - bool allowSemantic = true) const; + bool allowSemantic = true) const; /// Creates a TupleExpr or ParenExpr that holds the argument exprs. A /// ParenExpr will be returned for a single argument, otherwise a TupleExpr. diff --git a/include/swift/AST/Attr.h b/include/swift/AST/Attr.h index c2ab9be3ee9..e6557c5011a 100644 --- a/include/swift/AST/Attr.h +++ b/include/swift/AST/Attr.h @@ -17,31 +17,31 @@ #ifndef SWIFT_ATTR_H #define SWIFT_ATTR_H -#include "swift/Basic/Debug.h" -#include "swift/Basic/InlineBitfield.h" -#include "swift/Basic/SourceLoc.h" -#include "swift/Basic/UUID.h" -#include "swift/Basic/STLExtras.h" -#include "swift/Basic/Range.h" -#include "swift/Basic/OptimizationMode.h" -#include "swift/Basic/Version.h" -#include "swift/Basic/Located.h" #include "swift/AST/ASTAllocated.h" -#include "swift/AST/Identifier.h" #include "swift/AST/AttrKind.h" #include "swift/AST/AutoDiff.h" #include "swift/AST/ConcreteDeclRef.h" #include "swift/AST/DeclNameLoc.h" +#include "swift/AST/Identifier.h" #include "swift/AST/KnownProtocols.h" #include "swift/AST/MacroDeclaration.h" #include "swift/AST/Ownership.h" #include "swift/AST/PlatformKind.h" #include "swift/AST/Requirement.h" #include "swift/AST/StorageImpl.h" -#include "llvm/ADT/iterator_range.h" +#include "swift/Basic/Debug.h" +#include "swift/Basic/InlineBitfield.h" +#include "swift/Basic/Located.h" +#include "swift/Basic/OptimizationMode.h" +#include "swift/Basic/Range.h" +#include "swift/Basic/STLExtras.h" +#include "swift/Basic/SourceLoc.h" +#include "swift/Basic/UUID.h" +#include "swift/Basic/Version.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" -#include "llvm/ADT/Optional.h" +#include "llvm/ADT/iterator_range.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/TrailingObjects.h" #include "llvm/Support/VersionTuple.h" @@ -644,7 +644,7 @@ enum class PlatformAgnosticAvailabilityKind { /// Defines the @available attribute. class AvailableAttr : public DeclAttribute { public: -#define INIT_VER_TUPLE(X)\ +#define INIT_VER_TUPLE(X) \ X(X.empty() ? llvm::Optional() : X) AvailableAttr(SourceLoc AtLoc, SourceRange Range, @@ -803,9 +803,8 @@ class ObjCAttr final : public DeclAttribute, /// Create an implicit @objc attribute with the given (optional) name. explicit ObjCAttr(llvm::Optional name, bool implicitName) - : DeclAttribute(DAK_ObjC, SourceLoc(), SourceRange(), /*Implicit=*/true), - NameData(nullptr) - { + : DeclAttribute(DAK_ObjC, SourceLoc(), SourceRange(), /*Implicit=*/true), + NameData(nullptr) { Bits.ObjCAttr.HasTrailingLocationInfo = false; Bits.ObjCAttr.ImplicitName = implicitName; Bits.ObjCAttr.Swift3Inferred = false; @@ -816,8 +815,9 @@ class ObjCAttr final : public DeclAttribute, } /// Create an @objc attribute written in the source. - ObjCAttr(SourceLoc atLoc, SourceRange baseRange, llvm::Optional name, - SourceRange parenRange, ArrayRef nameLocs); + ObjCAttr(SourceLoc atLoc, SourceRange baseRange, + llvm::Optional name, SourceRange parenRange, + ArrayRef nameLocs); /// Determine whether this attribute has trailing location information. bool hasTrailingLocationInfo() const { @@ -2347,14 +2347,15 @@ public: /// in symbol graphs, and/or adding arbitrary metadata to it. class DocumentationAttr: public DeclAttribute { public: - DocumentationAttr(SourceLoc AtLoc, SourceRange Range, - StringRef Metadata, llvm::Optional Visibility, - bool Implicit) - : DeclAttribute(DAK_Documentation, AtLoc, Range, Implicit), - Metadata(Metadata), Visibility(Visibility) {} + DocumentationAttr(SourceLoc AtLoc, SourceRange Range, StringRef Metadata, + llvm::Optional Visibility, bool Implicit) + : DeclAttribute(DAK_Documentation, AtLoc, Range, Implicit), + Metadata(Metadata), Visibility(Visibility) {} - DocumentationAttr(StringRef Metadata, llvm::Optional Visibility, bool Implicit) - : DocumentationAttr(SourceLoc(), SourceRange(), Metadata, Visibility, Implicit) {} + DocumentationAttr(StringRef Metadata, llvm::Optional Visibility, + bool Implicit) + : DocumentationAttr(SourceLoc(), SourceRange(), Metadata, Visibility, + Implicit) {} const StringRef Metadata; const llvm::Optional Visibility; @@ -2434,8 +2435,7 @@ public: template struct ToAttributeKind { ToAttributeKind() {} - llvm::Optional - operator()(const DeclAttribute *Attr) const { + llvm::Optional operator()(const DeclAttribute *Attr) const { if (isa(Attr) && (Attr->isValid() || AllowInvalid)) return cast(Attr); return llvm::None; diff --git a/include/swift/AST/AutoDiff.h b/include/swift/AST/AutoDiff.h index 9cac16e9e35..472246942e2 100644 --- a/include/swift/AST/AutoDiff.h +++ b/include/swift/AST/AutoDiff.h @@ -107,7 +107,8 @@ struct NormalDifferentiableFunctionTypeComponent { /// Returns the derivative function kind, if the component is a derivative /// function. - llvm::Optional getAsDerivativeFunctionKind() const; + llvm::Optional + getAsDerivativeFunctionKind() const; }; /// A component of a SIL `@differentiable(_linear)` function-typed value. @@ -177,7 +178,8 @@ struct DifferentiabilityWitnessFunctionKind { explicit DifferentiabilityWitnessFunctionKind(StringRef name); operator innerty() const { return rawValue; } - llvm::Optional getAsDerivativeFunctionKind() const; + llvm::Optional + getAsDerivativeFunctionKind() const; }; /// The kind of a declaration generated by the differentiation transform. diff --git a/include/swift/AST/Availability.h b/include/swift/AST/Availability.h index 38164812d0f..b36f7c674c2 100644 --- a/include/swift/AST/Availability.h +++ b/include/swift/AST/Availability.h @@ -370,8 +370,8 @@ public: /// Returns the context for which the declaration /// is annotated as available, or None if the declaration /// has no availability annotation. - static llvm::Optional annotatedAvailableRange(const Decl *D, - ASTContext &C); + static llvm::Optional + annotatedAvailableRange(const Decl *D, ASTContext &C); static AvailabilityContext annotatedAvailableRangeForAttr(const SpecializeAttr *attr, ASTContext &ctx); diff --git a/include/swift/AST/Comment.h b/include/swift/AST/Comment.h index 84edf90ec57..51272db63f7 100644 --- a/include/swift/AST/Comment.h +++ b/include/swift/AST/Comment.h @@ -53,11 +53,11 @@ public: return Parts.Brief; } - llvm::OptionalgetReturnsField() const { + llvm::Optional getReturnsField() const { return Parts.ReturnsField; } - llvm::Optional getThrowsField() const { + llvm::Optional getThrowsField() const { return Parts.ThrowsField; } diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index 502f382d4af..2ea9a088d6e 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -946,7 +946,8 @@ public: /// Returns the introduced OS version in the given platform kind specified /// by @available attribute. /// This function won't consider the parent context to get the information. - llvm::Optional getIntroducedOSVersion(PlatformKind Kind) const; + llvm::Optional + getIntroducedOSVersion(PlatformKind Kind) const; /// Returns the OS version in which the decl became ABI as specified by the /// `@backDeployed` attribute. @@ -1409,7 +1410,8 @@ public: /// /// If the list is non-homogeneous, or if there is more than one decl that /// cannot be overloaded, returns None. - static llvm::Optional findBestImportKind(ArrayRef Decls); + static llvm::Optional + findBestImportKind(ArrayRef Decls); ImportKind getImportKind() const { return static_cast(Bits.ImportDecl.ImportKind); @@ -2596,8 +2598,8 @@ public: /// entities (classes, protocols, properties), this operation will /// return a zero-parameter selector with the appropriate name in its /// first slot. - llvm::Optional getObjCRuntimeName( - bool skipIsObjCResolution = false) const; + llvm::Optional + getObjCRuntimeName(bool skipIsObjCResolution = false) const; /// Determine whether the given declaration can infer @objc, or the /// Objective-C name, if used to satisfy the given requirement. @@ -3138,8 +3140,7 @@ public: /// Get the ordinal of the anonymous opaque parameter of this decl with type /// repr `repr`, as introduce implicitly by an occurrence of "some" in return /// position e.g. `func f() -> some P`. Returns -1 if `repr` is not found. - llvm::Optional getAnonymousOpaqueParamOrdinal( - TypeRepr *repr) const; + llvm::Optional getAnonymousOpaqueParamOrdinal(TypeRepr *repr) const; GenericSignature getOpaqueInterfaceGenericSignature() const { return OpaqueInterfaceGenericSignature; @@ -3175,7 +3176,7 @@ public: llvm::Optional getUniqueUnderlyingTypeSubstitutions() const { return UniqueUnderlyingType; } - + void setUniqueUnderlyingTypeSubstitutions(SubstitutionMap subs) { assert(!UniqueUnderlyingType.has_value() && "resetting underlying type?!"); UniqueUnderlyingType = subs; @@ -5014,11 +5015,12 @@ public: if (Bits.ProtocolDecl.KnownProtocol == 1) return llvm::None; - + return static_cast(Bits.ProtocolDecl.KnownProtocol - 2); } - llvm::Optional getKnownDerivableProtocolKind() const; + llvm::Optional + getKnownDerivableProtocolKind() const; /// Check whether this protocol is of a specific, known protocol kind. bool isSpecificProtocol(KnownProtocolKind kind) const { @@ -5985,7 +5987,7 @@ public: /// Retrieve information about the mutability of the composed /// property wrappers. llvm::Optional - getPropertyWrapperMutability() const; + getPropertyWrapperMutability() const; /// Returns whether this property is the backing storage property or a storage /// wrapper for wrapper instance's projectedValue. If this property is @@ -6053,7 +6055,8 @@ public: /// \param kind If not \c None, only returns the original property when /// \c this property is the specified synthesized property. VarDecl *getOriginalWrappedProperty( - llvm::Optional kind = llvm::None) const; + llvm::Optional kind = + llvm::None) const; /// Set the property that wraps to this property as it's backing /// property. @@ -7011,7 +7014,8 @@ public: void setBodyToBeReparsed(SourceRange bodyRange); /// Provide the parsed body for the function. - void setBodyParsed(BraceStmt *S, llvm::Optional fp = llvm::None) { + void setBodyParsed(BraceStmt *S, + llvm::Optional fp = llvm::None) { setBody(S, BodyKind::Parsed); BodyAndFP.setFingerprint(fp); } @@ -7159,7 +7163,8 @@ public: /// Retrieve the fingerprint of the body including the local type members and /// the local function bodies. - llvm::Optional getBodyFingerprintIncludingLocalTypeMembers() const; + llvm::Optional + getBodyFingerprintIncludingLocalTypeMembers() const; /// Retrieve the source range of the *original* function body. /// @@ -8697,11 +8702,11 @@ public: /// /// \param skipParamIndex If the value is a function or subscript declaration, /// specifies the index of the parameter that shall be skipped. -GenericParameterReferenceInfo findGenericParameterReferences( - const ValueDecl *value, - CanGenericSignature sig, GenericTypeParamType *genericParam, - bool treatNonResultCovarianceAsInvariant, - llvm::Optional skipParamIndex); +GenericParameterReferenceInfo +findGenericParameterReferences(const ValueDecl *value, CanGenericSignature sig, + GenericTypeParamType *genericParam, + bool treatNonResultCovarianceAsInvariant, + llvm::Optional skipParamIndex); inline bool AbstractStorageDecl::isSettable(const DeclContext *UseDC, const DeclRefExpr *base) const { diff --git a/include/swift/AST/DeclContext.h b/include/swift/AST/DeclContext.h index 91e6f87c6fd..7a0029951f8 100644 --- a/include/swift/AST/DeclContext.h +++ b/include/swift/AST/DeclContext.h @@ -29,10 +29,10 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/STLExtras.h" #include "swift/Basic/SourceLoc.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/PointerEmbeddedInt.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/PointerUnion.h" -#include "llvm/ADT/Optional.h" #include "llvm/Support/raw_ostream.h" #include diff --git a/include/swift/AST/DiagnosticConsumer.h b/include/swift/AST/DiagnosticConsumer.h index 380ab71860f..1030e850006 100644 --- a/include/swift/AST/DiagnosticConsumer.h +++ b/include/swift/AST/DiagnosticConsumer.h @@ -21,9 +21,9 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/SourceLoc.h" -#include "llvm/Support/SourceMgr.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/Support/SourceMgr.h" namespace swift { class DiagnosticArgument; diff --git a/include/swift/AST/Expr.h b/include/swift/AST/Expr.h index 261f941a03f..caf91f8bc7a 100644 --- a/include/swift/AST/Expr.h +++ b/include/swift/AST/Expr.h @@ -31,9 +31,9 @@ #include "swift/AST/TypeAlignments.h" #include "swift/Basic/Debug.h" #include "swift/Basic/InlineBitfield.h" -#include "llvm/Support/TrailingObjects.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/Support/TrailingObjects.h" #include namespace llvm { diff --git a/include/swift/AST/ExtInfo.h b/include/swift/AST/ExtInfo.h index d5aad773a6e..a015c984e4e 100644 --- a/include/swift/AST/ExtInfo.h +++ b/include/swift/AST/ExtInfo.h @@ -23,8 +23,8 @@ #include "swift/AST/AutoDiff.h" #include "swift/AST/ClangModuleLoader.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" #include "llvm/Support/raw_ostream.h" #include @@ -98,9 +98,9 @@ struct UnexpectedClangTypeError { const Kind errorKind; const clang::Type *type; - static llvm::Optional checkClangType( - SILFunctionTypeRepresentation fnRep, const clang::Type *type, - bool expectNonnullForCOrBlock, bool expectCanonical); + static llvm::Optional + checkClangType(SILFunctionTypeRepresentation fnRep, const clang::Type *type, + bool expectNonnullForCOrBlock, bool expectCanonical); void dump(); }; diff --git a/include/swift/AST/FileUnit.h b/include/swift/AST/FileUnit.h index 8faaf7cd5b7..aca067ebbfc 100644 --- a/include/swift/AST/FileUnit.h +++ b/include/swift/AST/FileUnit.h @@ -136,7 +136,9 @@ public: } virtual llvm::Optional - loadFingerprint(const IterableDeclContext *IDC) const { return llvm::None; } + loadFingerprint(const IterableDeclContext *IDC) const { + return llvm::None; + } protected: /// Look up an operator declaration. Do not call directly, use @@ -162,8 +164,7 @@ public: /// This function is an implementation detail for comment serialization. /// If you just want to get a comment attached to a decl, use /// \c Decl::getRawComment() or \c Decl::getSemanticBriefComment(). - virtual llvm::Optional - getCommentForDecl(const Decl *D) const { + virtual llvm::Optional getCommentForDecl(const Decl *D) const { return llvm::None; } @@ -171,8 +172,7 @@ public: /// loaded. Otherwise, returns \c false. virtual bool hasLoadedSwiftDoc() const { return false; } - virtual llvm::Optional - getGroupNameForDecl(const Decl *D) const { + virtual llvm::Optional getGroupNameForDecl(const Decl *D) const { return llvm::None; } @@ -181,13 +181,11 @@ public: return llvm::None; } - virtual llvm::Optional - getSourceOrderForDecl(const Decl *D) const { + virtual llvm::Optional getSourceOrderForDecl(const Decl *D) const { return llvm::None; } - virtual llvm::Optional - getGroupNameByUSR(StringRef USR) const { + virtual llvm::Optional getGroupNameByUSR(StringRef USR) const { return llvm::None; } diff --git a/include/swift/AST/FineGrainedDependencies.h b/include/swift/AST/FineGrainedDependencies.h index 09dc0123429..e49ceffe933 100644 --- a/include/swift/AST/FineGrainedDependencies.h +++ b/include/swift/AST/FineGrainedDependencies.h @@ -21,9 +21,9 @@ #include "swift/Basic/Range.h" #include "swift/Basic/ReferenceDependencyKeys.h" #include "llvm/ADT/Hashing.h" -#include "llvm/ADT/SetVector.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/SetVector.h" #include "llvm/Support/MD5.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/VirtualOutputBackend.h" @@ -156,7 +156,8 @@ public: if (iter == map.end()) return llvm::None; auto iter2 = iter->second.find(k2); - return iter2 == iter->second.end() ? llvm::None : llvm::Optional(iter2->second); + return iter2 == iter->second.end() ? llvm::None + : llvm::Optional(iter2->second); } NullablePtr find(const Key1 &k1) const { @@ -260,7 +261,9 @@ public: assert(assertConsistent(v, map2.find(k2, k1))); return v; } - llvm::Optional find(const Key2 &k2, Key1 &k1) const { return find(k1, k2); } + llvm::Optional find(const Key2 &k2, Key1 &k1) const { + return find(k1, k2); + } /// Return the submap for a given Key1. May create one, after the fashion of /// the standard library. @@ -670,7 +673,9 @@ public: this->key = key; } - const llvm::Optional getFingerprint() const { return fingerprint; } + const llvm::Optional getFingerprint() const { + return fingerprint; + } /// When driver reads a SourceFileDepGraphNode, it may be a node that was /// created to represent a name-lookup (a.k.a a "depend") in the frontend. In /// that case, the node represents an entity that resides in some other file @@ -726,7 +731,8 @@ public: SourceFileDepGraphNode() : DepGraphNode() {} /// Used by the frontend to build nodes. - SourceFileDepGraphNode(DependencyKey key, llvm::Optional fingerprint, + SourceFileDepGraphNode(DependencyKey key, + llvm::Optional fingerprint, bool isProvides) : DepGraphNode(key, fingerprint), isProvides(isProvides) { assert(key.verify()); @@ -859,8 +865,9 @@ public: /// The frontend creates a pair of nodes for every tracked Decl and the source /// file itself. InterfaceAndImplementationPair - findExistingNodePairOrCreateAndAddIfNew(const DependencyKey &interfaceKey, - llvm::Optional fingerprint); + findExistingNodePairOrCreateAndAddIfNew( + const DependencyKey &interfaceKey, + llvm::Optional fingerprint); NullablePtr findExistingNode(const DependencyKey &key); @@ -885,7 +892,8 @@ public: /// Read a swiftdeps file from \p buffer and return a SourceFileDepGraph if /// successful. - llvm::Optional static loadFromBuffer(llvm::MemoryBuffer &); + llvm::Optional static loadFromBuffer( + llvm::MemoryBuffer &); llvm::Optional static loadFromSwiftModuleBuffer( llvm::MemoryBuffer &); diff --git a/include/swift/AST/ForeignAsyncConvention.h b/include/swift/AST/ForeignAsyncConvention.h index a9c696866fe..89d1a88d4cb 100644 --- a/include/swift/AST/ForeignAsyncConvention.h +++ b/include/swift/AST/ForeignAsyncConvention.h @@ -44,21 +44,21 @@ public: : CompletionHandlerParamIndex(0), CompletionHandlerErrorParamIndexPlusOneOrZero(0) { } - Info( - unsigned completionHandlerParamIndex, - llvm::Optional completionHandlerErrorParamIndex, - llvm::Optional completionHandlerFlagParamIndex, - bool completionHandlerFlagIsErrorOnZero) - : CompletionHandlerParamIndex(completionHandlerParamIndex), - CompletionHandlerErrorParamIndexPlusOneOrZero( - completionHandlerErrorParamIndex - ? *completionHandlerErrorParamIndex + 1 - : 0), - CompletionHandlerFlagParamIndexPlusOneWithPolarityOrZero( - completionHandlerFlagParamIndex - ? (*completionHandlerFlagParamIndex | ((unsigned)completionHandlerFlagIsErrorOnZero << 31)) + 1 - : 0) - {} + Info(unsigned completionHandlerParamIndex, + llvm::Optional completionHandlerErrorParamIndex, + llvm::Optional completionHandlerFlagParamIndex, + bool completionHandlerFlagIsErrorOnZero) + : CompletionHandlerParamIndex(completionHandlerParamIndex), + CompletionHandlerErrorParamIndexPlusOneOrZero( + completionHandlerErrorParamIndex + ? *completionHandlerErrorParamIndex + 1 + : 0), + CompletionHandlerFlagParamIndexPlusOneWithPolarityOrZero( + completionHandlerFlagParamIndex + ? (*completionHandlerFlagParamIndex | + ((unsigned)completionHandlerFlagIsErrorOnZero << 31)) + + 1 + : 0) {} /// Retrieve the index of the completion handler argument in the method's /// parameter list. @@ -94,7 +94,7 @@ public: return (CompletionHandlerFlagParamIndexPlusOneWithPolarityOrZero - 1) & 0x7FFFFFFFu; } - + /// Indicates the polarity of the error flag parameter to the completion handler. /// /// It is only valid to call this if \c completionHandlerFlagParamIndex returns @@ -126,16 +126,15 @@ public: public: ForeignAsyncConvention() : TheInfo() { } - ForeignAsyncConvention(CanType completionHandlerType, - unsigned completionHandlerParamIndex, - llvm::Optional completionHandlerErrorParamIndex, - llvm::Optional completionHandlerFlagParamIndex, - bool completionHandlerFlagIsErrorOnZero) + ForeignAsyncConvention( + CanType completionHandlerType, unsigned completionHandlerParamIndex, + llvm::Optional completionHandlerErrorParamIndex, + llvm::Optional completionHandlerFlagParamIndex, + bool completionHandlerFlagIsErrorOnZero) : CompletionHandlerType(completionHandlerType), TheInfo(completionHandlerParamIndex, completionHandlerErrorParamIndex, completionHandlerFlagParamIndex, - completionHandlerFlagIsErrorOnZero) - { } + completionHandlerFlagIsErrorOnZero) {} /// Retrieve the type of the completion handler parameter. CanType completionHandlerType() const { return CompletionHandlerType; } @@ -156,7 +155,7 @@ public: llvm::Optional completionHandlerErrorParamIndex() const { return TheInfo.completionHandlerErrorParamIndex(); } - + /// Retrieve the index of the error flag parameter in the completion handler's /// parameter list, if any. /// @@ -167,7 +166,7 @@ public: llvm::Optional completionHandlerFlagParamIndex() const { return TheInfo.completionHandlerFlagParamIndex(); } - + /// Indicates the polarity of the error flag parameter to the completion handler. /// /// It is only valid to call this if \c completionHandlerFlagParamIndex returns diff --git a/include/swift/AST/IRGenOptions.h b/include/swift/AST/IRGenOptions.h index f89aae484d6..5853bc62c84 100644 --- a/include/swift/AST/IRGenOptions.h +++ b/include/swift/AST/IRGenOptions.h @@ -467,7 +467,8 @@ public: /// Pull in runtime compatibility shim libraries by autolinking. llvm::Optional AutolinkRuntimeCompatibilityLibraryVersion; - llvm::Optional AutolinkRuntimeCompatibilityDynamicReplacementLibraryVersion; + llvm::Optional + AutolinkRuntimeCompatibilityDynamicReplacementLibraryVersion; llvm::Optional AutolinkRuntimeCompatibilityConcurrencyLibraryVersion; bool AutolinkRuntimeCompatibilityBytecodeLayoutsLibrary; diff --git a/include/swift/AST/IRGenRequests.h b/include/swift/AST/IRGenRequests.h index 0f97beb0756..95d8ad0b383 100644 --- a/include/swift/AST/IRGenRequests.h +++ b/include/swift/AST/IRGenRequests.h @@ -189,14 +189,13 @@ public: outModuleHash}; } - static IRGenDescriptor - forWholeModule(ModuleDecl *M, const IRGenOptions &Opts, - const TBDGenOptions &TBDOpts, const SILOptions &SILOpts, - Lowering::TypeConverter &Conv, - std::unique_ptr &&SILMod, StringRef ModuleName, - const PrimarySpecificPaths &PSPs, SymsToEmit symsToEmit = llvm::None, - ArrayRef parallelOutputFilenames = {}, - llvm::GlobalVariable **outModuleHash = nullptr) { + static IRGenDescriptor forWholeModule( + ModuleDecl *M, const IRGenOptions &Opts, const TBDGenOptions &TBDOpts, + const SILOptions &SILOpts, Lowering::TypeConverter &Conv, + std::unique_ptr &&SILMod, StringRef ModuleName, + const PrimarySpecificPaths &PSPs, SymsToEmit symsToEmit = llvm::None, + ArrayRef parallelOutputFilenames = {}, + llvm::GlobalVariable **outModuleHash = nullptr) { return IRGenDescriptor{M, symsToEmit, Opts, diff --git a/include/swift/AST/Import.h b/include/swift/AST/Import.h index caa7d6bec02..bfa6ff73fb1 100644 --- a/include/swift/AST/Import.h +++ b/include/swift/AST/Import.h @@ -25,12 +25,12 @@ #include "swift/Basic/OptionSet.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMapInfo.h" -#include "llvm/ADT/PointerIntPair.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/PointerIntPair.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" #include diff --git a/include/swift/AST/Module.h b/include/swift/AST/Module.h index ca9912f752b..aa1d88cb638 100644 --- a/include/swift/AST/Module.h +++ b/include/swift/AST/Module.h @@ -31,10 +31,10 @@ #include "swift/Basic/STLExtras.h" #include "swift/Basic/SourceLoc.h" #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" -#include "llvm/ADT/Optional.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MD5.h" #include @@ -523,7 +523,8 @@ private: /// A cache of this module's underlying module and required bystander if it's /// an underscored cross-import overlay. - llvm::Optional> declaringModuleAndBystander; + llvm::Optional> + declaringModuleAndBystander; /// If this module is an underscored cross import overlay, gets the underlying /// module that declared it (which may itself be a cross-import overlay), diff --git a/include/swift/AST/ModuleDependencies.h b/include/swift/AST/ModuleDependencies.h index 16dfad539d8..2d23a5d9e0f 100644 --- a/include/swift/AST/ModuleDependencies.h +++ b/include/swift/AST/ModuleDependencies.h @@ -898,7 +898,7 @@ private: /// Look for module dependencies for a module with the given name /// /// \returns the cached result, or \c None if there is no cached entry. - llvm::Optional + llvm::Optional findDependency(StringRef moduleName, llvm::Optional kind, StringRef scanContextHash) const; @@ -973,7 +973,7 @@ public: /// Look for module dependencies for a module with the given name /// /// \returns the cached result, or \c None if there is no cached entry. - llvm::Optional + llvm::Optional findDependency(StringRef moduleName, llvm::Optional kind) const; diff --git a/include/swift/AST/ModuleLoader.h b/include/swift/AST/ModuleLoader.h index 2c77a35c82c..be6acbfa5d4 100644 --- a/include/swift/AST/ModuleLoader.h +++ b/include/swift/AST/ModuleLoader.h @@ -24,10 +24,10 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/Located.h" #include "swift/Basic/SourceLoc.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/StringSet.h" #include "llvm/ADT/TinyPtrVector.h" -#include "llvm/ADT/Optional.h" #include "llvm/Support/VersionTuple.h" #include @@ -327,11 +327,10 @@ public: /// Retrieve the dependencies for the given, named module, or \c None /// if no such module exists. - virtual llvm::Optional getModuleDependencies( - StringRef moduleName, - ModuleDependenciesCache &cache, - InterfaceSubContextDelegate &delegate, - bool isTestableImport = false) = 0; + virtual llvm::Optional + getModuleDependencies(StringRef moduleName, ModuleDependenciesCache &cache, + InterfaceSubContextDelegate &delegate, + bool isTestableImport = false) = 0; }; } // namespace swift diff --git a/include/swift/AST/PackConformance.h b/include/swift/AST/PackConformance.h index 3997bcfb021..62411d7094c 100644 --- a/include/swift/AST/PackConformance.h +++ b/include/swift/AST/PackConformance.h @@ -82,13 +82,13 @@ public: /// The ProtocolConformanceRef either stores a pack conformance, or /// it is invalid in the case of substitution failure. ProtocolConformanceRef subst(SubstitutionMap subMap, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// The ProtocolConformanceRef either stores a pack conformance, or /// it is invalid in the case of substitution failure. ProtocolConformanceRef subst(TypeSubstitutionFn subs, LookupConformanceFn conformances, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Apply an in-flight substitution to the conformances in this /// protocol conformance ref. diff --git a/include/swift/AST/PlatformKind.h b/include/swift/AST/PlatformKind.h index 646ee8eabec..13c9821ceaa 100644 --- a/include/swift/AST/PlatformKind.h +++ b/include/swift/AST/PlatformKind.h @@ -19,8 +19,8 @@ #include "swift/Basic/LLVM.h" #include "swift/Config.h" -#include "llvm/ADT/StringRef.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/StringRef.h" #include "llvm/Support/VersionTuple.h" namespace swift { diff --git a/include/swift/AST/PrettyStackTrace.h b/include/swift/AST/PrettyStackTrace.h index 187e9595360..0184b47012e 100644 --- a/include/swift/AST/PrettyStackTrace.h +++ b/include/swift/AST/PrettyStackTrace.h @@ -23,9 +23,9 @@ #include "swift/AST/Identifier.h" #include "swift/AST/Type.h" #include "swift/Basic/SourceLoc.h" -#include "llvm/Support/PrettyStackTrace.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/Support/PrettyStackTrace.h" namespace clang { class Type; @@ -217,10 +217,10 @@ class PrettyStackTraceGenericSignature : public llvm::PrettyStackTraceEntry { llvm::Optional Requirement; public: - PrettyStackTraceGenericSignature(const char *action, - GenericSignature genericSig, - llvm::Optional requirement = llvm::None) - : Action(action), GenericSig(genericSig), Requirement(requirement) { } + PrettyStackTraceGenericSignature( + const char *action, GenericSignature genericSig, + llvm::Optional requirement = llvm::None) + : Action(action), GenericSig(genericSig), Requirement(requirement) {} void setRequirement(llvm::Optional requirement) { Requirement = requirement; diff --git a/include/swift/AST/ProtocolConformance.h b/include/swift/AST/ProtocolConformance.h index f4cf496098e..0bda83072f4 100644 --- a/include/swift/AST/ProtocolConformance.h +++ b/include/swift/AST/ProtocolConformance.h @@ -155,13 +155,13 @@ public: /// Retrieve the type witness for the given associated type. Type getTypeWitness(AssociatedTypeDecl *assocType, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Retrieve the type witness and type decl (if one exists) /// for the given associated type. TypeWitnessAndDecl getTypeWitnessAndDecl(AssociatedTypeDecl *assocType, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Apply the given function object to each type witness within this /// protocol conformance. @@ -292,7 +292,8 @@ public: /// Get any additional requirements that are required for this conformance to /// be satisfied, if it is possible for them to be computed. - llvm::Optional> getConditionalRequirementsIfAvailable() const; + llvm::Optional> + getConditionalRequirementsIfAvailable() const; /// Get any additional requirements that are required for this conformance to /// be satisfied. @@ -301,13 +302,13 @@ public: /// Substitute the conforming type and produce a ProtocolConformance that /// applies to the substituted type. ProtocolConformance *subst(SubstitutionMap subMap, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Substitute the conforming type and produce a ProtocolConformance that /// applies to the substituted type. ProtocolConformance *subst(TypeSubstitutionFn subs, LookupConformanceFn conformances, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Substitute the conforming type and produce a ProtocolConformance that /// applies to the substituted type. @@ -496,7 +497,8 @@ public: /// to be satisfied. ArrayRef getConditionalRequirements() const; - llvm::Optional> getConditionalRequirementsIfAvailable() const; + llvm::Optional> + getConditionalRequirementsIfAvailable() const; /// Retrieve the state of this conformance. ProtocolConformanceState getState() const { @@ -575,7 +577,7 @@ public: /// for the given associated type. TypeWitnessAndDecl getTypeWitnessAndDecl(AssociatedTypeDecl *assocType, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; TypeWitnessAndDecl getTypeWitnessUncached(AssociatedTypeDecl *requirement) const; @@ -708,12 +710,12 @@ public: TypeWitnessAndDecl getTypeWitnessAndDecl(AssociatedTypeDecl *assocType, - SubstOptions options=llvm::None) const { + SubstOptions options = llvm::None) const { llvm_unreachable("self-conformances never have associated types"); } Type getTypeWitness(AssociatedTypeDecl *assocType, - SubstOptions options=llvm::None) const { + SubstOptions options = llvm::None) const { llvm_unreachable("self-conformances never have associated types"); } @@ -731,7 +733,8 @@ public: } Witness getWitness(ValueDecl *requirement) const; - llvm::Optional> getConditionalRequirementsIfAvailable() const{ + llvm::Optional> + getConditionalRequirementsIfAvailable() const { return ArrayRef(); } @@ -854,7 +857,7 @@ public: /// for the given associated type. TypeWitnessAndDecl getTypeWitnessAndDecl(AssociatedTypeDecl *assocType, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Given that the requirement signature of the protocol directly states /// that the given dependent type must conform to the given protocol, @@ -971,7 +974,7 @@ public: /// for the given associated type. TypeWitnessAndDecl getTypeWitnessAndDecl(AssociatedTypeDecl *assocType, - SubstOptions options=llvm::None) const { + SubstOptions options = llvm::None) const { return InheritedConformance->getTypeWitnessAndDecl(assocType, options); } @@ -1095,7 +1098,7 @@ public: /// for the given associated type. TypeWitnessAndDecl getTypeWitnessAndDecl(AssociatedTypeDecl *assocType, - SubstOptions options=llvm::None) const { + SubstOptions options = llvm::None) const { llvm_unreachable("builtin-conformances never have associated types"); } diff --git a/include/swift/AST/ProtocolConformanceRef.h b/include/swift/AST/ProtocolConformanceRef.h index 14c7e197168..b3cdc501ec2 100644 --- a/include/swift/AST/ProtocolConformanceRef.h +++ b/include/swift/AST/ProtocolConformanceRef.h @@ -16,15 +16,15 @@ #ifndef SWIFT_AST_PROTOCOLCONFORMANCEREF_H #define SWIFT_AST_PROTOCOLCONFORMANCEREF_H -#include "swift/Basic/Debug.h" -#include "llvm/ADT/Hashing.h" -#include "llvm/ADT/PointerUnion.h" -#include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/Optional.h" #include "swift/AST/ProtocolConformanceRef.h" #include "swift/AST/Requirement.h" -#include "swift/AST/TypeAlignments.h" #include "swift/AST/Type.h" +#include "swift/AST/TypeAlignments.h" +#include "swift/Basic/Debug.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/PointerUnion.h" +#include "llvm/ADT/STLExtras.h" namespace llvm { class raw_ostream; @@ -153,15 +153,13 @@ public: ProtocolDecl *getRequirement() const; /// Apply a substitution to the conforming type. - ProtocolConformanceRef subst(Type origType, - SubstitutionMap subMap, - SubstOptions options=llvm::None) const; + ProtocolConformanceRef subst(Type origType, SubstitutionMap subMap, + SubstOptions options = llvm::None) const; /// Apply a substitution to the conforming type. - ProtocolConformanceRef subst(Type origType, - TypeSubstitutionFn subs, + ProtocolConformanceRef subst(Type origType, TypeSubstitutionFn subs, LookupConformanceFn conformances, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Apply a substitution to the conforming type. /// @@ -218,7 +216,8 @@ public: /// Get any additional requirements that are required for this conformance to /// be satisfied, if they're possible to compute. - llvm::Optional> getConditionalRequirementsIfAvailable() const; + llvm::Optional> + getConditionalRequirementsIfAvailable() const; /// Get any additional requirements that are required for this conformance to /// be satisfied. diff --git a/include/swift/AST/Stmt.h b/include/swift/AST/Stmt.h index f413689edc8..7a247964c5a 100644 --- a/include/swift/AST/Stmt.h +++ b/include/swift/AST/Stmt.h @@ -26,9 +26,9 @@ #include "swift/AST/TypeAlignments.h" #include "swift/Basic/Debug.h" #include "swift/Basic/NullablePtr.h" -#include "llvm/Support/TrailingObjects.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/Support/TrailingObjects.h" namespace swift { @@ -108,10 +108,11 @@ protected: /// Return the given value for the 'implicit' flag if present, or if None, /// return true if the location is invalid. - static bool getDefaultImplicitFlag(llvm::Optional implicit, SourceLoc keyLoc){ + static bool getDefaultImplicitFlag(llvm::Optional implicit, + SourceLoc keyLoc) { return implicit.has_value() ? *implicit : keyLoc.isInvalid(); } - + public: Stmt(StmtKind kind, bool implicit) { Bits.OpaqueBits = 0; @@ -167,13 +168,12 @@ class BraceStmt final : public Stmt, SourceLoc LBLoc; SourceLoc RBLoc; - BraceStmt(SourceLoc lbloc, ArrayRef elements,SourceLoc rbloc, + BraceStmt(SourceLoc lbloc, ArrayRef elements, SourceLoc rbloc, llvm::Optional implicit); public: static BraceStmt *create(ASTContext &ctx, SourceLoc lbloc, - ArrayRef elements, - SourceLoc rbloc, + ArrayRef elements, SourceLoc rbloc, llvm::Optional implicit = llvm::None); static BraceStmt *createImplicit(ASTContext &ctx, @@ -244,8 +244,8 @@ class ReturnStmt : public Stmt { public: ReturnStmt(SourceLoc ReturnLoc, Expr *Result, llvm::Optional implicit = llvm::None) - : Stmt(StmtKind::Return, getDefaultImplicitFlag(implicit, ReturnLoc)), - ReturnLoc(ReturnLoc), Result(Result) {} + : Stmt(StmtKind::Return, getDefaultImplicitFlag(implicit, ReturnLoc)), + ReturnLoc(ReturnLoc), Result(Result) {} SourceLoc getReturnLoc() const { return ReturnLoc; } @@ -275,8 +275,8 @@ class YieldStmt final YieldStmt(SourceLoc yieldLoc, SourceLoc lpLoc, ArrayRef yields, SourceLoc rpLoc, llvm::Optional implicit = llvm::None) - : Stmt(StmtKind::Yield, getDefaultImplicitFlag(implicit, yieldLoc)), - YieldLoc(yieldLoc), LPLoc(lpLoc), RPLoc(rpLoc) { + : Stmt(StmtKind::Yield, getDefaultImplicitFlag(implicit, yieldLoc)), + YieldLoc(yieldLoc), LPLoc(lpLoc), RPLoc(rpLoc) { Bits.YieldStmt.NumYields = yields.size(); memcpy(getMutableYields().data(), yields.data(), yields.size() * sizeof(Expr*)); @@ -284,7 +284,7 @@ class YieldStmt final public: static YieldStmt *create(const ASTContext &ctx, SourceLoc yieldLoc, - SourceLoc lp, ArrayRef yields, SourceLoc rp, + SourceLoc lp, ArrayRef yields, SourceLoc rp, llvm::Optional implicit = llvm::None); SourceLoc getYieldLoc() const { return YieldLoc; } @@ -664,11 +664,11 @@ class DoStmt : public LabeledStmt { BraceStmt *Body; public: - DoStmt(LabeledStmtInfo labelInfo, SourceLoc doLoc, - BraceStmt *body, llvm::Optional implicit = llvm::None) - : LabeledStmt(StmtKind::Do, getDefaultImplicitFlag(implicit, doLoc), - labelInfo), - DoLoc(doLoc), Body(body) {} + DoStmt(LabeledStmtInfo labelInfo, SourceLoc doLoc, BraceStmt *body, + llvm::Optional implicit = llvm::None) + : LabeledStmt(StmtKind::Do, getDefaultImplicitFlag(implicit, doLoc), + labelInfo), + DoLoc(doLoc), Body(body) {} static DoStmt *createImplicit(ASTContext &C, LabeledStmtInfo labelInfo, ArrayRef body); @@ -731,13 +731,13 @@ public: IfStmt(LabeledStmtInfo LabelInfo, SourceLoc IfLoc, StmtCondition Cond, Stmt *Then, SourceLoc ElseLoc, Stmt *Else, llvm::Optional implicit = llvm::None) - : LabeledConditionalStmt(StmtKind::If, - getDefaultImplicitFlag(implicit, IfLoc), - LabelInfo, Cond), - IfLoc(IfLoc), ElseLoc(ElseLoc), Then(Then), Else(Else) {} + : LabeledConditionalStmt(StmtKind::If, + getDefaultImplicitFlag(implicit, IfLoc), + LabelInfo, Cond), + IfLoc(IfLoc), ElseLoc(ElseLoc), Then(Then), Else(Else) {} - IfStmt(SourceLoc IfLoc, Expr *Cond, Stmt *Then, SourceLoc ElseLoc, - Stmt *Else, llvm::Optional implicit, ASTContext &Ctx); + IfStmt(SourceLoc IfLoc, Expr *Cond, Stmt *Then, SourceLoc ElseLoc, Stmt *Else, + llvm::Optional implicit, ASTContext &Ctx); SourceLoc getIfLoc() const { return IfLoc; } SourceLoc getElseLoc() const { return ElseLoc; } @@ -775,16 +775,16 @@ class GuardStmt : public LabeledConditionalStmt { BraceStmt *Body; public: - GuardStmt(SourceLoc GuardLoc, StmtCondition Cond, - BraceStmt *Body, llvm::Optional implicit = llvm::None) - : LabeledConditionalStmt(StmtKind::Guard, - getDefaultImplicitFlag(implicit, GuardLoc), - LabeledStmtInfo(), Cond), - GuardLoc(GuardLoc), Body(Body) {} - + GuardStmt(SourceLoc GuardLoc, StmtCondition Cond, BraceStmt *Body, + llvm::Optional implicit = llvm::None) + : LabeledConditionalStmt(StmtKind::Guard, + getDefaultImplicitFlag(implicit, GuardLoc), + LabeledStmtInfo(), Cond), + GuardLoc(GuardLoc), Body(Body) {} + GuardStmt(SourceLoc GuardLoc, Expr *Cond, BraceStmt *Body, llvm::Optional implicit, ASTContext &Ctx); - + SourceLoc getGuardLoc() const { return GuardLoc; } SourceLoc getStartLoc() const { @@ -811,10 +811,10 @@ class WhileStmt : public LabeledConditionalStmt { public: WhileStmt(LabeledStmtInfo LabelInfo, SourceLoc WhileLoc, StmtCondition Cond, Stmt *Body, llvm::Optional implicit = llvm::None) - : LabeledConditionalStmt(StmtKind::While, - getDefaultImplicitFlag(implicit, WhileLoc), - LabelInfo, Cond), - WhileLoc(WhileLoc), Body(Body) {} + : LabeledConditionalStmt(StmtKind::While, + getDefaultImplicitFlag(implicit, WhileLoc), + LabelInfo, Cond), + WhileLoc(WhileLoc), Body(Body) {} SourceLoc getStartLoc() const { return getLabelLocOrKeywordLoc(WhileLoc); } SourceLoc getEndLoc() const { return Body->getEndLoc(); } @@ -835,11 +835,11 @@ class RepeatWhileStmt : public LabeledStmt { public: RepeatWhileStmt(LabeledStmtInfo LabelInfo, SourceLoc RepeatLoc, Expr *Cond, - SourceLoc WhileLoc, Stmt *Body, llvm::Optional implicit = llvm::None) - : LabeledStmt(StmtKind::RepeatWhile, - getDefaultImplicitFlag(implicit, RepeatLoc), - LabelInfo), - RepeatLoc(RepeatLoc), WhileLoc(WhileLoc), Body(Body), Cond(Cond) {} + SourceLoc WhileLoc, Stmt *Body, + llvm::Optional implicit = llvm::None) + : LabeledStmt(StmtKind::RepeatWhile, + getDefaultImplicitFlag(implicit, RepeatLoc), LabelInfo), + RepeatLoc(RepeatLoc), WhileLoc(WhileLoc), Body(Body), Cond(Cond) {} SourceLoc getStartLoc() const { return getLabelLocOrKeywordLoc(RepeatLoc); } SourceLoc getEndLoc() const; @@ -882,13 +882,15 @@ class ForEachStmt : public LabeledStmt { Expr *convertElementExpr = nullptr; public: - ForEachStmt(LabeledStmtInfo LabelInfo, SourceLoc ForLoc, SourceLoc TryLoc, SourceLoc AwaitLoc, - Pattern *Pat, SourceLoc InLoc, Expr *Sequence, SourceLoc WhereLoc, - Expr *WhereExpr, BraceStmt *Body, llvm::Optional implicit = llvm::None) - : LabeledStmt(StmtKind::ForEach, getDefaultImplicitFlag(implicit, ForLoc), - LabelInfo), - ForLoc(ForLoc), TryLoc(TryLoc), AwaitLoc(AwaitLoc), Pat(nullptr), InLoc(InLoc), Sequence(Sequence), - WhereLoc(WhereLoc), WhereExpr(WhereExpr), Body(Body) { + ForEachStmt(LabeledStmtInfo LabelInfo, SourceLoc ForLoc, SourceLoc TryLoc, + SourceLoc AwaitLoc, Pattern *Pat, SourceLoc InLoc, Expr *Sequence, + SourceLoc WhereLoc, Expr *WhereExpr, BraceStmt *Body, + llvm::Optional implicit = llvm::None) + : LabeledStmt(StmtKind::ForEach, getDefaultImplicitFlag(implicit, ForLoc), + LabelInfo), + ForLoc(ForLoc), TryLoc(TryLoc), AwaitLoc(AwaitLoc), Pat(nullptr), + InLoc(InLoc), Sequence(Sequence), WhereLoc(WhereLoc), + WhereExpr(WhereExpr), Body(Body) { setPattern(Pat); } @@ -1269,10 +1271,10 @@ class SwitchStmt final : public LabeledStmt, SwitchStmt(LabeledStmtInfo LabelInfo, SourceLoc SwitchLoc, Expr *SubjectExpr, SourceLoc LBraceLoc, unsigned CaseCount, SourceLoc RBraceLoc, SourceLoc EndLoc, llvm::Optional implicit = llvm::None) - : LabeledStmt(StmtKind::Switch, getDefaultImplicitFlag(implicit, SwitchLoc), - LabelInfo), - SwitchLoc(SwitchLoc), LBraceLoc(LBraceLoc), RBraceLoc(RBraceLoc), - EndLoc(EndLoc), SubjectExpr(SubjectExpr) { + : LabeledStmt(StmtKind::Switch, + getDefaultImplicitFlag(implicit, SwitchLoc), LabelInfo), + SwitchLoc(SwitchLoc), LBraceLoc(LBraceLoc), RBraceLoc(RBraceLoc), + EndLoc(EndLoc), SubjectExpr(SubjectExpr) { Bits.SwitchStmt.CaseCount = CaseCount; } @@ -1318,7 +1320,7 @@ public: private: struct AsCaseStmtWithSkippingNonCaseStmts { AsCaseStmtWithSkippingNonCaseStmts() {} - llvm::Optional operator()(const ASTNode &N) const { + llvm::Optional operator()(const ASTNode &N) const { if (auto *CS = llvm::dyn_cast_or_null(N.dyn_cast())) return CS; return llvm::None; @@ -1406,8 +1408,8 @@ class BreakStmt : public Stmt { public: BreakStmt(SourceLoc Loc, Identifier TargetName, SourceLoc TargetLoc, DeclContext *DC, llvm::Optional implicit = llvm::None) - : Stmt(StmtKind::Break, getDefaultImplicitFlag(implicit, Loc)), Loc(Loc), - TargetName(TargetName), TargetLoc(TargetLoc), DC(DC) {} + : Stmt(StmtKind::Break, getDefaultImplicitFlag(implicit, Loc)), Loc(Loc), + TargetName(TargetName), TargetLoc(TargetLoc), DC(DC) {} SourceLoc getLoc() const { return Loc; } @@ -1441,8 +1443,8 @@ class ContinueStmt : public Stmt { public: ContinueStmt(SourceLoc Loc, Identifier TargetName, SourceLoc TargetLoc, DeclContext *DC, llvm::Optional implicit = llvm::None) - : Stmt(StmtKind::Continue, getDefaultImplicitFlag(implicit, Loc)), Loc(Loc), - TargetName(TargetName), TargetLoc(TargetLoc), DC(DC) {} + : Stmt(StmtKind::Continue, getDefaultImplicitFlag(implicit, Loc)), + Loc(Loc), TargetName(TargetName), TargetLoc(TargetLoc), DC(DC) {} Identifier getTargetName() const { return TargetName; } void setTargetName(Identifier N) { TargetName = N; } @@ -1475,10 +1477,9 @@ class FailStmt : public Stmt { public: FailStmt(SourceLoc returnLoc, SourceLoc nilLoc, llvm::Optional implicit = llvm::None) - : Stmt(StmtKind::Fail, getDefaultImplicitFlag(implicit, returnLoc)), - ReturnLoc(returnLoc), NilLoc(nilLoc) - {} - + : Stmt(StmtKind::Fail, getDefaultImplicitFlag(implicit, returnLoc)), + ReturnLoc(returnLoc), NilLoc(nilLoc) {} + SourceLoc getLoc() const { return ReturnLoc; } SourceRange getSourceRange() const { return SourceRange(ReturnLoc, NilLoc); } diff --git a/include/swift/AST/SubstitutionMap.h b/include/swift/AST/SubstitutionMap.h index c77bf13fac7..1610d99d1f3 100644 --- a/include/swift/AST/SubstitutionMap.h +++ b/include/swift/AST/SubstitutionMap.h @@ -182,13 +182,13 @@ public: /// Apply a substitution to all replacement types in the map. Does not /// change keys. SubstitutionMap subst(SubstitutionMap subMap, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Apply a substitution to all replacement types in the map. Does not /// change keys. SubstitutionMap subst(TypeSubstitutionFn subs, LookupConformanceFn conformances, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Apply an in-flight substitution to all replacement types in the map. /// Does not change keys. diff --git a/include/swift/AST/Type.h b/include/swift/AST/Type.h index 8ab2f562b7b..63a058950ce 100644 --- a/include/swift/AST/Type.h +++ b/include/swift/AST/Type.h @@ -20,19 +20,19 @@ #ifndef SWIFT_TYPE_H #define SWIFT_TYPE_H -#include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/DenseMapInfo.h" -#include "llvm/ADT/Hashing.h" -#include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/Optional.h" -#include "swift/Basic/Debug.h" -#include "swift/Basic/LLVM.h" -#include "swift/Basic/ArrayRefView.h" #include "swift/AST/LayoutConstraint.h" #include "swift/AST/PrintOptions.h" #include "swift/AST/TypeAlignments.h" -#include "swift/Basic/OptionSet.h" +#include "swift/Basic/ArrayRefView.h" #include "swift/Basic/Compiler.h" +#include "swift/Basic/Debug.h" +#include "swift/Basic/LLVM.h" +#include "swift/Basic/OptionSet.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/DenseMapInfo.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/STLExtras.h" #include #include @@ -172,7 +172,7 @@ struct SubstOptions : public OptionSet { /// conformance with the state \c CheckingTypeWitnesses. GetTentativeTypeWitness getTentativeTypeWitness; - SubstOptions(llvm::NoneType) : OptionSet(llvm::None) { } + SubstOptions(llvm::NoneType) : OptionSet(llvm::None) {} SubstOptions(SubstFlags flags) : OptionSet(flags) { } @@ -295,7 +295,8 @@ public: /// than \c getAs when the transform is intended to preserve sugar. /// /// \returns the result of transforming the type. - Type transformRec(llvm::function_ref(TypeBase *)> fn) const; + Type + transformRec(llvm::function_ref(TypeBase *)> fn) const; /// Transform the given type by recursively applying the user-provided /// function to each node. @@ -312,7 +313,8 @@ public: /// \returns the result of transforming the type. Type transformWithPosition( TypePosition pos, - llvm::function_ref(TypeBase *, TypePosition)> fn) const; + llvm::function_ref(TypeBase *, TypePosition)> fn) + const; /// Look through the given type and its children and apply fn to them. void visit(llvm::function_ref fn) const { @@ -332,7 +334,7 @@ public: /// /// \returns the substituted type, or a null type if an error occurred. Type subst(SubstitutionMap substitutions, - SubstOptions options=llvm::None) const; + SubstOptions options = llvm::None) const; /// Replace references to substitutable types with new, concrete types and /// return the substituted result. @@ -345,9 +347,8 @@ public: /// \param options Options that affect the substitutions. /// /// \returns the substituted type, or a null type if an error occurred. - Type subst(TypeSubstitutionFn substitutions, - LookupConformanceFn conformances, - SubstOptions options=llvm::None) const; + Type subst(TypeSubstitutionFn substitutions, LookupConformanceFn conformances, + SubstOptions options = llvm::None) const; /// Apply an in-flight substitution to this type. /// diff --git a/include/swift/AST/TypeCheckRequests.h b/include/swift/AST/TypeCheckRequests.h index 23c2ad7f8a4..1a0f5e6619c 100644 --- a/include/swift/AST/TypeCheckRequests.h +++ b/include/swift/AST/TypeCheckRequests.h @@ -786,10 +786,10 @@ public: }; /// Request information about the mutability of composed property wrappers. -class PropertyWrapperMutabilityRequest : - public SimpleRequest (VarDecl *), - RequestFlags::Cached> { +class PropertyWrapperMutabilityRequest + : public SimpleRequest(VarDecl *), + RequestFlags::Cached> { public: using SimpleRequest::SimpleRequest; @@ -797,8 +797,8 @@ private: friend SimpleRequest; // Evaluation. - llvm::Optional - evaluate(Evaluator &evaluator, VarDecl *var) const; + llvm::Optional evaluate(Evaluator &evaluator, + VarDecl *var) const; public: // Caching @@ -806,10 +806,10 @@ public: }; /// Request information about the l-valueness of composed property wrappers. -class PropertyWrapperLValuenessRequest : - public SimpleRequest (VarDecl *), - RequestFlags::Cached> { +class PropertyWrapperLValuenessRequest + : public SimpleRequest(VarDecl *), + RequestFlags::Cached> { public: using SimpleRequest::SimpleRequest; @@ -817,8 +817,8 @@ private: friend SimpleRequest; // Evaluation. - llvm::Optional - evaluate(Evaluator &evaluator, VarDecl *var) const; + llvm::Optional evaluate(Evaluator &evaluator, + VarDecl *var) const; public: // Caching @@ -1372,12 +1372,11 @@ using CustomAttrNominalPair = std::pair; /// /// This is the "raw" global actor attribute as written directly on the /// declaration, with any inference rules applied. -class GlobalActorAttributeRequest : - public SimpleRequest< - GlobalActorAttributeRequest, - llvm::Optional( - llvm::PointerUnion), - RequestFlags::Cached> { +class GlobalActorAttributeRequest + : public SimpleRequest( + llvm::PointerUnion), + RequestFlags::Cached> { public: using SimpleRequest::SimpleRequest; @@ -1386,8 +1385,8 @@ private: // Evaluation. llvm::Optional> - evaluate( - Evaluator &evaluator, llvm::PointerUnion) const; + evaluate(Evaluator &evaluator, + llvm::PointerUnion) const; public: // Caching @@ -3721,7 +3720,7 @@ private: friend SimpleRequest; llvm::Optional evaluate(Evaluator &evaluator, - const Decl *decl) const; + const Decl *decl) const; public: bool isCached() const { return true; } @@ -3738,7 +3737,7 @@ private: friend SimpleRequest; llvm::Optional evaluate(Evaluator &evaluator, - const Decl *decl) const; + const Decl *decl) const; public: bool isCached() const { return true; } @@ -3981,8 +3980,8 @@ public: private: friend SimpleRequest; - llvm::Optional - evaluate(Evaluator &evaluator, MacroExpansionDecl *med) const; + llvm::Optional evaluate(Evaluator &evaluator, + MacroExpansionDecl *med) const; public: bool isCached() const { return true; } @@ -4001,8 +4000,8 @@ public: private: friend SimpleRequest; - llvm::Optional - evaluate(Evaluator &evaluator, MacroExpansionExpr *mee) const; + llvm::Optional evaluate(Evaluator &evaluator, + MacroExpansionExpr *mee) const; public: bool isCached() const { return true; } diff --git a/include/swift/AST/Types.h b/include/swift/AST/Types.h index ede87243cce..03932d2884f 100644 --- a/include/swift/AST/Types.h +++ b/include/swift/AST/Types.h @@ -38,8 +38,8 @@ #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/FoldingSet.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/PointerEmbeddedInt.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/SmallBitVector.h" @@ -2852,11 +2852,9 @@ class AnyMetatypeType : public TypeBase { Type InstanceType; protected: AnyMetatypeType(TypeKind kind, const ASTContext *C, - RecursiveTypeProperties properties, - Type instanceType, + RecursiveTypeProperties properties, Type instanceType, llvm::Optional repr); - public: Type getInstanceType() const { return InstanceType; } @@ -2916,8 +2914,8 @@ public: /// /// Metatype representation is a SIL-only property. Thin metatypes /// can be lowered away to empty types in IR. - static MetatypeType *get(Type T, - llvm::Optional repr = llvm::None) { + static MetatypeType * + get(Type T, llvm::Optional repr = llvm::None) { return get(T, repr, T->getASTContext()); } @@ -2927,8 +2925,7 @@ public: } private: - MetatypeType(Type T, const ASTContext *C, - RecursiveTypeProperties properties, + MetatypeType(Type T, const ASTContext *C, RecursiveTypeProperties properties, llvm::Optional repr); friend class TypeDecl; }; @@ -2954,18 +2951,16 @@ END_CAN_TYPE_WRAPPER(MetatypeType, AnyMetatypeType) /// The representation of an existential metatype cannot be thin. class ExistentialMetatypeType : public AnyMetatypeType { public: - static ExistentialMetatypeType *get(Type T, - llvm::Optional Repr, - const ASTContext &C); + static ExistentialMetatypeType * + get(Type T, llvm::Optional Repr, const ASTContext &C); /// Return the ExistentialMetatypeType for the specified type /// with the given representation. /// /// Metatype representation is a SIL-only property. Existential /// metatypes cannot be thin. - static ExistentialMetatypeType *get(Type T, - llvm::Optional repr - = llvm::None) { + static ExistentialMetatypeType * + get(Type T, llvm::Optional repr = llvm::None) { return get(T, repr, T->getASTContext()); } @@ -3259,7 +3254,7 @@ public: return Param(getType(), Identifier(), getFlags().asParamFlags()); } - Yield subst(SubstitutionMap subs, SubstOptions options=llvm::None) const { + Yield subst(SubstitutionMap subs, SubstOptions options = llvm::None) const { return Yield(getType().subst(subs, options), getFlags()); } @@ -3280,7 +3275,8 @@ public: CanType getType() const { return CanType(Yield::getType()); } CanParam asParam() const { return CanParam::getFromParam(Yield::asParam());} - CanYield subst(SubstitutionMap subs, SubstOptions options=llvm::None) const { + CanYield subst(SubstitutionMap subs, + SubstOptions options = llvm::None) const { return CanYield(getType().subst(subs, options)->getCanonicalType(), getFlags()); } @@ -3587,8 +3583,7 @@ BEGIN_CAN_TYPE_WRAPPER(AnyFunctionType, Type) using CanParamArrayRef = AnyFunctionType::CanParamArrayRef; static CanAnyFunctionType get(CanGenericSignature signature, - CanParamArrayRef params, - CanType result, + CanParamArrayRef params, CanType result, llvm::Optional info = llvm::None); CanGenericSignature getOptGenericSignature() const; @@ -3662,10 +3657,8 @@ public: info = getExtInfo(); Profile(ID, getParams(), getResult(), info); } - static void Profile(llvm::FoldingSetNodeID &ID, - ArrayRef params, - Type result, - llvm::Optional info); + static void Profile(llvm::FoldingSetNodeID &ID, ArrayRef params, + Type result, llvm::Optional info); // Implement isa/cast/dyncast/etc. static bool classof(const TypeBase *T) { @@ -3673,15 +3666,16 @@ public: } private: - FunctionType(ArrayRef params, Type result, llvm::Optional info, - const ASTContext *ctx, RecursiveTypeProperties properties); + FunctionType(ArrayRef params, Type result, + llvm::Optional info, const ASTContext *ctx, + RecursiveTypeProperties properties); }; BEGIN_CAN_TYPE_WRAPPER(FunctionType, AnyFunctionType) - static CanFunctionType get(CanParamArrayRef params, CanType result, - llvm::Optional info = llvm::None) { - auto fnType = FunctionType::get(params.getOriginalArray(), result, info); - return cast(fnType->getCanonicalType()); - } +static CanFunctionType get(CanParamArrayRef params, CanType result, + llvm::Optional info = llvm::None) { + auto fnType = FunctionType::get(params.getOriginalArray(), result, info); + return cast(fnType->getCanonicalType()); +} CanFunctionType withExtInfo(ExtInfo info) const { return CanFunctionType(cast(getPointer()->withExtInfo(info))); @@ -3765,17 +3759,13 @@ class GenericFunctionType final : public AnyFunctionType, } /// Construct a new generic function type. - GenericFunctionType(GenericSignature sig, - ArrayRef params, - Type result, - llvm::Optional info, - const ASTContext *ctx, + GenericFunctionType(GenericSignature sig, ArrayRef params, Type result, + llvm::Optional info, const ASTContext *ctx, RecursiveTypeProperties properties); public: /// Create a new generic function type. - static GenericFunctionType *get(GenericSignature sig, - ArrayRef params, + static GenericFunctionType *get(GenericSignature sig, ArrayRef params, Type result, llvm::Optional info = llvm::None); @@ -3813,10 +3803,8 @@ public: info = getExtInfo(); Profile(ID, getGenericSignature(), getParams(), getResult(), info); } - static void Profile(llvm::FoldingSetNodeID &ID, - GenericSignature sig, - ArrayRef params, - Type result, + static void Profile(llvm::FoldingSetNodeID &ID, GenericSignature sig, + ArrayRef params, Type result, llvm::Optional info); // Implement isa/cast/dyncast/etc. @@ -3827,16 +3815,15 @@ public: BEGIN_CAN_TYPE_WRAPPER(GenericFunctionType, AnyFunctionType) /// Create a new generic function type. - static CanGenericFunctionType get(CanGenericSignature sig, - CanParamArrayRef params, - CanType result, - llvm::Optional info = llvm::None) { - // Knowing that the argument types are independently canonical is - // not sufficient to guarantee that the function type will be canonical. - auto fnType = - GenericFunctionType::get(sig, params.getOriginalArray(), result, info); - return cast(fnType->getCanonicalType()); - } +static CanGenericFunctionType get(CanGenericSignature sig, + CanParamArrayRef params, CanType result, + llvm::Optional info = llvm::None) { + // Knowing that the argument types are independently canonical is + // not sufficient to guarantee that the function type will be canonical. + auto fnType = + GenericFunctionType::get(sig, params.getOriginalArray(), result, info); + return cast(fnType->getCanonicalType()); +} CanFunctionType substGenericArgs(SubstitutionMap subs) const; @@ -4574,8 +4561,7 @@ private: ArrayRef yieldResults, ArrayRef normalResults, llvm::Optional errorResult, - SubstitutionMap patternSubs, - SubstitutionMap invocationSubs, + SubstitutionMap patternSubs, SubstitutionMap invocationSubs, const ASTContext &ctx, RecursiveTypeProperties properties, ProtocolConformanceRef witnessMethodConformance); @@ -5238,9 +5224,10 @@ public: Profile(llvm::FoldingSetNodeID &ID, GenericSignature genericSig, ExtInfo info, SILCoroutineKind coroutineKind, ParameterConvention calleeConvention, ArrayRef params, ArrayRef yields, - ArrayRef results, llvm::Optional errorResult, - ProtocolConformanceRef conformance, - SubstitutionMap patternSub, SubstitutionMap invocationSubs); + ArrayRef results, + llvm::Optional errorResult, + ProtocolConformanceRef conformance, SubstitutionMap patternSub, + SubstitutionMap invocationSubs); // Implement isa/cast/dyncast/etc. static bool classof(const TypeBase *T) { @@ -6342,9 +6329,9 @@ public: /// /// \param knownID When non-empty, the known ID of the archetype. When empty, /// a fresh archetype with a unique ID will be opened. - static CanTypeWrapper get(CanType existential, - GenericSignature parentSig, - llvm::Optional knownID = llvm::None); + static CanTypeWrapper + get(CanType existential, GenericSignature parentSig, + llvm::Optional knownID = llvm::None); /// Get or create an archetype that represents the opened type /// of an existential value. @@ -6356,10 +6343,9 @@ public: /// /// \param knownID When non-empty, the known ID of the archetype. When empty, /// a fresh archetype with a unique ID will be opened. - static CanTypeWrapper get(CanType existential, - Type interfaceType, - GenericSignature parentSig, - llvm::Optional knownID = llvm::None); + static CanTypeWrapper + get(CanType existential, Type interfaceType, GenericSignature parentSig, + llvm::Optional knownID = llvm::None); /// Create a new archetype that represents the opened type /// of an existential value. diff --git a/include/swift/AST/Witness.h b/include/swift/AST/Witness.h index af229f11e5c..b470b64989a 100644 --- a/include/swift/AST/Witness.h +++ b/include/swift/AST/Witness.h @@ -125,9 +125,9 @@ public: /// Create a witness for the given requirement. /// /// Deserialized witnesses do not have a witness thunk signature. - static Witness forDeserialized(ValueDecl *decl, - SubstitutionMap substitutions, - llvm::Optional enterIsolation) { + static Witness + forDeserialized(ValueDecl *decl, SubstitutionMap substitutions, + llvm::Optional enterIsolation) { // TODO: It's probably a good idea to have a separate 'deserialized' bit. return Witness( decl, substitutions, nullptr, SubstitutionMap(), CanGenericSignature(), @@ -151,8 +151,7 @@ public: /// /// \param enterIsolation The actor isolation that the witness thunk will /// need to hop to before calling the witness. - Witness(ValueDecl *decl, - SubstitutionMap substitutions, + Witness(ValueDecl *decl, SubstitutionMap substitutions, GenericSignature witnessThunkSig, SubstitutionMap reqToWitnessThunkSigSubs, GenericSignature derivativeGenSig, diff --git a/include/swift/Basic/BlotMapVector.h b/include/swift/Basic/BlotMapVector.h index 1a0714f2c90..49b902cc686 100644 --- a/include/swift/Basic/BlotMapVector.h +++ b/include/swift/Basic/BlotMapVector.h @@ -29,7 +29,8 @@ bool compareKeyAgainstDefaultKey(const std::pair &Pair) { /// iteration over its elements. Plus the special blot operation. template , - typename VectorT = std::vector>>> + typename VectorT = + std::vector>>> class BlotMapVector { /// Map keys to indices in Vector. MapT Map; diff --git a/include/swift/Basic/BlotSetVector.h b/include/swift/Basic/BlotSetVector.h index 32a37c7cbcd..a9e061bc6af 100644 --- a/include/swift/Basic/BlotSetVector.h +++ b/include/swift/Basic/BlotSetVector.h @@ -45,7 +45,8 @@ namespace swift { /// /// (a) The `blot operation' is leaving the value in the set vector, but marking /// the value as being dead. -template >, +template >, typename MapT = llvm::DenseMap> class BlotSetVector { VectorT vector; diff --git a/include/swift/Basic/EditorPlaceholder.h b/include/swift/Basic/EditorPlaceholder.h index f024484aa49..c4b5d17745f 100644 --- a/include/swift/Basic/EditorPlaceholder.h +++ b/include/swift/Basic/EditorPlaceholder.h @@ -18,8 +18,8 @@ #ifndef SWIFT_BASIC_EDITORPLACEHOLDER_H #define SWIFT_BASIC_EDITORPLACEHOLDER_H -#include "llvm/ADT/StringRef.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/StringRef.h" namespace swift { @@ -44,7 +44,7 @@ struct EditorPlaceholderData { /// Deconstructs a placeholder string and returns info about it. /// \returns None if the \c PlaceholderText is not a valid placeholder string. llvm::Optional - parseEditorPlaceholder(llvm::StringRef PlaceholderText); +parseEditorPlaceholder(llvm::StringRef PlaceholderText); /// Checks if an identifier with the given text is an editor placeholder bool isEditorPlaceholder(llvm::StringRef IdentifierText); diff --git a/include/swift/Basic/FrozenMultiMap.h b/include/swift/Basic/FrozenMultiMap.h index 8384c397857..93ca8eba8bb 100644 --- a/include/swift/Basic/FrozenMultiMap.h +++ b/include/swift/Basic/FrozenMultiMap.h @@ -44,7 +44,8 @@ namespace swift { template >>> + typename VectorStorage = + std::vector>>> class FrozenMultiMap { VectorStorage storage; bool frozen = false; @@ -86,10 +87,11 @@ public: // Ok, we found our first element. Now scan forward until we find a pair // whose instruction is not our own instruction. - auto end = find_if_not(start, storage.end(), - [&](const std::pair> &pair) { - return pair.first == key; - }); + auto end = + find_if_not(start, storage.end(), + [&](const std::pair> &pair) { + return pair.first == key; + }); unsigned count = std::distance(start, end); ArrayRef>> slice(&*start, count); return PairToSecondEltRange(slice, PairToSecondElt()); @@ -164,7 +166,8 @@ public: FrozenMultiMap ↦ base_iterator baseIter; - llvm::Optional>> currentValue; + llvm::Optional>> + currentValue; iterator(FrozenMultiMap &map, base_iterator iter) : map(map), baseIter(iter), currentValue() { @@ -181,27 +184,28 @@ public: } // Otherwise, determine the next range that we are visiting. - auto rangeEnd = - std::find_if_not(std::next(baseIter), end, - [&](const std::pair> &elt) { - return elt.first == baseIter->first; - }); + auto rangeEnd = std::find_if_not( + std::next(baseIter), end, + [&](const std::pair> &elt) { + return elt.first == baseIter->first; + }); llvm::Optional resultRange; if (baseIter->second.has_value()) { unsigned count = std::distance(baseIter, rangeEnd); - ArrayRef>> slice(&*baseIter, count); + ArrayRef>> slice(&*baseIter, + count); resultRange.emplace(slice, PairToSecondElt()); } currentValue = {baseIter->first, resultRange}; } iterator &operator++() { - baseIter = - std::find_if_not(std::next(baseIter), map.storage.end(), - [&](const std::pair> &elt) { - return elt.first == baseIter->first; - }); + baseIter = std::find_if_not( + std::next(baseIter), map.storage.end(), + [&](const std::pair> &elt) { + return elt.first == baseIter->first; + }); updateCurrentValue(); return *this; } @@ -231,7 +235,8 @@ public: struct ToNonErasedValues { llvm::Optional>> - operator()(std::pair> pair) const { + operator()( + std::pair> pair) const { if (!pair.second.has_value()) return llvm::None; return pair; @@ -266,9 +271,10 @@ public: /// that all values for all keys were properly handled. One cannot perform /// this operation with getRange() in a nice way. bool allValuesHaveBeenDeleted() const { - return llvm::all_of(storage, [](const std::pair> &pair) { - return !pair.second.hasValue(); - }); + return llvm::all_of(storage, + [](const std::pair> &pair) { + return !pair.second.hasValue(); + }); } typename VectorStorage::iterator vector_begin() { @@ -306,16 +312,15 @@ struct FrozenMultiMap::PairWithTypeErasedOptionalSecondElt { PairWithTypeErasedOptionalSecondElt() {} - std::pair - operator()(const std::pair> &pair) const { + std::pair operator()( + const std::pair> &pair) const { return std::make_pair(pair.first, *pair.second); } }; template -using SmallFrozenMultiMap = - FrozenMultiMap>, SmallSize>>; +using SmallFrozenMultiMap = FrozenMultiMap< + Key, Value, SmallVector>, SmallSize>>; } // namespace swift diff --git a/include/swift/Basic/ImmutablePointerSet.h b/include/swift/Basic/ImmutablePointerSet.h index 49437700c8c..c1f73f08919 100644 --- a/include/swift/Basic/ImmutablePointerSet.h +++ b/include/swift/Basic/ImmutablePointerSet.h @@ -233,7 +233,8 @@ public: // Copy in the pointers into the tail allocated memory. We do not need to do // any sorting/uniquing ourselves since we assume that our users perform // this task for us. - llvm::MutableArrayRef DataMem(reinterpret_cast(&Mem[1]), NumElts); + llvm::MutableArrayRef DataMem(reinterpret_cast(&Mem[1]), + NumElts); std::copy(Array.begin(), Array.end(), DataMem.begin()); // Allocate the new node and insert it into the Set. @@ -284,7 +285,8 @@ public: // Copy in the union of the two pointer sets into the tail allocated // memory. Since we know that our sorted arrays are uniqued, we can use // set_union to get the uniqued sorted array that we want. - llvm::MutableArrayRef DataMem(reinterpret_cast(&Mem[1]), NumElts); + llvm::MutableArrayRef DataMem(reinterpret_cast(&Mem[1]), + NumElts); std::set_union(S1->begin(), S1->end(), S2.begin(), S2.end(), DataMem.begin()); @@ -333,7 +335,8 @@ public: // Copy in the union of the two pointer sets into the tail allocated // memory. Since we know that our sorted arrays are uniqued, we can use // set_union to get the uniqued sorted array that we want. - llvm::MutableArrayRef DataMem(reinterpret_cast(&Mem[1]), NumElts); + llvm::MutableArrayRef DataMem(reinterpret_cast(&Mem[1]), + NumElts); std::set_union(S1->begin(), S1->end(), S2->begin(), S2->end(), DataMem.begin()); diff --git a/include/swift/Basic/JSONSerialization.h b/include/swift/Basic/JSONSerialization.h index e62eeff7b84..b3b4e05ce72 100644 --- a/include/swift/Basic/JSONSerialization.h +++ b/include/swift/Basic/JSONSerialization.h @@ -355,9 +355,7 @@ inline bool isNumeric(llvm::StringRef S) { return false; } -inline bool isNull(llvm::StringRef S) { - return S.equals("null"); -} +inline bool isNull(llvm::StringRef S) { return S.equals("null"); } inline bool isBool(llvm::StringRef S) { return S.equals("true") || S.equals("false"); @@ -463,13 +461,13 @@ public: } template - void mapRequired(llvm::StringRef Key, T& Val) { + void mapRequired(llvm::StringRef Key, T &Val) { this->processKey(Key, Val, true); } template - typename std::enable_if::value,void>::type - mapOptional(llvm::StringRef Key, T& Val) { + typename std::enable_if::value, void>::type + mapOptional(llvm::StringRef Key, T &Val) { // omit key/value instead of outputting empty array if (this->canElideEmptyArray() && !(Val.begin() != Val.end())) return; @@ -482,20 +480,21 @@ public: } template - typename std::enable_if::value,void>::type - mapOptional(llvm::StringRef Key, T& Val) { + typename std::enable_if::value, void>::type + mapOptional(llvm::StringRef Key, T &Val) { this->processKey(Key, Val, false); } template - void mapOptional(llvm::StringRef Key, T& Val, const T& Default) { + void mapOptional(llvm::StringRef Key, T &Val, const T &Default) { this->processKeyWithDefault(Key, Val, Default, false); } private: template void processKeyWithDefault(llvm::StringRef Key, llvm::Optional &Val, - const llvm::Optional &DefaultValue, bool Required) { + const llvm::Optional &DefaultValue, + bool Required) { assert(!DefaultValue.has_value() && "Optional shouldn't have a value!"); void *SaveInfo; @@ -559,7 +558,7 @@ struct ScalarReferenceTraits { static bool mustQuote(llvm::StringRef) { return false; } }; -template<> +template <> struct ScalarReferenceTraits { static llvm::StringRef stringRef(const llvm::StringRef &); static bool mustQuote(llvm::StringRef S) { return true; } diff --git a/include/swift/Basic/LLVM.h b/include/swift/Basic/LLVM.h index 48269db6f9f..d6514765b2f 100644 --- a/include/swift/Basic/LLVM.h +++ b/include/swift/Basic/LLVM.h @@ -58,7 +58,8 @@ namespace llvm { template class ArrayRef; template class MutableArrayRef; #endif - template class TinyPtrVector; + template + class TinyPtrVector; template class PointerUnion; template class iterator_range; class SmallBitVector; diff --git a/include/swift/Basic/LangOptions.h b/include/swift/Basic/LangOptions.h index a50d1116dfd..c3300903340 100644 --- a/include/swift/Basic/LangOptions.h +++ b/include/swift/Basic/LangOptions.h @@ -26,14 +26,13 @@ #include "clang/CAS/CASOptions.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Hashing.h" +#include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallString.h" -#include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/SmallSet.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Triple.h" -#include "llvm/ADT/Optional.h" -#include "llvm/ADT/None.h" #include "llvm/Support/Regex.h" #include "llvm/Support/VersionTuple.h" #include "llvm/Support/raw_ostream.h" diff --git a/include/swift/Basic/MultiMapCache.h b/include/swift/Basic/MultiMapCache.h index 0eb1504cf9d..2d6840f1527 100644 --- a/include/swift/Basic/MultiMapCache.h +++ b/include/swift/Basic/MultiMapCache.h @@ -31,11 +31,11 @@ namespace swift { /// /// For an example of a subclass implementation see: /// unittests/Basic/MultiMapCacheTest.cpp. -template >>, - typename VectorTy = std::vector, - typename VectorTyImpl = VectorTy> +template < + typename KeyTy, typename ValueTy, + typename MapTy = + llvm::DenseMap>>, + typename VectorTy = std::vector, typename VectorTyImpl = VectorTy> class MultiMapCache { std::function function; MapTy valueToDataOffsetIndexMap; @@ -91,10 +91,11 @@ public: }; template -using SmallMultiMapCache = MultiMapCache< - KeyTy, ValueTy, - llvm::SmallDenseMap>, 8>, - SmallVector, SmallVectorImpl>; +using SmallMultiMapCache = + MultiMapCache>, 8>, + SmallVector, SmallVectorImpl>; } // namespace swift diff --git a/include/swift/Basic/Platform.h b/include/swift/Basic/Platform.h index fec24a99e30..96bbab4dbff 100644 --- a/include/swift/Basic/Platform.h +++ b/include/swift/Basic/Platform.h @@ -16,8 +16,8 @@ #include "swift/Basic/LLVM.h" #include "swift/Config.h" #include "clang/Basic/DarwinSDKInfo.h" -#include "llvm/ADT/StringRef.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/StringRef.h" namespace llvm { class Triple; diff --git a/include/swift/Basic/STLExtras.h b/include/swift/Basic/STLExtras.h index 8b4cade65a7..3abee1f1e08 100644 --- a/include/swift/Basic/STLExtras.h +++ b/include/swift/Basic/STLExtras.h @@ -17,8 +17,8 @@ #ifndef SWIFT_BASIC_STLEXTRAS_H #define SWIFT_BASIC_STLEXTRAS_H -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Casting.h" #include diff --git a/include/swift/Basic/SourceManager.h b/include/swift/Basic/SourceManager.h index e1342174627..277621af1b4 100644 --- a/include/swift/Basic/SourceManager.h +++ b/include/swift/Basic/SourceManager.h @@ -17,8 +17,8 @@ #include "swift/Basic/SourceLoc.h" #include "clang/Basic/FileManager.h" #include "llvm/ADT/DenseSet.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" #include "llvm/Support/SourceMgr.h" #include @@ -132,6 +132,7 @@ private: mutable std::pair CachedVFile = {nullptr, nullptr}; llvm::Optional findBufferContainingLocInternal(SourceLoc Loc) const; + public: SourceManager(llvm::IntrusiveRefCntPtr FS = llvm::vfs::getRealFileSystem()) @@ -196,7 +197,8 @@ public: bool hasGeneratedSourceInfo(unsigned bufferID); /// Retrieve the generated source information for the given buffer. - llvm::Optional getGeneratedSourceInfo(unsigned bufferID) const; + llvm::Optional + getGeneratedSourceInfo(unsigned bufferID) const; /// Record the starting source location of a regex literal. void recordRegexLiteralStartLoc(SourceLoc loc) { @@ -284,7 +286,8 @@ public: /// Returns a buffer ID for a previously added buffer with the given /// buffer identifier, or None if there is no such buffer. - llvm::Optional getIDForBufferIdentifier(StringRef BufIdentifier) const; + llvm::Optional + getIDForBufferIdentifier(StringRef BufIdentifier) const; /// Returns the identifier for the buffer with the given ID. /// diff --git a/include/swift/Basic/StringExtras.h b/include/swift/Basic/StringExtras.h index cb78de9672a..f869f349d67 100644 --- a/include/swift/Basic/StringExtras.h +++ b/include/swift/Basic/StringExtras.h @@ -20,10 +20,10 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/OptionSet.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" -#include "llvm/ADT/Optional.h" #include "llvm/Support/Allocator.h" #include #include @@ -345,14 +345,12 @@ struct OmissionTypeName { OmissionTypeName(StringRef name = StringRef(), OmissionTypeOptions options = llvm::None, StringRef collectionElement = StringRef()) - : Name(name), CollectionElement(collectionElement), - Options(options) { } + : Name(name), CollectionElement(collectionElement), Options(options) {} /// Construct a type name. - OmissionTypeName(const char * name, OmissionTypeOptions options = llvm::None, + OmissionTypeName(const char *name, OmissionTypeOptions options = llvm::None, StringRef collectionElement = StringRef()) - : Name(name), CollectionElement(collectionElement), - Options(options) { } + : Name(name), CollectionElement(collectionElement), Options(options) {} /// Produce a new type name for omission with a default argument. OmissionTypeName withDefaultArgument(bool defaultArgument = true) { @@ -454,13 +452,10 @@ public: /// just chopping names. /// /// \returns true if any words were omitted, false otherwise. -bool omitNeedlessWords(StringRef &baseName, - MutableArrayRef argNames, - StringRef firstParamName, - OmissionTypeName resultType, +bool omitNeedlessWords(StringRef &baseName, MutableArrayRef argNames, + StringRef firstParamName, OmissionTypeName resultType, OmissionTypeName contextType, - ArrayRef paramTypes, - bool returnsSelf, + ArrayRef paramTypes, bool returnsSelf, bool isProperty, const InheritedNameSet *allPropertyNames, llvm::Optional completionHandlerIndex, diff --git a/include/swift/Basic/SuccessorMap.h b/include/swift/Basic/SuccessorMap.h index ab0e3c945c4..bead53ba4dd 100644 --- a/include/swift/Basic/SuccessorMap.h +++ b/include/swift/Basic/SuccessorMap.h @@ -158,7 +158,8 @@ public: /// Validate the well-formedness of this data structure. void validate() const { #ifndef NDEBUG - if (Root) validateNode(Root, llvm::None, llvm::None); + if (Root) + validateNode(Root, llvm::None, llvm::None); #endif } @@ -368,8 +369,7 @@ private: /// Validate that the node is well-formed and that all of its keys /// (and those of its children) fall (non-inclusively) between /// lowerBound and upperBound-1. - static void validateNode(Node *node, - llvm::Optional lowerBound, + static void validateNode(Node *node, llvm::Optional lowerBound, llvm::Optional upperBound) { // The node cannot have an empty key range. assert(Traits::precedes(node->Begin, node->End)); diff --git a/include/swift/Basic/TaskQueue.h b/include/swift/Basic/TaskQueue.h index 4068b1208cf..9c813e01f3e 100644 --- a/include/swift/Basic/TaskQueue.h +++ b/include/swift/Basic/TaskQueue.h @@ -91,7 +91,8 @@ public: uint64_t maxrss) : OSPid(Pid), ProcessUsage(ResourceUsage(utime, stime, maxrss)) {} - TaskProcessInformation(ProcessId Pid) : OSPid(Pid), ProcessUsage(llvm::None) {} + TaskProcessInformation(ProcessId Pid) + : OSPid(Pid), ProcessUsage(llvm::None) {} #if defined(HAVE_GETRUSAGE) && !defined(__HAIKU__) TaskProcessInformation(ProcessId Pid, struct rusage Usage); @@ -175,7 +176,8 @@ public: /// should proceed using TaskSignalledCallback = std::function Signal, TaskProcessInformation ProcInfo)>; + void *Context, llvm::Optional Signal, + TaskProcessInformation ProcInfo)>; #pragma clang diagnostic pop /// Indicates whether TaskQueue supports buffering output on the diff --git a/include/swift/Basic/TypeID.h b/include/swift/Basic/TypeID.h index e58e752b0fa..35b9104f790 100644 --- a/include/swift/Basic/TypeID.h +++ b/include/swift/Basic/TypeID.h @@ -21,9 +21,9 @@ // NOTE: Most of these includes are for CTypeIDZone.def and DefineTypeIDZone.h. #include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/TinyPtrVector.h" -#include "llvm/ADT/StringRef.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/TinyPtrVector.h" #include #include #include diff --git a/include/swift/Basic/UUID.h b/include/swift/Basic/UUID.h index b97dc81c419..e46a78a86df 100644 --- a/include/swift/Basic/UUID.h +++ b/include/swift/Basic/UUID.h @@ -66,7 +66,7 @@ public: /// Parse a UUID from a C string. static llvm::Optional fromString(const char *s); - + /// Convert a UUID to its string representation. void toString(llvm::SmallVectorImpl &out) const; diff --git a/include/swift/ClangImporter/ClangImporter.h b/include/swift/ClangImporter/ClangImporter.h index b16e7250449..02c1022d8d7 100644 --- a/include/swift/ClangImporter/ClangImporter.h +++ b/include/swift/ClangImporter/ClangImporter.h @@ -441,10 +441,10 @@ public: ModuleDependencyInfo &MDI, const clang::tooling::dependencies::TranslationUnitDeps &deps); - llvm::Optional getModuleDependencies( - StringRef moduleName, ModuleDependenciesCache &cache, - InterfaceSubContextDelegate &delegate, - bool isTestableImport = false) override; + llvm::Optional + getModuleDependencies(StringRef moduleName, ModuleDependenciesCache &cache, + InterfaceSubContextDelegate &delegate, + bool isTestableImport = false) override; /// Add dependency information for the bridging header. /// diff --git a/include/swift/Demangling/TypeDecoder.h b/include/swift/Demangling/TypeDecoder.h index d9d9bfd1ad8..a23f6dfbb21 100644 --- a/include/swift/Demangling/TypeDecoder.h +++ b/include/swift/Demangling/TypeDecoder.h @@ -31,10 +31,10 @@ #include "swift/Strings.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/PointerIntPair.h" -#include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/PointerIntPair.h" +#include "llvm/ADT/StringSwitch.h" #include namespace swift { diff --git a/include/swift/Driver/Action.h b/include/swift/Driver/Action.h index 175fcdfe59c..abd23f492ba 100644 --- a/include/swift/Driver/Action.h +++ b/include/swift/Driver/Action.h @@ -194,7 +194,8 @@ private: public: CompileJobAction(file_types::ID OutputType) - : IncrementalJobAction(Action::Kind::CompileJob, llvm::None, OutputType, {}) {} + : IncrementalJobAction(Action::Kind::CompileJob, llvm::None, OutputType, + {}) {} CompileJobAction(Action *Input, file_types::ID OutputType, InputInfo info) : IncrementalJobAction(Action::Kind::CompileJob, Input, OutputType, info) {} diff --git a/include/swift/Driver/Compilation.h b/include/swift/Driver/Compilation.h index 509c3e9439d..c0ea0ed6504 100644 --- a/include/swift/Driver/Compilation.h +++ b/include/swift/Driver/Compilation.h @@ -430,13 +430,9 @@ public: return LastBuildTime; } - llvm::Optional getBatchCount() const { - return BatchCount; - } + llvm::Optional getBatchCount() const { return BatchCount; } - llvm::Optional getBatchSizeLimit() const { - return BatchSizeLimit; - } + llvm::Optional getBatchSizeLimit() const { return BatchSizeLimit; } /// Requests the path to a file containing all input source files. This can /// be shared across jobs. diff --git a/include/swift/Driver/FineGrainedDependencyDriverGraph.h b/include/swift/Driver/FineGrainedDependencyDriverGraph.h index b2fc739dec2..76469682c92 100644 --- a/include/swift/Driver/FineGrainedDependencyDriverGraph.h +++ b/include/swift/Driver/FineGrainedDependencyDriverGraph.h @@ -358,7 +358,8 @@ private: enum class LocationOfPreexistingNode { nowhere, here, elsewhere }; - typedef llvm::Optional> + typedef llvm::Optional< + std::pair> PreexistingNodeIfAny; /// Find the preexisting node here that best matches the integrand. @@ -477,7 +478,8 @@ public: void printPath(raw_ostream &out, const driver::Job *node) const; /// Get a printable filename, given a node's swiftDeps. - StringRef getProvidingFilename(const llvm::Optional &swiftDeps) const; + StringRef + getProvidingFilename(const llvm::Optional &swiftDeps) const; /// Print one node on the dependency path. static void printOneNodeOfPath(raw_ostream &out, const DependencyKey &key, diff --git a/include/swift/Frontend/Frontend.h b/include/swift/Frontend/Frontend.h index 5743c94b619..3d2be182c3b 100644 --- a/include/swift/Frontend/Frontend.h +++ b/include/swift/Frontend/Frontend.h @@ -691,14 +691,15 @@ private: /// Set failed on failure. llvm::Optional getRecordedBufferID(const InputFile &input, - const bool shouldRecover, - bool &failed); + const bool shouldRecover, + bool &failed); /// Given an input file, return a buffer to use for its contents, /// and a buffer for the corresponding module doc file if one exists. /// On failure, return a null pointer for the first element of the returned /// pair. - llvm::Optional getInputBuffersIfPresent(const InputFile &input); + llvm::Optional + getInputBuffersIfPresent(const InputFile &input); /// Try to open the module doc file corresponding to the input parameter. /// Return None for error, nullptr if no such file exists, or the buffer if @@ -711,6 +712,7 @@ private: /// one was found. llvm::Optional> openModuleSourceInfo(const InputFile &input); + public: /// Parses and type-checks all input files. void performSema(); diff --git a/include/swift/Frontend/ModuleInterfaceLoader.h b/include/swift/Frontend/ModuleInterfaceLoader.h index 9cd2e5bc05e..1f385d32238 100644 --- a/include/swift/Frontend/ModuleInterfaceLoader.h +++ b/include/swift/Frontend/ModuleInterfaceLoader.h @@ -238,20 +238,16 @@ public: // Explicitly-specified Swift module inputs struct ExplicitSwiftModuleInputInfo { - ExplicitSwiftModuleInputInfo(std::string modulePath, - llvm::Optional moduleDocPath, - llvm::Optional moduleSourceInfoPath, - llvm::Optional> headerDependencyPaths, - bool isFramework = false, - bool isSystem = false, - llvm::Optional moduleCacheKey = llvm::None) - : modulePath(modulePath), - moduleDocPath(moduleDocPath), - moduleSourceInfoPath(moduleSourceInfoPath), - headerDependencyPaths(headerDependencyPaths), - isFramework(isFramework), - isSystem(isSystem), - moduleCacheKey(moduleCacheKey) {} + ExplicitSwiftModuleInputInfo( + std::string modulePath, llvm::Optional moduleDocPath, + llvm::Optional moduleSourceInfoPath, + llvm::Optional> headerDependencyPaths, + bool isFramework = false, bool isSystem = false, + llvm::Optional moduleCacheKey = llvm::None) + : modulePath(modulePath), moduleDocPath(moduleDocPath), + moduleSourceInfoPath(moduleSourceInfoPath), + headerDependencyPaths(headerDependencyPaths), isFramework(isFramework), + isSystem(isSystem), moduleCacheKey(moduleCacheKey) {} // Path of the .swiftmodule file. std::string modulePath; // Path of the .swiftmoduledoc file. @@ -270,16 +266,13 @@ struct ExplicitSwiftModuleInputInfo { // Explicitly-specified Clang module inputs struct ExplicitClangModuleInputInfo { - ExplicitClangModuleInputInfo(std::string moduleMapPath, - std::string modulePath, - bool isFramework = false, - bool isSystem = false, - llvm::Optional moduleCacheKey = llvm::None) - : moduleMapPath(moduleMapPath), - modulePath(modulePath), - isFramework(isFramework), - isSystem(isSystem), - moduleCacheKey(moduleCacheKey) {} + ExplicitClangModuleInputInfo( + std::string moduleMapPath, std::string modulePath, + bool isFramework = false, bool isSystem = false, + llvm::Optional moduleCacheKey = llvm::None) + : moduleMapPath(moduleMapPath), modulePath(modulePath), + isFramework(isFramework), isSystem(isSystem), + moduleCacheKey(moduleCacheKey) {} // Path of the Clang module map file. std::string moduleMapPath; // Path of a compiled Clang explicit module file (pcm). diff --git a/include/swift/IDE/APIDigesterData.h b/include/swift/IDE/APIDigesterData.h index f431225b2a5..9b9ad0ed452 100644 --- a/include/swift/IDE/APIDigesterData.h +++ b/include/swift/IDE/APIDigesterData.h @@ -278,15 +278,17 @@ public: public: TypeMemberDiffItem(StringRef usr, StringRef newTypeName, - StringRef newPrintedName, llvm::Optional selfIndex, - llvm::Optional removedIndex, StringRef oldTypeName, - StringRef oldPrintedName) : usr(usr), - newTypeName(newTypeName), newPrintedName(newPrintedName), - selfIndex(selfIndex), removedIndex(removedIndex), oldTypeName(oldTypeName), - oldPrintedName(oldPrintedName), OldNameViewer(oldPrintedName), - NewNameViewer(newPrintedName), - NewTypeDot(isNewNameGlobal() ? "" : (llvm::Twine(newTypeName) + ".").str()), - Subkind(getSubKind()) {} + StringRef newPrintedName, + llvm::Optional selfIndex, + llvm::Optional removedIndex, + StringRef oldTypeName, StringRef oldPrintedName) + : usr(usr), newTypeName(newTypeName), newPrintedName(newPrintedName), + selfIndex(selfIndex), removedIndex(removedIndex), + oldTypeName(oldTypeName), oldPrintedName(oldPrintedName), + OldNameViewer(oldPrintedName), NewNameViewer(newPrintedName), + NewTypeDot(isNewNameGlobal() ? "" + : (llvm::Twine(newTypeName) + ".").str()), + Subkind(getSubKind()) {} static StringRef head(); static void describe(llvm::raw_ostream &os); static void undef(llvm::raw_ostream &os); diff --git a/include/swift/IDE/CompletionLookup.h b/include/swift/IDE/CompletionLookup.h index 799c8a38633..288b912bbe4 100644 --- a/include/swift/IDE/CompletionLookup.h +++ b/include/swift/IDE/CompletionLookup.h @@ -313,8 +313,9 @@ public: void collectImportedModules(llvm::StringSet<> &directImportedModules, llvm::StringSet<> &allImportedModules); - void addModuleName(ModuleDecl *MD, - llvm::Optional R = llvm::None); + void + addModuleName(ModuleDecl *MD, + llvm::Optional R = llvm::None); void addImportModuleNames(); @@ -412,8 +413,8 @@ public: void addConstructorCall(const ConstructorDecl *CD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo, - llvm::Optional BaseType, llvm::Optional Result, - bool IsOnType = true, + llvm::Optional BaseType, + llvm::Optional Result, bool IsOnType = true, Identifier addName = Identifier()); void addConstructorCallsForType(Type type, Identifier name, @@ -587,7 +588,8 @@ public: static bool canUseAttributeOnDecl(DeclAttrKind DAK, bool IsInSil, bool IsConcurrencyEnabled, - llvm::Optional DK, StringRef Name); + llvm::Optional DK, + StringRef Name); void getAttributeDeclCompletions(bool IsInSil, llvm::Optional DK); diff --git a/include/swift/IDE/ModuleInterfacePrinting.h b/include/swift/IDE/ModuleInterfacePrinting.h index 0115586aefb..05587bc3a2f 100644 --- a/include/swift/IDE/ModuleInterfacePrinting.h +++ b/include/swift/IDE/ModuleInterfacePrinting.h @@ -48,8 +48,7 @@ using ModuleTraversalOptions = OptionSet; void collectModuleGroups(ModuleDecl *M, SmallVectorImpl &Into); -llvm::Optional -findGroupNameForUSR(ModuleDecl *M, StringRef USR); +llvm::Optional findGroupNameForUSR(ModuleDecl *M, StringRef USR); bool printTypeInterface(ModuleDecl *M, Type Ty, ASTPrinter &Printer, std::string &TypeName, std::string &Error); diff --git a/include/swift/IDE/Utils.h b/include/swift/IDE/Utils.h index df2bd82b65a..6cbc7bfd4bb 100644 --- a/include/swift/IDE/Utils.h +++ b/include/swift/IDE/Utils.h @@ -172,7 +172,8 @@ private: bool IsRef = true; Type Ty; Type ContainerType; - llvm::Optional> CustomAttrRef = llvm::None; + llvm::Optional> CustomAttrRef = + llvm::None; bool IsKeywordArgument = false; /// It this is a ref, whether it is "dynamic". See \c ide::isDynamicRef. @@ -239,7 +240,8 @@ public: ValueDecl *typeOrValue() { return CtorTyRef ? CtorTyRef : ValueD; } - llvm::Optional> getCustomAttrRef() const { + llvm::Optional> + getCustomAttrRef() const { return CustomAttrRef; } @@ -362,8 +364,8 @@ class NameMatcher: public ASTWalker { bool tryResolve(ASTWalker::ParentTy Node, SourceLoc NameLoc); bool tryResolve(ASTWalker::ParentTy Node, DeclNameLoc NameLoc, ArgumentList *Args); - bool tryResolve(ASTWalker::ParentTy Node, SourceLoc NameLoc, LabelRangeType RangeType, - ArrayRef LabelLocs, + bool tryResolve(ASTWalker::ParentTy Node, SourceLoc NameLoc, + LabelRangeType RangeType, ArrayRef LabelLocs, llvm::Optional FirstTrailingLabel); bool handleCustomAttrs(Decl *D); ArgumentList *getApplicableArgsFor(Expr* E); diff --git a/include/swift/IRGen/IRABIDetailsProvider.h b/include/swift/IRGen/IRABIDetailsProvider.h index 0ed1f7d3261..26398c021fc 100644 --- a/include/swift/IRGen/IRABIDetailsProvider.h +++ b/include/swift/IRGen/IRABIDetailsProvider.h @@ -295,7 +295,8 @@ public: assert(kind == Kind::IndirectVTableStaticOffset); return offset; } - llvm::Optional getPointerAuthDiscriminator() const { + llvm::Optional + getPointerAuthDiscriminator() const { assert(kind == Kind::IndirectVTableStaticOffset || kind == Kind::IndirectVTableRelativeOffset); return discriminator; @@ -320,8 +321,9 @@ public: } private: - MethodDispatchInfo(Kind kind, size_t offset, std::string symbolName = "", - llvm::Optional discriminator = llvm::None) + MethodDispatchInfo( + Kind kind, size_t offset, std::string symbolName = "", + llvm::Optional discriminator = llvm::None) : kind(kind), offset(offset), symbolName(symbolName), discriminator(discriminator) {} diff --git a/include/swift/Markup/AST.h b/include/swift/Markup/AST.h index 570bb0e0437..a0b2a5a70f1 100644 --- a/include/swift/Markup/AST.h +++ b/include/swift/Markup/AST.h @@ -40,7 +40,8 @@ struct CommentParts { llvm::Optional ReturnsField; llvm::Optional ThrowsField; llvm::SmallSetVector Tags; - llvm::Optional LocalizationKeyField; + llvm::Optional + LocalizationKeyField; bool isEmpty() const { return !Brief.has_value() && @@ -561,10 +562,9 @@ class Image final : public InlineContent, ArrayRef Children); public: - static Image *create(MarkupContext &MC, - StringRef Destination, - llvm::Optional Title, - ArrayRef Children); + static Image *create(MarkupContext &MC, StringRef Destination, + llvm::Optional Title, + ArrayRef Children); StringRef getDestination() const { return Destination; } diff --git a/include/swift/Parse/IDEInspectionCallbacks.h b/include/swift/Parse/IDEInspectionCallbacks.h index d1132fdc6c6..4b370c6b779 100644 --- a/include/swift/Parse/IDEInspectionCallbacks.h +++ b/include/swift/Parse/IDEInspectionCallbacks.h @@ -240,10 +240,10 @@ public: /// index means that the completion is within the parentheses and is /// for a specific yield value. virtual void completeYieldStmt(CodeCompletionExpr *E, - llvm::Optional yieldIndex) {}; + llvm::Optional yieldIndex){}; virtual void completeAfterPoundExpr(CodeCompletionExpr *E, - llvm::Optional ParentKind) {}; + llvm::Optional ParentKind){}; virtual void completeAfterPoundDirective() {}; diff --git a/include/swift/Parse/ParseVersion.h b/include/swift/Parse/ParseVersion.h index 885726001d3..f366fe3ea76 100644 --- a/include/swift/Parse/ParseVersion.h +++ b/include/swift/Parse/ParseVersion.h @@ -41,9 +41,9 @@ public: /// Parse a generic version string of the format [0-9]+(.[0-9]+)* /// /// Version components can be any unsigned 64-bit number. - static llvm::Optional parseVersionString(StringRef VersionString, - SourceLoc Loc, - DiagnosticEngine *Diags); + static llvm::Optional + parseVersionString(StringRef VersionString, SourceLoc Loc, + DiagnosticEngine *Diags); }; } // namespace swift diff --git a/include/swift/Parse/Parser.h b/include/swift/Parse/Parser.h index 36037fb8308..72f02983b47 100644 --- a/include/swift/Parse/Parser.h +++ b/include/swift/Parse/Parser.h @@ -916,9 +916,10 @@ public: void parseTopLevelItems(SmallVectorImpl &items); /// Parse the source file via the Swift Parser using the ASTGen library. - void parseSourceFileViaASTGen(SmallVectorImpl &items, - llvm::Optional &transaction, - bool suppressDiagnostics = false); + void + parseSourceFileViaASTGen(SmallVectorImpl &items, + llvm::Optional &transaction, + bool suppressDiagnostics = false); /// Parse the top-level SIL decls into the SIL module. /// \returns \c true if there was a parsing error. @@ -1060,7 +1061,8 @@ public: /// Parse the arguments inside the @_specialize attribute bool parseSpecializeAttributeArguments( - swift::tok ClosingBrace, bool &DiscardAttribute, llvm::Optional &Exported, + swift::tok ClosingBrace, bool &DiscardAttribute, + llvm::Optional &Exported, llvm::Optional &Kind, TrailingWhereClause *&TrailingWhereClause, DeclNameRef &targetFunction, AvailabilityContext *SILAvailability, @@ -1112,8 +1114,9 @@ public: SourceLoc Loc); /// Parse a single argument from a @_documentation attribute. - bool parseDocumentationAttributeArgument(llvm::Optional &Metadata, - llvm::Optional &Visibility); + bool + parseDocumentationAttributeArgument(llvm::Optional &Metadata, + llvm::Optional &Visibility); /// Parse the @attached or @freestanding attribute that specifies a macro /// role. @@ -1898,7 +1901,8 @@ public: bool isExprBasic); ParserResult parseExprMacroExpansion(bool isExprBasic); ParserResult parseExprCollection(); - ParserResult parseExprCollectionElement(llvm::Optional &isDictionary); + ParserResult + parseExprCollectionElement(llvm::Optional &isDictionary); ParserResult parseExprPoundCodeCompletion(llvm::Optional ParentKind); diff --git a/include/swift/Remote/MemoryReader.h b/include/swift/Remote/MemoryReader.h index 288ee8ef33f..96dcbb30ea6 100644 --- a/include/swift/Remote/MemoryReader.h +++ b/include/swift/Remote/MemoryReader.h @@ -20,8 +20,8 @@ #include "swift/Remote/RemoteAddress.h" #include "swift/SwiftRemoteMirror/MemoryReaderInterface.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" #include #include diff --git a/include/swift/Remote/MetadataReader.h b/include/swift/Remote/MetadataReader.h index c3eebd87db3..5c404940101 100644 --- a/include/swift/Remote/MetadataReader.h +++ b/include/swift/Remote/MetadataReader.h @@ -544,7 +544,8 @@ public: llvm::Optional readKindFromMetadata(StoredPointer MetadataAddress) { auto meta = readMetadata(MetadataAddress); - if (!meta) return llvm::None; + if (!meta) + return llvm::None; return meta->getKind(); } @@ -1656,9 +1657,9 @@ public: if (classIndex == 0) { return llvm::None; - // If the index is out of range, it's an error; but check for an - // update first. (This will also trigger the first time because - // we initialize LastIndexedClassesCount to 0). + // If the index is out of range, it's an error; but check for an + // update first. (This will also trigger the first time because + // we initialize LastIndexedClassesCount to 0). } else if (classIndex >= LastIndexedClassesCount) { StoredPointer count; if (!Reader->readInteger(RemoteAddress(IndexedClassesCountPointer), @@ -1829,7 +1830,7 @@ public: auto generics = descriptor->getGenericContext(); if (!generics) return llvm::None; - + auto offsetToGenericArgs = readGenericArgsOffset(Meta, descriptor); if (!offsetToGenericArgs) return llvm::None; diff --git a/include/swift/SIL/AbstractionPattern.h b/include/swift/SIL/AbstractionPattern.h index cf226e7d739..755e1168c0b 100644 --- a/include/swift/SIL/AbstractionPattern.h +++ b/include/swift/SIL/AbstractionPattern.h @@ -309,26 +309,35 @@ class AbstractionPattern { assert(errorStripsResultOptionality() == stripsResultOptionality); } - EncodedForeignInfo(Async_t, - unsigned completionParameterIndex, - llvm::Optional completionErrorParameterIndex, - llvm::Optional completionErrorFlagParameterIndex, - bool completionErrorFlagIsZeroOnError) - : Value(1 - + (unsigned(IsAsync) - 1) - + (unsigned(completionParameterIndex) << AsyncCompletionParameterIndexShift) - + ((completionErrorParameterIndex ? *completionErrorParameterIndex + 1 - : 0) << AsyncCompletionErrorParameterIndexShift) - + ((completionErrorFlagParameterIndex ? *completionErrorFlagParameterIndex + 1 - : 0) << AsyncCompletionErrorFlagParameterIndexShift) - + (unsigned(completionErrorFlagIsZeroOnError) << AsyncCompletionErrorFlagParameterPolarityShift)){ + EncodedForeignInfo( + Async_t, unsigned completionParameterIndex, + llvm::Optional completionErrorParameterIndex, + llvm::Optional completionErrorFlagParameterIndex, + bool completionErrorFlagIsZeroOnError) + : Value(1 + (unsigned(IsAsync) - 1) + + (unsigned(completionParameterIndex) + << AsyncCompletionParameterIndexShift) + + ((completionErrorParameterIndex + ? *completionErrorParameterIndex + 1 + : 0) + << AsyncCompletionErrorParameterIndexShift) + + ((completionErrorFlagParameterIndex + ? *completionErrorFlagParameterIndex + 1 + : 0) + << AsyncCompletionErrorFlagParameterIndexShift) + + (unsigned(completionErrorFlagIsZeroOnError) + << AsyncCompletionErrorFlagParameterPolarityShift)) { - assert(getKind() == IsAsync); - assert(getAsyncCompletionHandlerParamIndex() == completionParameterIndex); - assert(getAsyncCompletionHandlerErrorParamIndex() == completionErrorParameterIndex); - assert(getAsyncCompletionHandlerErrorFlagParamIndex() == completionErrorFlagParameterIndex); - assert(isCompletionErrorFlagZeroOnError() == completionErrorFlagIsZeroOnError); - } + assert(getKind() == IsAsync); + assert(getAsyncCompletionHandlerParamIndex() == + completionParameterIndex); + assert(getAsyncCompletionHandlerErrorParamIndex() == + completionErrorParameterIndex); + assert(getAsyncCompletionHandlerErrorFlagParamIndex() == + completionErrorFlagParameterIndex); + assert(isCompletionErrorFlagZeroOnError() == + completionErrorFlagIsZeroOnError); + } public: static EncodedForeignInfo @@ -363,7 +372,7 @@ class AbstractionPattern { return ((Value - 1) & AsyncCompletionParameterIndexMask) >> AsyncCompletionParameterIndexShift; } - + llvm::Optional getAsyncCompletionHandlerErrorParamIndex() const { assert(getKind() == IsAsync); @@ -375,7 +384,8 @@ class AbstractionPattern { return encodedValue - 1; } - llvm::Optional getAsyncCompletionHandlerErrorFlagParamIndex() const { + llvm::Optional + getAsyncCompletionHandlerErrorFlagParamIndex() const { assert(getKind() == IsAsync); unsigned encodedValue = ((Value - 1) & AsyncCompletionErrorFlagParameterIndexMask) @@ -385,7 +395,7 @@ class AbstractionPattern { } return encodedValue - 1; } - + bool isCompletionErrorFlagZeroOnError() const { assert(getKind() == IsAsync); @@ -678,12 +688,11 @@ public: public: /// Return an abstraction pattern for the curried type of an /// Objective-C method. - static AbstractionPattern - getCurriedObjCMethod(CanType origType, const clang::ObjCMethodDecl *method, - const llvm::Optional &foreignError, - const llvm::Optional &foreignAsync); + static AbstractionPattern getCurriedObjCMethod( + CanType origType, const clang::ObjCMethodDecl *method, + const llvm::Optional &foreignError, + const llvm::Optional &foreignAsync); - /// Return an abstraction pattern for the uncurried type of a C function /// imported as a method. /// @@ -1342,7 +1351,8 @@ public: /// /// If the surviving element came from an expansion element, the /// returned element is the pattern type of the expansion. - llvm::Optional getVanishingTupleElementPatternType() const; + llvm::Optional + getVanishingTupleElementPatternType() const; static AbstractionPattern projectTupleElementType(const AbstractionPattern *base, size_t index) { diff --git a/include/swift/SIL/ApplySite.h b/include/swift/SIL/ApplySite.h index 7c403574013..a38e25bb331 100644 --- a/include/swift/SIL/ApplySite.h +++ b/include/swift/SIL/ApplySite.h @@ -564,7 +564,8 @@ struct FullApplySiteKind { FullApplySiteKind(innerty value) : value(value) {} operator innerty() const { return value; } - static llvm::Optional fromNodeKind(SILInstructionKind kind) { + static llvm::Optional + fromNodeKind(SILInstructionKind kind) { if (auto innerOpt = FullApplySiteKind::fromNodeKindHelper(kind)) return FullApplySiteKind(*innerOpt); return llvm::None; diff --git a/include/swift/SIL/DynamicCasts.h b/include/swift/SIL/DynamicCasts.h index 897c6910f96..c1816f446ef 100644 --- a/include/swift/SIL/DynamicCasts.h +++ b/include/swift/SIL/DynamicCasts.h @@ -133,7 +133,8 @@ struct SILDynamicCastKind { SILDynamicCastKind(innerty value) : value(value) {} operator innerty() const { return value; } - static llvm::Optional fromNodeKind(SILInstructionKind kind) { + static llvm::Optional + fromNodeKind(SILInstructionKind kind) { if (auto innerTyOpt = SILDynamicCastKind::fromNodeKindHelper(kind)) return SILDynamicCastKind(*innerTyOpt); return llvm::None; diff --git a/include/swift/SIL/FieldSensitivePrunedLiveness.h b/include/swift/SIL/FieldSensitivePrunedLiveness.h index 8fbd5365bd7..345fdec8faf 100644 --- a/include/swift/SIL/FieldSensitivePrunedLiveness.h +++ b/include/swift/SIL/FieldSensitivePrunedLiveness.h @@ -203,7 +203,7 @@ struct SubElementOffset { /// \returns None if we didn't know how to compute sub-element for this /// projection. static llvm::Optional compute(SILValue projectionFromRoot, - SILValue root) { + SILValue root) { assert(projectionFromRoot->getType().getCategory() == root->getType().getCategory() && "projectionFromRoot and root must both be objects or address."); @@ -222,8 +222,8 @@ struct SubElementOffset { private: static llvm::Optional computeForAddress(SILValue projectionFromRoot, SILValue rootAddress); - static llvm::Optional computeForValue(SILValue projectionFromRoot, - SILValue rootValue); + static llvm::Optional + computeForValue(SILValue projectionFromRoot, SILValue rootValue); }; /// Given a type T, this is the number of leaf field types in T's type tree. A @@ -295,7 +295,7 @@ struct TypeTreeLeafTypeRange { /// \returns None if we are unable to understand the path in between \p /// projectedAddress and \p rootAddress. static llvm::Optional get(SILValue projectedValue, - SILValue rootValue) { + SILValue rootValue) { auto startEltOffset = SubElementOffset::compute(projectedValue, rootValue); if (!startEltOffset) return llvm::None; @@ -726,7 +726,8 @@ public: return; assert(ranges.empty()); - llvm::Optional> current = llvm::None; + llvm::Optional> current = + llvm::None; for (unsigned bit = 0, size = liveBits.size(); bit < size; ++bit) { auto interesting = isInterestingUser(bit); if (!current) { diff --git a/include/swift/SIL/Projection.h b/include/swift/SIL/Projection.h index 751790c5110..2691742a8ee 100644 --- a/include/swift/SIL/Projection.h +++ b/include/swift/SIL/Projection.h @@ -571,7 +571,7 @@ public: /// types via ref_element_addr. If Start is an address type though, End will /// always also be an address type. static llvm::Optional getProjectionPath(SILValue Start, - SILValue End); + SILValue End); /// Treating a projection path as an ordered set, if RHS is a prefix of LHS, /// return the projection path with that prefix removed. diff --git a/include/swift/SIL/SILBuilder.h b/include/swift/SIL/SILBuilder.h index 5183df073e3..73d307140dc 100644 --- a/include/swift/SIL/SILBuilder.h +++ b/include/swift/SIL/SILBuilder.h @@ -395,7 +395,8 @@ public: /// Substitute anonymous function arguments with "_$ArgNo". llvm::Optional substituteAnonymousArgs(llvm::SmallString<4> Name, - llvm::Optional Var, SILLocation Loc) { + llvm::Optional Var, + SILLocation Loc) { if (Var && shouldDropVariable(*Var, Loc)) return {}; if (!Var || !Var->ArgNo || !Var->Name.empty()) @@ -410,13 +411,11 @@ public: return Var; } - AllocStackInst *createAllocStack(SILLocation Loc, SILType elementType, - llvm::Optional Var = llvm::None, - bool hasDynamicLifetime = false, - bool isLexical = false, - bool wasMoved = false, - bool skipVarDeclAssert = false - ) { + AllocStackInst * + createAllocStack(SILLocation Loc, SILType elementType, + llvm::Optional Var = llvm::None, + bool hasDynamicLifetime = false, bool isLexical = false, + bool wasMoved = false, bool skipVarDeclAssert = false) { llvm::SmallString<4> Name; Loc.markAsPrologue(); #ifndef NDEBUG @@ -473,12 +472,12 @@ public: /// Helper function that calls \p createAllocBox after constructing a /// SILBoxType for \p fieldType. - AllocBoxInst *createAllocBox(SILLocation loc, SILType fieldType, - llvm::Optional Var = llvm::None, - bool hasDynamicLifetime = false, - bool reflection = false, - bool usesMoveableValueDebugInfo = false, - bool hasPointerEscape = false) { + AllocBoxInst * + createAllocBox(SILLocation loc, SILType fieldType, + llvm::Optional Var = llvm::None, + bool hasDynamicLifetime = false, bool reflection = false, + bool usesMoveableValueDebugInfo = false, + bool hasPointerEscape = false) { return createAllocBox(loc, SILBoxType::get(fieldType.getASTType()), Var, hasDynamicLifetime, reflection, usesMoveableValueDebugInfo, @@ -486,13 +485,13 @@ public: hasPointerEscape); } - AllocBoxInst *createAllocBox(SILLocation Loc, CanSILBoxType BoxType, - llvm::Optional Var = llvm::None, - bool hasDynamicLifetime = false, - bool reflection = false, - bool usesMoveableValueDebugInfo = false, - bool skipVarDeclAssert = false, - bool hasPointerEscape = false) { + AllocBoxInst * + createAllocBox(SILLocation Loc, CanSILBoxType BoxType, + llvm::Optional Var = llvm::None, + bool hasDynamicLifetime = false, bool reflection = false, + bool usesMoveableValueDebugInfo = false, + bool skipVarDeclAssert = false, + bool hasPointerEscape = false) { #if NDEBUG (void)skipVarDeclAssert; #endif @@ -1698,12 +1697,11 @@ public: getSILDebugLocation(Loc), Operand, Element)); } - SelectEnumInst * - createSelectEnum(SILLocation Loc, SILValue Operand, SILType Ty, - SILValue DefaultValue, - ArrayRef> CaseValues, - llvm::Optional> CaseCounts = llvm::None, - ProfileCounter DefaultCount = ProfileCounter()) { + SelectEnumInst *createSelectEnum( + SILLocation Loc, SILValue Operand, SILType Ty, SILValue DefaultValue, + ArrayRef> CaseValues, + llvm::Optional> CaseCounts = llvm::None, + ProfileCounter DefaultCount = ProfileCounter()) { return createSelectEnum(Loc, Operand, Ty, DefaultValue, CaseValues, CaseCounts, DefaultCount, Operand->getOwnershipKind()); @@ -2549,8 +2547,7 @@ public: SILLocation Loc, SILValue Operand, SILBasicBlock *DefaultBB, ArrayRef> CaseBBs, llvm::Optional> CaseCounts, - ProfileCounter DefaultCount, - ValueOwnershipKind forwardingOwnershipKind) { + ProfileCounter DefaultCount, ValueOwnershipKind forwardingOwnershipKind) { return insertTerminator(SwitchEnumInst::create( getSILDebugLocation(Loc), Operand, DefaultBB, CaseBBs, getFunction(), CaseCounts, DefaultCount, forwardingOwnershipKind)); @@ -2811,7 +2808,8 @@ public: DifferentiableFunctionInst *createDifferentiableFunction( SILLocation Loc, IndexSubset *ParameterIndices, IndexSubset *ResultIndices, SILValue OriginalFunction, - llvm::Optional> JVPAndVJPFunctions = llvm::None) { + llvm::Optional> JVPAndVJPFunctions = + llvm::None) { SILValue jvpAndVJPArray[2]; if (JVPAndVJPFunctions.has_value()) { jvpAndVJPArray[0] = JVPAndVJPFunctions->first; @@ -2840,10 +2838,9 @@ public: OriginalFunction, JVPAndVJPFunctions, forwardingOwnershipKind)); } - LinearFunctionInst * - createLinearFunction(SILLocation Loc, IndexSubset *ParameterIndices, - SILValue OriginalFunction, - llvm::Optional TransposeFunction = llvm::None) { + LinearFunctionInst *createLinearFunction( + SILLocation Loc, IndexSubset *ParameterIndices, SILValue OriginalFunction, + llvm::Optional TransposeFunction = llvm::None) { auto ownershipKind = hasOwnership() ? (TransposeFunction ? mergeSILValueOwnership( @@ -2854,11 +2851,10 @@ public: ownershipKind, TransposeFunction); } - LinearFunctionInst * - createLinearFunction(SILLocation Loc, IndexSubset *ParameterIndices, - SILValue OriginalFunction, - ValueOwnershipKind forwardingOwnershipKind, - llvm::Optional TransposeFunction = llvm::None) { + LinearFunctionInst *createLinearFunction( + SILLocation Loc, IndexSubset *ParameterIndices, SILValue OriginalFunction, + ValueOwnershipKind forwardingOwnershipKind, + llvm::Optional TransposeFunction = llvm::None) { return insert(LinearFunctionInst::create( getModule(), getSILDebugLocation(Loc), ParameterIndices, OriginalFunction, TransposeFunction, forwardingOwnershipKind)); @@ -3185,7 +3181,8 @@ class DebugLocOverrideRAII { #endif public: - DebugLocOverrideRAII(SILBuilder &B, llvm::Optional Loc) : Builder(B) { + DebugLocOverrideRAII(SILBuilder &B, llvm::Optional Loc) + : Builder(B) { oldOverride = B.getCurrentDebugLocOverride(); Builder.applyDebugLocOverride(Loc); #ifndef NDEBUG diff --git a/include/swift/SIL/SILConstants.h b/include/swift/SIL/SILConstants.h index 5b5b7b36cad..ac82b87210e 100644 --- a/include/swift/SIL/SILConstants.h +++ b/include/swift/SIL/SILConstants.h @@ -574,11 +574,12 @@ public: /// arguments along with their symbolic values when available. /// \param allocator the allocator to use for storing the contents of this /// symbolic value. - static SymbolicValue makeClosure( - SILFunction *target, - ArrayRef>> capturedArguments, - SubstitutionMap substMap, SingleValueInstruction *closureInst, - SymbolicValueAllocator &allocator); + static SymbolicValue + makeClosure(SILFunction *target, + ArrayRef>> + capturedArguments, + SubstitutionMap substMap, SingleValueInstruction *closureInst, + SymbolicValueAllocator &allocator); SymbolicClosure *getClosure() const { assert(getKind() == Closure); @@ -670,7 +671,8 @@ private: void operator=(const SymbolicValueMemoryObject &) = delete; }; -using SymbolicClosureArgument = std::pair>; +using SymbolicClosureArgument = + std::pair>; /// Representation of a symbolic closure. A symbolic closure consists of a /// SILFunction and an array of SIL values, corresponding to the captured diff --git a/include/swift/SIL/SILDebugVariable.h b/include/swift/SIL/SILDebugVariable.h index f79c4e81415..bffc9a4cfb5 100644 --- a/include/swift/SIL/SILDebugVariable.h +++ b/include/swift/SIL/SILDebugVariable.h @@ -64,7 +64,8 @@ struct SILDebugVariable { : ArgNo(ArgNo), Constant(Constant), Implicit(false), isDenseMapSingleton(0), Scope(nullptr) {} SILDebugVariable(StringRef Name, bool Constant, unsigned ArgNo, - bool IsImplicit = false, llvm::Optional AuxType = {}, + bool IsImplicit = false, + llvm::Optional AuxType = {}, llvm::Optional DeclLoc = {}, const SILDebugScope *DeclScope = nullptr, llvm::ArrayRef ExprElements = {}) diff --git a/include/swift/SIL/SILFunction.h b/include/swift/SIL/SILFunction.h index 4e41960feba..45459f4da0a 100644 --- a/include/swift/SIL/SILFunction.h +++ b/include/swift/SIL/SILFunction.h @@ -474,8 +474,7 @@ private: ProfileCounter entryCount, IsDynamicallyReplaceable_t isDynamic, IsDistributed_t isDistributed, IsRuntimeAccessible_t isRuntimeAccessible, - IsExactSelfClass_t isExactSelfClass, - IsThunk_t isThunk = IsNotThunk, + IsExactSelfClass_t isExactSelfClass, IsThunk_t isThunk = IsNotThunk, SubclassScope classSubclassScope = SubclassScope::NotApplicable, Inline_t inlineStrategy = InlineDefault, EffectsKind EffectsKindAttr = EffectsKind::Unspecified, diff --git a/include/swift/SIL/SILFunctionBuilder.h b/include/swift/SIL/SILFunctionBuilder.h index b3986022bfd..6cd18935a1d 100644 --- a/include/swift/SIL/SILFunctionBuilder.h +++ b/include/swift/SIL/SILFunctionBuilder.h @@ -100,21 +100,19 @@ class SILFunctionBuilder { /// This signature is a direct copy of the signature of SILFunction::create() /// in order to simplify refactoring all SILFunction creation use-sites to use /// SILFunctionBuilder. Eventually the uses should probably be refactored. - SILFunction * - createFunction(SILLinkage linkage, StringRef name, - CanSILFunctionType loweredType, GenericEnvironment *genericEnv, - llvm::Optional loc, IsBare_t isBareSILFunction, - IsTransparent_t isTrans, IsSerialized_t isSerialized, - IsDynamicallyReplaceable_t isDynamic, - IsDistributed_t isDistributed, - IsRuntimeAccessible_t isRuntimeAccessible, - ProfileCounter entryCount = ProfileCounter(), - IsThunk_t isThunk = IsNotThunk, - SubclassScope subclassScope = SubclassScope::NotApplicable, - Inline_t inlineStrategy = InlineDefault, - EffectsKind EK = EffectsKind::Unspecified, - SILFunction *InsertBefore = nullptr, - const SILDebugScope *DebugScope = nullptr); + SILFunction *createFunction( + SILLinkage linkage, StringRef name, CanSILFunctionType loweredType, + GenericEnvironment *genericEnv, llvm::Optional loc, + IsBare_t isBareSILFunction, IsTransparent_t isTrans, + IsSerialized_t isSerialized, IsDynamicallyReplaceable_t isDynamic, + IsDistributed_t isDistributed, IsRuntimeAccessible_t isRuntimeAccessible, + ProfileCounter entryCount = ProfileCounter(), + IsThunk_t isThunk = IsNotThunk, + SubclassScope subclassScope = SubclassScope::NotApplicable, + Inline_t inlineStrategy = InlineDefault, + EffectsKind EK = EffectsKind::Unspecified, + SILFunction *InsertBefore = nullptr, + const SILDebugScope *DebugScope = nullptr); void addFunctionAttributes( SILFunction *F, DeclAttributes &Attrs, SILModule &M, diff --git a/include/swift/SIL/SILGlobalVariable.h b/include/swift/SIL/SILGlobalVariable.h index 1a60574bfc0..e58310b5aba 100644 --- a/include/swift/SIL/SILGlobalVariable.h +++ b/include/swift/SIL/SILGlobalVariable.h @@ -96,10 +96,10 @@ private: SILBasicBlock StaticInitializerBlock; SILGlobalVariable(SILModule &M, SILLinkage linkage, - IsSerialized_t IsSerialized, - StringRef mangledName, SILType loweredType, - llvm::Optional loc, VarDecl *decl); - + IsSerialized_t IsSerialized, StringRef mangledName, + SILType loweredType, llvm::Optional loc, + VarDecl *decl); + public: static void registerBridgedMetatype(SwiftMetatype metatype) { registeredMetatype = metatype; diff --git a/include/swift/SIL/SILInstruction.h b/include/swift/SIL/SILInstruction.h index 2bc6e4db07c..4acb06d2047 100644 --- a/include/swift/SIL/SILInstruction.h +++ b/include/swift/SIL/SILInstruction.h @@ -1995,7 +1995,8 @@ class AllocStackInst final bool isLexical, bool usesMoveableValueDebugInfo); static AllocStackInst *create(SILDebugLocation Loc, SILType elementType, - SILFunction &F, llvm::Optional Var, + SILFunction &F, + llvm::Optional Var, bool hasDynamicLifetime, bool isLexical, bool usesMoveableValueDebugInfo); @@ -2384,7 +2385,8 @@ class AllocBoxInst final bool hasPointerEscape = false); static AllocBoxInst *create(SILDebugLocation Loc, CanSILBoxType boxType, - SILFunction &F, llvm::Optional Var, + SILFunction &F, + llvm::Optional Var, bool hasDynamicLifetime, bool reflection = false, bool usesMoveableValueDebugInfo = false, bool hasPointerEscape = false); @@ -2744,9 +2746,11 @@ public: /// and, if so, return that index. llvm::Optional getArgumentIndexForOperandIndex(unsigned index) { assert(index < getNumAllOperands()); - if (index < NumStaticOperands) return llvm::None; + if (index < NumStaticOperands) + return llvm::None; index -= NumStaticOperands; - if (index >= NumCallArguments) return llvm::None; + if (index >= NumCallArguments) + return llvm::None; return index; } @@ -2950,8 +2954,7 @@ class ApplyInst final create(SILDebugLocation DebugLoc, SILValue Callee, SubstitutionMap Substitutions, ArrayRef Args, ApplyOptions options, - llvm::Optional ModuleConventions, - SILFunction &F, + llvm::Optional ModuleConventions, SILFunction &F, const GenericSpecializationInformation *SpecializationInfo); }; @@ -3039,8 +3042,8 @@ class BeginApplyInst final static BeginApplyInst * create(SILDebugLocation debugLoc, SILValue Callee, SubstitutionMap substitutions, ArrayRef args, - ApplyOptions options, llvm::Optional moduleConventions, - SILFunction &F, + ApplyOptions options, + llvm::Optional moduleConventions, SILFunction &F, const GenericSpecializationInformation *specializationInfo); public: @@ -6541,13 +6544,12 @@ protected: sharedUInt8().SelectEnumInstBase.hasDefault = defaultValue; } template - static SELECT_ENUM_INST * - createSelectEnum(SILDebugLocation DebugLoc, SILValue Enum, SILType Type, - SILValue DefaultValue, - ArrayRef> CaseValues, - SILModule &M, llvm::Optional> CaseCounts, - ProfileCounter DefaultCount, - ValueOwnershipKind forwardingOwnershipKind); + static SELECT_ENUM_INST *createSelectEnum( + SILDebugLocation DebugLoc, SILValue Enum, SILType Type, + SILValue DefaultValue, + ArrayRef> CaseValues, SILModule &M, + llvm::Optional> CaseCounts, + ProfileCounter DefaultCount, ValueOwnershipKind forwardingOwnershipKind); public: ArrayRef getAllOperands() const; @@ -9614,7 +9616,8 @@ public: return getSuccessorBuf()[getNumCases()]; } - llvm::Optional getUniqueCaseForDestination(SILBasicBlock *bb) const { + llvm::Optional + getUniqueCaseForDestination(SILBasicBlock *bb) const { for (unsigned i = 0; i < getNumCases(); ++i) { if (getCase(i).second == bb) { return i + 1; @@ -9662,8 +9665,8 @@ protected: SILInstructionKind Kind, SILDebugLocation DebugLoc, SILValue Operand, SILBasicBlock *DefaultBB, ArrayRef> CaseBBs, - llvm::Optional> Counts, ProfileCounter DefaultCount, - Rest &&... rest) + llvm::Optional> Counts, + ProfileCounter DefaultCount, Rest &&...rest) : BaseTy(Kind, DebugLoc, std::forward(rest)...), Operands(this, Operand) { sharedUInt8().SwitchEnumInstBase.hasDefault = bool(DefaultBB); @@ -9691,7 +9694,7 @@ protected: SILDebugLocation DebugLoc, SILValue Operand, SILBasicBlock *DefaultBB, ArrayRef> CaseBBs, SILFunction &F, llvm::Optional> Counts, - ProfileCounter DefaultCount, RestTys &&... restArgs); + ProfileCounter DefaultCount, RestTys &&...restArgs); public: /// Clean up tail-allocated successor records for the switch cases. @@ -10389,7 +10392,8 @@ public: bool hasTransposeFunction() const { return HasTransposeFunction; } SILValue getOriginalFunction() const { return getOperand(0); } llvm::Optional getOptionalTransposeFunction() const { - return HasTransposeFunction ? llvm::Optional(getOperand(1)) : llvm::None; + return HasTransposeFunction ? llvm::Optional(getOperand(1)) + : llvm::None; } SILValue getTransposeFunction() const { assert(HasTransposeFunction); @@ -10554,7 +10558,8 @@ public: DifferentiabilityWitnessFunctionInst( SILModule &module, SILDebugLocation loc, DifferentiabilityWitnessFunctionKind witnessKind, - SILDifferentiabilityWitness *witness, llvm::Optional FunctionType); + SILDifferentiabilityWitness *witness, + llvm::Optional FunctionType); DifferentiabilityWitnessFunctionKind getWitnessKind() const { return witnessKind; diff --git a/include/swift/SIL/SILModule.h b/include/swift/SIL/SILModule.h index 4a0bce12668..f55f4b24334 100644 --- a/include/swift/SIL/SILModule.h +++ b/include/swift/SIL/SILModule.h @@ -771,8 +771,7 @@ public: /// /// If \p linkage is provided, the deserialized function is required to have /// that linkage. Returns null, if this is not the case. - SILFunction *loadFunction(StringRef name, - LinkingMode LinkMode, + SILFunction *loadFunction(StringRef name, LinkingMode LinkMode, llvm::Optional linkage = llvm::None); /// Update the linkage of the SILFunction with the linkage of the serialized diff --git a/include/swift/SIL/SILProperty.h b/include/swift/SIL/SILProperty.h index e22a735ce56..3eab2ded2f6 100644 --- a/include/swift/SIL/SILProperty.h +++ b/include/swift/SIL/SILProperty.h @@ -44,18 +44,15 @@ private: /// The key path component that represents its implementation. llvm::Optional Component; - SILProperty(bool Serialized, - AbstractStorageDecl *Decl, + SILProperty(bool Serialized, AbstractStorageDecl *Decl, llvm::Optional Component) - : Serialized(Serialized), Decl(Decl), Component(Component) - {} + : Serialized(Serialized), Decl(Decl), Component(Component) {} public: - static SILProperty *create(SILModule &M, - bool Serialized, + static SILProperty *create(SILModule &M, bool Serialized, AbstractStorageDecl *Decl, llvm::Optional Component); - + bool isSerialized() const { return Serialized; } AbstractStorageDecl *getDecl() const { return Decl; } @@ -63,11 +60,11 @@ public: bool isTrivial() const { return !Component.has_value(); } - + const llvm::Optional &getComponent() const { return Component; } - + void print(SILPrintContext &Ctx) const; void dump() const; diff --git a/include/swift/SIL/TypeLowering.h b/include/swift/SIL/TypeLowering.h index a29dcfa4c8e..f759751c1f2 100644 --- a/include/swift/SIL/TypeLowering.h +++ b/include/swift/SIL/TypeLowering.h @@ -805,16 +805,16 @@ class TypeConverter { /// /// Second element is a ResilienceExpansion. llvm::DenseMap, unsigned> TypeFields; - + llvm::DenseMap> - ClosureAbstractionPatterns; + ClosureAbstractionPatterns; llvm::DenseMap CaptureTypeExpansionContexts; CanAnyFunctionType makeConstantInterfaceType(SILDeclRef constant); // Types converted during foreign bridging. -#define BRIDGING_KNOWN_TYPE(BridgedModule,BridgedType) \ +#define BRIDGING_KNOWN_TYPE(BridgedModule, BridgedType) \ llvm::Optional BridgedType##Ty; #include "swift/SIL/BridgedTypes.def" @@ -1213,7 +1213,8 @@ public: /// This can be set using \c setAbstractionPattern , but only before /// the abstraction pattern is queried using this function. Once the /// abstraction pattern has been asked for, it may not be changed. - llvm::Optional getConstantAbstractionPattern(SILDeclRef constant); + llvm::Optional + getConstantAbstractionPattern(SILDeclRef constant); TypeExpansionContext getCaptureTypeExpansionContext(SILDeclRef constant); /// Set the preferred abstraction pattern for a closure. @@ -1262,16 +1263,15 @@ private: void verifyLowering(const TypeLowering &, AbstractionPattern origType, CanType origSubstType, TypeExpansionContext forExpansion); - bool - visitAggregateLeaves(Lowering::AbstractionPattern origType, - CanType substType, - TypeExpansionContext context, - std::function)> - isLeafAggregate, - std::function)> - visit); + bool visitAggregateLeaves( + Lowering::AbstractionPattern origType, CanType substType, + TypeExpansionContext context, + std::function)> + isLeafAggregate, + std::function)> + visit); #endif }; @@ -1307,16 +1307,13 @@ enum class DifferentiationThunkKind { /// Build the type of a function transformation thunk. CanSILFunctionType buildSILFunctionThunkType( - SILFunction *fn, - CanSILFunctionType &sourceType, - CanSILFunctionType &expectedType, - CanType &inputSubstType, - CanType &outputSubstType, - GenericEnvironment *&genericEnv, - SubstitutionMap &interfaceSubs, - CanType &dynamicSelfType, + SILFunction *fn, CanSILFunctionType &sourceType, + CanSILFunctionType &expectedType, CanType &inputSubstType, + CanType &outputSubstType, GenericEnvironment *&genericEnv, + SubstitutionMap &interfaceSubs, CanType &dynamicSelfType, bool withoutActuallyEscaping, - llvm::Optional differentiationThunkKind = llvm::None); + llvm::Optional differentiationThunkKind = + llvm::None); } // namespace swift diff --git a/include/swift/SILOptimizer/Analysis/ARCAnalysis.h b/include/swift/SILOptimizer/Analysis/ARCAnalysis.h index 62c188f079b..f976c5f62c0 100644 --- a/include/swift/SILOptimizer/Analysis/ARCAnalysis.h +++ b/include/swift/SILOptimizer/Analysis/ARCAnalysis.h @@ -88,17 +88,18 @@ bool mayGuaranteedUseValue(SILInstruction *User, SILValue Ptr, /// first such instruction. Otherwise return None. We assume that /// Start and End are both in the same basic block. llvm::Optional -valueHasARCUsesInInstructionRange(SILValue Op, - SILBasicBlock::iterator Start, +valueHasARCUsesInInstructionRange(SILValue Op, SILBasicBlock::iterator Start, SILBasicBlock::iterator End, AliasAnalysis *AA); /// If \p Op has arc uses in the instruction range [Start, End), return the last /// use of such instruction. Otherwise return None. We assume that Start and End /// are both in the same basic block. -llvm::Optional valueHasARCUsesInReverseInstructionRange( - SILValue Op, SILBasicBlock::iterator Start, SILBasicBlock::iterator End, - AliasAnalysis *AA); +llvm::Optional +valueHasARCUsesInReverseInstructionRange(SILValue Op, + SILBasicBlock::iterator Start, + SILBasicBlock::iterator End, + AliasAnalysis *AA); /// If \p Op has instructions in the instruction range (Start, End] which may /// decrement it, return the first such instruction. Returns None @@ -233,7 +234,8 @@ private: /// set. /// /// *NOTE* This returns none if we did not find any releases. - llvm::Optional> getPartiallyPostDomReleases() const { + llvm::Optional> + getPartiallyPostDomReleases() const { if (releases.empty() || !foundSomeButNotAllReleases()) return llvm::None; return ArrayRef(releases); diff --git a/include/swift/SILOptimizer/Analysis/AccessStorageAnalysis.h b/include/swift/SILOptimizer/Analysis/AccessStorageAnalysis.h index 2047d12961a..fdd94b36376 100644 --- a/include/swift/SILOptimizer/Analysis/AccessStorageAnalysis.h +++ b/include/swift/SILOptimizer/Analysis/AccessStorageAnalysis.h @@ -146,7 +146,9 @@ public: return storageAccessSet.empty() && !unidentifiedAccess; } - bool hasUnidentifiedAccess() const { return unidentifiedAccess != llvm::None; } + bool hasUnidentifiedAccess() const { + return unidentifiedAccess != llvm::None; + } /// Return true if the analysis has determined all accesses of otherStorage /// have the [no_nested_conflict] flag set. diff --git a/include/swift/SILOptimizer/Analysis/LoopRegionAnalysis.h b/include/swift/SILOptimizer/Analysis/LoopRegionAnalysis.h index f2cde629bb6..945469dc760 100644 --- a/include/swift/SILOptimizer/Analysis/LoopRegionAnalysis.h +++ b/include/swift/SILOptimizer/Analysis/LoopRegionAnalysis.h @@ -206,13 +206,15 @@ public: unsigned asInt() const { return *reinterpret_cast(this); } struct ToLiveSucc { - llvm::Optional operator()(llvm::Optional ID) const { + llvm::Optional + operator()(llvm::Optional ID) const { return ID; } }; struct ToLiveLocalSucc { - llvm::Optional operator()(llvm::Optional ID) const { + llvm::Optional + operator()(llvm::Optional ID) const { if (!ID) return llvm::None; if ((*ID).IsNonLocal) @@ -222,7 +224,8 @@ public: }; struct ToLiveNonLocalSucc { - llvm::Optional operator()(llvm::Optional ID) const { + llvm::Optional + operator()(llvm::Optional ID) const { if (!ID) return llvm::None; if (!(*ID).IsNonLocal) diff --git a/include/swift/SILOptimizer/Differentiation/ADContext.h b/include/swift/SILOptimizer/Differentiation/ADContext.h index 932d344e23b..070345b5f02 100644 --- a/include/swift/SILOptimizer/Differentiation/ADContext.h +++ b/include/swift/SILOptimizer/Differentiation/ADContext.h @@ -217,7 +217,8 @@ public: DifferentiableFunctionInst *createDifferentiableFunction( SILBuilder &builder, SILLocation loc, IndexSubset *parameterIndices, IndexSubset *resultIndices, SILValue original, - llvm::Optional> derivativeFunctions = llvm::None); + llvm::Optional> derivativeFunctions = + llvm::None); /// Creates a `linear_function` instruction using the given builder /// and arguments. Erase the newly created instruction from the processed set, diff --git a/include/swift/SILOptimizer/Differentiation/AdjointValue.h b/include/swift/SILOptimizer/Differentiation/AdjointValue.h index bdd4e9a1518..ac3a6ead25b 100644 --- a/include/swift/SILOptimizer/Differentiation/AdjointValue.h +++ b/include/swift/SILOptimizer/Differentiation/AdjointValue.h @@ -103,24 +103,24 @@ public: using DebugInfo = AdjointValueBase::DebugInfo; - static AdjointValue createConcrete( - llvm::BumpPtrAllocator &allocator, SILValue value, - llvm::Optional debugInfo = llvm::None) { + static AdjointValue + createConcrete(llvm::BumpPtrAllocator &allocator, SILValue value, + llvm::Optional debugInfo = llvm::None) { auto *buf = allocator.Allocate(); return new (buf) AdjointValueBase(value, debugInfo); } - static AdjointValue createZero( - llvm::BumpPtrAllocator &allocator, SILType type, - llvm::Optional debugInfo = llvm::None) { + static AdjointValue + createZero(llvm::BumpPtrAllocator &allocator, SILType type, + llvm::Optional debugInfo = llvm::None) { auto *buf = allocator.Allocate(); return new (buf) AdjointValueBase(type, debugInfo); } - static AdjointValue createAggregate( - llvm::BumpPtrAllocator &allocator, SILType type, - ArrayRef elements, - llvm::Optional debugInfo = llvm::None) { + static AdjointValue + createAggregate(llvm::BumpPtrAllocator &allocator, SILType type, + ArrayRef elements, + llvm::Optional debugInfo = llvm::None) { AdjointValue *buf = reinterpret_cast(allocator.Allocate( sizeof(AdjointValueBase) + elements.size() * sizeof(AdjointValue), alignof(AdjointValueBase))); diff --git a/include/swift/SILOptimizer/Utils/CompileTimeInterpolationUtils.h b/include/swift/SILOptimizer/Utils/CompileTimeInterpolationUtils.h index 191c0079093..6ca14dd8b96 100644 --- a/include/swift/SILOptimizer/Utils/CompileTimeInterpolationUtils.h +++ b/include/swift/SILOptimizer/Utils/CompileTimeInterpolationUtils.h @@ -33,7 +33,8 @@ bool shouldAttemptEvaluation(SILInstruction *inst); /// Skip or evaluate the given instruction based on the evaluation policy and /// handle errors. The policy is to evaluate all non-apply instructions as well /// as apply instructions that are marked as "constant_evaluable". -std::pair, llvm::Optional> +std::pair, + llvm::Optional> evaluateOrSkip(ConstExprStepEvaluator &stepEval, SILBasicBlock::iterator instI); /// Given a vector of SILValues \p worklist, compute the set of transitive diff --git a/include/swift/SILOptimizer/Utils/ConstExpr.h b/include/swift/SILOptimizer/Utils/ConstExpr.h index 775ccf4b61b..a45d70c11dd 100644 --- a/include/swift/SILOptimizer/Utils/ConstExpr.h +++ b/include/swift/SILOptimizer/Utils/ConstExpr.h @@ -149,7 +149,8 @@ public: /// /// Second element is None, if the evaluation is successful. /// Otherwise, is an unknown symbolic value that contains the error. - std::pair, llvm::Optional> + std::pair, + llvm::Optional> evaluate(SILBasicBlock::iterator instI); /// Skip the instruction without evaluating it and conservatively account for @@ -168,7 +169,8 @@ public: /// /// Second element is None if skipping the instruction is successful. /// Otherwise, it is an unknown symbolic value containing the error. - std::pair, llvm::Optional> + std::pair, + llvm::Optional> skipByMakingEffectsNonConstant(SILBasicBlock::iterator instI); /// Try evaluating an instruction and if the evaluation fails, skip the @@ -187,7 +189,8 @@ public: /// /// Second element is None if the evaluation is successful. /// Otherwise, it is an unknown symbolic value containing the error. - std::pair, llvm::Optional> + std::pair, + llvm::Optional> tryEvaluateOrElseMakeEffectsNonConstant(SILBasicBlock::iterator instI); llvm::Optional lookupConstValue(SILValue value); diff --git a/include/swift/SILOptimizer/Utils/LoadStoreOptUtils.h b/include/swift/SILOptimizer/Utils/LoadStoreOptUtils.h index abbfe4ea1ab..0b0848b837e 100644 --- a/include/swift/SILOptimizer/Utils/LoadStoreOptUtils.h +++ b/include/swift/SILOptimizer/Utils/LoadStoreOptUtils.h @@ -66,7 +66,8 @@ public: LSBase() : Base(), Kind(Normal) {} LSBase(KeyKind Kind) : Base(), Kind(Kind) {} LSBase(SILValue B) : Base(B), Kind(Normal) {} - LSBase(SILValue B, const llvm::Optional &P, KeyKind Kind = Normal) + LSBase(SILValue B, const llvm::Optional &P, + KeyKind Kind = Normal) : Base(B), Kind(Kind), Path(P) {} /// Virtual destructor. @@ -323,7 +324,8 @@ class LSLocation : public LSBase { public: /// Constructors. LSLocation() {} - LSLocation(SILValue B, const llvm::Optional &P, KeyKind K = Normal) + LSLocation(SILValue B, const llvm::Optional &P, + KeyKind K = Normal) : LSBase(B, P, K) {} LSLocation(KeyKind Kind) : LSBase(Kind) {} /// Use the concatenation of the 2 ProjectionPaths as the Path. @@ -336,7 +338,8 @@ public: } /// Initialize a location with a new set of base, projectionpath and kind. - void init(SILValue B, const llvm::Optional &P, KeyKind K= Normal) { + void init(SILValue B, const llvm::Optional &P, + KeyKind K = Normal) { Base = B; Path = P; Kind = K; diff --git a/include/swift/Sema/CSFix.h b/include/swift/Sema/CSFix.h index 8a100defb50..71341977f3d 100644 --- a/include/swift/Sema/CSFix.h +++ b/include/swift/Sema/CSFix.h @@ -1641,14 +1641,16 @@ class AllowTupleTypeMismatch final : public ContextualMismatch { llvm::Optional Index; AllowTupleTypeMismatch(ConstraintSystem &cs, Type lhs, Type rhs, - ConstraintLocator *locator, llvm::Optional index) + ConstraintLocator *locator, + llvm::Optional index) : ContextualMismatch(cs, FixKind::AllowTupleTypeMismatch, lhs, rhs, - locator), Index(index) {} + locator), + Index(index) {} public: - static AllowTupleTypeMismatch *create(ConstraintSystem &cs, Type lhs, - Type rhs, ConstraintLocator *locator, - llvm::Optional index = llvm::None); + static AllowTupleTypeMismatch * + create(ConstraintSystem &cs, Type lhs, Type rhs, ConstraintLocator *locator, + llvm::Optional index = llvm::None); static bool classof(const ConstraintFix *fix) { return fix->getKind() == FixKind::AllowTupleTypeMismatch; @@ -3425,10 +3427,11 @@ public: openedExistentials, ConstraintLocatorBuilder locator); - static bool isRequired(ConstraintSystem &cs, Type resultTy, - llvm::function_ref(TypeVariableType *)> - findExistentialType, - ConstraintLocatorBuilder locator); + static bool + isRequired(ConstraintSystem &cs, Type resultTy, + llvm::function_ref(TypeVariableType *)> + findExistentialType, + ConstraintLocatorBuilder locator); static AddExplicitExistentialCoercion *create(ConstraintSystem &cs, Type resultTy, diff --git a/include/swift/Sema/ConstraintLocator.h b/include/swift/Sema/ConstraintLocator.h index 7b1f4bebf6c..76399a66948 100644 --- a/include/swift/Sema/ConstraintLocator.h +++ b/include/swift/Sema/ConstraintLocator.h @@ -1389,7 +1389,8 @@ public: // Next, check the constraint locator itself. if (auto locator = previous.dyn_cast()) { auto path = locator->getPath(); - if (path.empty()) return llvm::None; + if (path.empty()) + return llvm::None; return path.back(); } diff --git a/include/swift/Sema/ConstraintSystem.h b/include/swift/Sema/ConstraintSystem.h index d90b588fbff..8b1d5256325 100644 --- a/include/swift/Sema/ConstraintSystem.h +++ b/include/swift/Sema/ConstraintSystem.h @@ -1942,8 +1942,8 @@ struct DynamicCallableMethods { /// A function that rewrites a syntactic element target in the context /// of solution application. -using RewriteTargetFn = - std::function(SyntacticElementTarget)>; +using RewriteTargetFn = std::function( + SyntacticElementTarget)>; enum class ConstraintSystemPhase { ConstraintGeneration, @@ -2089,7 +2089,7 @@ private: /// Cached member lookups. llvm::DenseMap, llvm::Optional> - MemberLookups; + MemberLookups; /// Folding set containing all of the locators used in this /// constraint system. @@ -3202,8 +3202,8 @@ public: (void)inserted; } - llvm::Optional getCaseLabelItemInfo( - const CaseLabelItem *item) const { + llvm::Optional + getCaseLabelItemInfo(const CaseLabelItem *item) const { auto known = caseLabelItems.find(item); if (known == caseLabelItems.end()) return llvm::None; @@ -3495,11 +3495,11 @@ public: /// /// \returns the joined type, which is generally a new type variable, unless there are /// fewer than 2 input types or the \c supertype parameter is specified. - template - Type addJoinConstraint(ConstraintLocator *locator, - Iterator begin, Iterator end, - llvm::Optional supertype, - std::function(Iterator)> getType) { + template + Type addJoinConstraint( + ConstraintLocator *locator, Iterator begin, Iterator end, + llvm::Optional supertype, + std::function(Iterator)> getType) { if (begin == end) return Type(); @@ -4239,7 +4239,8 @@ private: /// /// \returns The constraint found along with the number of optional object /// constraints looked through, or \c None if no constraint was found. - llvm::Optional> findConstraintThroughOptionals( + llvm::Optional> + findConstraintThroughOptionals( TypeVariableType *typeVar, OptionalWrappingDirection optionalDirection, llvm::function_ref predicate); @@ -4406,7 +4407,8 @@ public: void generateConstraints( SmallVectorImpl &constraints, Type type, ArrayRef choices, DeclContext *useDC, - ConstraintLocator *locator, llvm::Optional favoredIndex = llvm::None, + ConstraintLocator *locator, + llvm::Optional favoredIndex = llvm::None, bool requiresFix = false, llvm::function_ref getFix = [](unsigned, const OverloadChoice &) { return nullptr; }); @@ -5135,9 +5137,10 @@ public: /// /// \returns a solution if a single unambiguous one could be found, or None if /// ambiguous or unsolvable. - llvm::Optional solveSingle(FreeTypeVariableBinding allowFreeTypeVariables - = FreeTypeVariableBinding::Disallow, - bool allowFixes = false); + llvm::Optional + solveSingle(FreeTypeVariableBinding allowFreeTypeVariables = + FreeTypeVariableBinding::Disallow, + bool allowFixes = false); /// Assuming that constraints have already been generated, solve the /// constraint system for code completion, writing all solutions to @@ -5202,20 +5205,19 @@ public: /// \returns The index of the best solution, or nothing if there was no /// best solution. llvm::Optional - findBestSolution(SmallVectorImpl &solutions, - bool minimize); + findBestSolution(SmallVectorImpl &solutions, bool minimize); public: /// Apply a given solution to the target, producing a fully /// type-checked target or \c None if an error occurred. /// /// \param target the target to which the solution will be applied. - llvm::Optional applySolution(Solution &solution, - SyntacticElementTarget target); + llvm::Optional + applySolution(Solution &solution, SyntacticElementTarget target); /// Apply the given solution to the given statement-condition. - llvm::Optional applySolution( - Solution &solution, StmtCondition condition, DeclContext *dc); + llvm::Optional + applySolution(Solution &solution, StmtCondition condition, DeclContext *dc); /// Apply the given solution to the given function's body and, for /// closure expressions, the expression itself. @@ -5227,10 +5229,11 @@ public: /// \param rewriteTarget Function that performs a rewrite of any targets /// within the context. /// - SolutionApplicationToFunctionResult applySolution( - Solution &solution, AnyFunctionRef fn, DeclContext *¤tDC, - std::function(SyntacticElementTarget)> - rewriteTarget); + SolutionApplicationToFunctionResult + applySolution(Solution &solution, AnyFunctionRef fn, DeclContext *¤tDC, + std::function( + SyntacticElementTarget)> + rewriteTarget); /// Apply the given solution to the given closure body. /// @@ -5243,10 +5246,11 @@ public: /// within the context. /// /// \returns true if solution cannot be applied. - bool applySolutionToBody( - Solution &solution, AnyFunctionRef fn, DeclContext *¤tDC, - std::function(SyntacticElementTarget)> - rewriteTarget); + bool applySolutionToBody(Solution &solution, AnyFunctionRef fn, + DeclContext *¤tDC, + std::function( + SyntacticElementTarget)> + rewriteTarget); /// Apply the given solution to the given SingleValueStmtExpr. /// @@ -5260,7 +5264,8 @@ public: /// \returns true if solution cannot be applied. bool applySolutionToSingleValueStmt( Solution &solution, SingleValueStmtExpr *SVE, DeclContext *DC, - std::function(SyntacticElementTarget)> + std::function< + llvm::Optional(SyntacticElementTarget)> rewriteTarget); /// Reorder the disjunctive clauses for a given expression to @@ -5503,7 +5508,7 @@ public: /// \param argInsertIdx The index in the argument list where this argument was /// expected. virtual llvm::Optional missingArgument(unsigned paramIdx, - unsigned argInsertIdx); + unsigned argInsertIdx); /// Indicate that there was no label given when one was expected by parameter. /// @@ -5581,7 +5586,7 @@ struct CompletionArgInfo { /// from the provided anchor if it's a \c CallExpr, \c SubscriptExpr, or /// \c ObjectLiteralExpr. llvm::Optional getCompletionArgInfo(ASTNode anchor, - ConstraintSystem &cs); + ConstraintSystem &cs); /// Match the call arguments (as described by the given argument type) to /// the parameters (as described by the given parameter type). @@ -5602,13 +5607,10 @@ llvm::Optional getCompletionArgInfo(ASTNode anchor, /// /// \returns the bindings produced by performing this matching, or \c None if /// the match failed. -llvm::Optional -matchCallArguments( +llvm::Optional matchCallArguments( SmallVectorImpl &args, - ArrayRef params, - const ParameterListInfo ¶mInfo, - llvm::Optional unlabeledTrailingClosureIndex, - bool allowFixes, + ArrayRef params, const ParameterListInfo ¶mInfo, + llvm::Optional unlabeledTrailingClosureIndex, bool allowFixes, MatchCallArgumentListener &listener, llvm::Optional trailingClosureMatching); diff --git a/include/swift/Sema/IDETypeChecking.h b/include/swift/Sema/IDETypeChecking.h index 8265b09801a..f68b6394411 100644 --- a/include/swift/Sema/IDETypeChecking.h +++ b/include/swift/Sema/IDETypeChecking.h @@ -125,11 +125,8 @@ namespace swift { /// Return the type of an expression parsed during code completion, or /// None on error. llvm::Optional getTypeOfCompletionContextExpr( - ASTContext &Ctx, - DeclContext *DC, - CompletionTypeCheckKind kind, - Expr *&parsedExpr, - ConcreteDeclRef &referencedDecl); + ASTContext &Ctx, DeclContext *DC, CompletionTypeCheckKind kind, + Expr *&parsedExpr, ConcreteDeclRef &referencedDecl); /// Resolve type of operator function with \c opName appending it to \c LHS. /// @@ -320,10 +317,11 @@ namespace swift { /// Print the declaration for a result builder "build" function, for use /// in Fix-Its, code completion, and so on. - void printResultBuilderBuildFunction( - NominalTypeDecl *builder, Type componentType, - ResultBuilderBuildFunction function, - llvm::Optional stubIndent, llvm::raw_ostream &out); + void printResultBuilderBuildFunction(NominalTypeDecl *builder, + Type componentType, + ResultBuilderBuildFunction function, + llvm::Optional stubIndent, + llvm::raw_ostream &out); /// Compute the insertion location, indentation string, and component type /// for a Fix-It that adds a new build* function to a result builder. diff --git a/include/swift/Sema/SourceLoader.h b/include/swift/Sema/SourceLoader.h index fb2c314efaf..cc09b3146f2 100644 --- a/include/swift/Sema/SourceLoader.h +++ b/include/swift/Sema/SourceLoader.h @@ -97,7 +97,7 @@ public: // Parsing populates the Objective-C method tables. } - llvm::Optional + llvm::Optional getModuleDependencies(StringRef moduleName, ModuleDependenciesCache &cache, InterfaceSubContextDelegate &delegate, bool isTestableImport) override; diff --git a/include/swift/Serialization/ModuleDependencyScanner.h b/include/swift/Serialization/ModuleDependencyScanner.h index b0fa563614f..c0d10732df1 100644 --- a/include/swift/Serialization/ModuleDependencyScanner.h +++ b/include/swift/Serialization/ModuleDependencyScanner.h @@ -44,14 +44,15 @@ namespace swift { std::string moduleCachePath; llvm::Optional dependencyTracker; + public: llvm::Optional dependencies; - ModuleDependencyScanner(ASTContext &ctx, ModuleLoadingMode LoadMode, - Identifier moduleName, - InterfaceSubContextDelegate &astDelegate, - ScannerKind kind = MDS_plain, - llvm::Optional tracker = llvm::None) + ModuleDependencyScanner( + ASTContext &ctx, ModuleLoadingMode LoadMode, Identifier moduleName, + InterfaceSubContextDelegate &astDelegate, + ScannerKind kind = MDS_plain, + llvm::Optional tracker = llvm::None) : SerializedModuleLoaderBase(ctx, nullptr, LoadMode, /*IgnoreSwiftSourceInfoFile=*/true), kind(kind), moduleName(moduleName), astDelegate(astDelegate), @@ -118,11 +119,11 @@ namespace swift { llvm::BumpPtrAllocator Allocator; public: - PlaceholderSwiftModuleScanner(ASTContext &ctx, ModuleLoadingMode LoadMode, - Identifier moduleName, - StringRef PlaceholderDependencyModuleMap, - InterfaceSubContextDelegate &astDelegate, - llvm::Optional tracker = llvm::None) + PlaceholderSwiftModuleScanner( + ASTContext &ctx, ModuleLoadingMode LoadMode, Identifier moduleName, + StringRef PlaceholderDependencyModuleMap, + InterfaceSubContextDelegate &astDelegate, + llvm::Optional tracker = llvm::None) : ModuleDependencyScanner(ctx, LoadMode, moduleName, astDelegate, MDS_placeholder, tracker) { diff --git a/include/swift/Serialization/SerializedModuleLoader.h b/include/swift/Serialization/SerializedModuleLoader.h index b24e262e09d..044d7887c6b 100644 --- a/include/swift/Serialization/SerializedModuleLoader.h +++ b/include/swift/Serialization/SerializedModuleLoader.h @@ -232,10 +232,10 @@ public: virtual void verifyAllModules() override; - virtual llvm::Optional getModuleDependencies( - StringRef moduleName, ModuleDependenciesCache &cache, - InterfaceSubContextDelegate &delegate, - bool isTestableImport) override; + virtual llvm::Optional + getModuleDependencies(StringRef moduleName, ModuleDependenciesCache &cache, + InterfaceSubContextDelegate &delegate, + bool isTestableImport) override; }; /// Imports serialized Swift modules into an ASTContext. @@ -439,8 +439,8 @@ public: llvm::Optional getGroupNameForDecl(const Decl *D) const override; - - llvm::Optional getSourceFileNameForDecl(const Decl *D) const override; + llvm::Optional + getSourceFileNameForDecl(const Decl *D) const override; llvm::Optional getSourceOrderForDecl(const Decl *D) const override; diff --git a/include/swift/Serialization/SerializedSILLoader.h b/include/swift/Serialization/SerializedSILLoader.h index c2f3ce26cef..c1e0172ee8b 100644 --- a/include/swift/Serialization/SerializedSILLoader.h +++ b/include/swift/Serialization/SerializedSILLoader.h @@ -61,8 +61,10 @@ public: ~SerializedSILLoader(); SILFunction *lookupSILFunction(SILFunction *Callee, bool onlyUpdateLinkage); - SILFunction *lookupSILFunction(StringRef Name, llvm::Optional linkage); - bool hasSILFunction(StringRef Name, llvm::Optional linkage = llvm::None); + SILFunction *lookupSILFunction(StringRef Name, + llvm::Optional linkage); + bool hasSILFunction(StringRef Name, + llvm::Optional linkage = llvm::None); SILVTable *lookupVTable(const ClassDecl *C); SILMoveOnlyDeinit *lookupMoveOnlyDeinit(const NominalTypeDecl *nomDecl); SILWitnessTable *lookupWitnessTable(SILWitnessTable *C); diff --git a/include/swift/SymbolGraphGen/DocumentationCategory.h b/include/swift/SymbolGraphGen/DocumentationCategory.h index 061fe2539c1..8ee2a3712d5 100644 --- a/include/swift/SymbolGraphGen/DocumentationCategory.h +++ b/include/swift/SymbolGraphGen/DocumentationCategory.h @@ -32,8 +32,10 @@ static StringRef documentationMetadataForDecl(const Decl *D) { } LLVM_ATTRIBUTE_USED -static llvm::Optional documentationVisibilityForDecl(const Decl *D) { - if (!D) return llvm::None; +static llvm::Optional +documentationVisibilityForDecl(const Decl *D) { + if (!D) + return llvm::None; if (const auto *DC = D->getAttrs().getAttribute()) { return DC->Visibility; diff --git a/lib/APIDigester/ModuleAnalyzerNodes.cpp b/lib/APIDigester/ModuleAnalyzerNodes.cpp index 9c9f4d63833..a8dd2870502 100644 --- a/lib/APIDigester/ModuleAnalyzerNodes.cpp +++ b/lib/APIDigester/ModuleAnalyzerNodes.cpp @@ -550,7 +550,7 @@ StringRef SDKNodeTypeWitness::getWitnessedTypeName() const { getName()) + "." + getName()).str()); } -llvm::Optional SDKNodeDeclType::getSuperclass() const { +llvm::Optional SDKNodeDeclType::getSuperclass() const { if (SuperclassUsr.empty()) return llvm::None; auto Descendants = getRootNode()->getDescendantsByUsr(SuperclassUsr); @@ -562,7 +562,7 @@ llvm::Optional SDKNodeDeclType::getSuperclass() const { /// Finding the node through all children, including the inherited ones, /// whose printed name matches with the given name. -llvm::Optional +llvm::Optional SDKNodeDeclType::lookupChildByPrintedName(StringRef Name) const { for (auto C : getChildren()) { if (C->getPrintedName() == Name) @@ -618,7 +618,7 @@ static llvm::Optional parseKeyKind(StringRef Content) { return llvm::StringSwitch>(Content) #define KEY(NAME) .Case(#NAME, KeyKind::KK_##NAME) #include "swift/IDE/DigesterEnums.def" - .Default(llvm::None); + .Default(llvm::None); } static StringRef getKeyContent(SDKContext &Ctx, KeyKind Kind) { @@ -752,10 +752,10 @@ SDKNode* SDKNode::constructSDKNode(SDKContext &Ctx, } case KeyKind::KK_declKind: { auto dKind = llvm::StringSwitch>( - GetScalarString(Pair.getValue())) - #define DECL(X, PARENT) .Case(#X, DeclKind::X) + GetScalarString(Pair.getValue())) +#define DECL(X, PARENT) .Case(#X, DeclKind::X) #include "swift/AST/DeclNodes.def" - .Default(llvm::None); + .Default(llvm::None); if (dKind) Info.DKind = *dKind; else @@ -848,7 +848,8 @@ static bool hasSameParameterFlags(const SDKNodeType *Left, const SDKNodeType *Ri } // Return whether a decl has been moved in/out to an extension -static llvm::Optional isFromExtensionChanged(const SDKNode &L, const SDKNode &R) { +static llvm::Optional isFromExtensionChanged(const SDKNode &L, + const SDKNode &R) { assert(L.getKind() == R.getKind()); // Version 8 starts to include whether a decl is from an extension. if (L.getJsonFormatVersion() + R.getJsonFormatVersion() < 2 * 8) { @@ -1262,9 +1263,9 @@ StringRef printGenericSignature(SDKContext &Ctx, ProtocolConformance *Conf, bool return printGenericSignature(Ctx, Conf->getConditionalRequirements(), Canonical); } -static llvm::Optional getSimilarMemberCount(NominalTypeDecl *NTD, - ValueDecl *VD, - llvm::function_ref Check) { +static llvm::Optional +getSimilarMemberCount(NominalTypeDecl *NTD, ValueDecl *VD, + llvm::function_ref Check) { if (!Check(VD)) return llvm::None; auto Members = NTD->getMembers(); diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp index a24e2853df5..15551c01ced 100644 --- a/lib/AST/ASTContext.cpp +++ b/lib/AST/ASTContext.cpp @@ -2023,12 +2023,10 @@ static void diagnoseScannerFailure(StringRef moduleName, } } -llvm::Optional ASTContext::getModuleDependencies( +llvm::Optional ASTContext::getModuleDependencies( StringRef moduleName, ModuleDependenciesCache &cache, - InterfaceSubContextDelegate &delegate, - bool optionalDependencyLookup, - bool isTestableImport, - llvm::Optional dependencyOf) { + InterfaceSubContextDelegate &delegate, bool optionalDependencyLookup, + bool isTestableImport, llvm::Optional dependencyOf) { // Retrieve the dependencies for this module. // Check whether we've cached this result. if (auto found = @@ -2060,7 +2058,7 @@ llvm::Optional ASTContext::getModuleDependencies( return llvm::None; } -llvm::Optional +llvm::Optional ASTContext::getSwiftModuleDependencies(StringRef moduleName, ModuleDependenciesCache &cache, InterfaceSubContextDelegate &delegate) { @@ -2088,7 +2086,7 @@ ASTContext::getSwiftModuleDependencies(StringRef moduleName, return llvm::None; } -llvm::Optional +llvm::Optional ASTContext::getClangModuleDependencies(StringRef moduleName, ModuleDependenciesCache &cache, InterfaceSubContextDelegate &delegate) { @@ -3010,7 +3008,8 @@ AbstractFunctionDecl::getForeignErrorConvention() const { return llvm::None; auto &conventionsMap = getASTContext().getImpl().ForeignErrorConventions; auto it = conventionsMap.find(this); - if (it == conventionsMap.end()) return llvm::None; + if (it == conventionsMap.end()) + return llvm::None; return it->second; } @@ -3028,15 +3027,17 @@ AbstractFunctionDecl::getForeignAsyncConvention() const { return llvm::None; auto &conventionsMap = getASTContext().getImpl().ForeignAsyncConventions; auto it = conventionsMap.find(this); - if (it == conventionsMap.end()) return llvm::None; + if (it == conventionsMap.end()) + return llvm::None; return it->second; } -llvm::Optional swift::getKnownFoundationEntity(StringRef name){ +llvm::Optional +swift::getKnownFoundationEntity(StringRef name) { return llvm::StringSwitch>(name) #define FOUNDATION_ENTITY(Name) .Case(#Name, KnownFoundationEntity::Name) #include "swift/AST/KnownFoundationEntities.def" - .Default(llvm::None); + .Default(llvm::None); } StringRef swift::getSwiftName(KnownFoundationEntity kind) { @@ -3914,7 +3915,8 @@ AnyMetatypeType::AnyMetatypeType(TypeKind kind, const ASTContext *C, } } -MetatypeType *MetatypeType::get(Type T, llvm::Optional Repr, +MetatypeType *MetatypeType::get(Type T, + llvm::Optional Repr, const ASTContext &Ctx) { auto properties = T->getRecursiveProperties(); auto arena = getArena(properties); @@ -3938,11 +3940,11 @@ MetatypeType *MetatypeType::get(Type T, llvm::Optional R MetatypeType::MetatypeType(Type T, const ASTContext *C, RecursiveTypeProperties properties, llvm::Optional repr) - : AnyMetatypeType(TypeKind::Metatype, C, properties, T, repr) { -} + : AnyMetatypeType(TypeKind::Metatype, C, properties, T, repr) {} ExistentialMetatypeType * -ExistentialMetatypeType::get(Type T, llvm::Optional repr, +ExistentialMetatypeType::get(Type T, + llvm::Optional repr, const ASTContext &ctx) { // If we're creating an existential metatype from an // existential type, wrap the constraint type direcly. @@ -3968,11 +3970,10 @@ ExistentialMetatypeType::get(Type T, llvm::Optional repr T, T->isCanonical() ? &ctx : nullptr, properties, repr); } -ExistentialMetatypeType::ExistentialMetatypeType(Type T, - const ASTContext *C, - RecursiveTypeProperties properties, - llvm::Optional repr) - : AnyMetatypeType(TypeKind::ExistentialMetatype, C, properties, T, repr) { +ExistentialMetatypeType::ExistentialMetatypeType( + Type T, const ASTContext *C, RecursiveTypeProperties properties, + llvm::Optional repr) + : AnyMetatypeType(TypeKind::ExistentialMetatype, C, properties, T, repr) { if (repr) { assert(*repr != MetatypeRepresentation::Thin && "creating a thin existential metatype?"); @@ -4343,14 +4344,12 @@ GenericFunctionType *GenericFunctionType::get(GenericSignature sig, } GenericFunctionType::GenericFunctionType( - GenericSignature sig, - ArrayRef params, - Type result, - llvm::Optional info, - const ASTContext *ctx, - RecursiveTypeProperties properties) - : AnyFunctionType(TypeKind::GenericFunction, ctx, result, - properties, params.size(), info), Signature(sig) { + GenericSignature sig, ArrayRef params, Type result, + llvm::Optional info, const ASTContext *ctx, + RecursiveTypeProperties properties) + : AnyFunctionType(TypeKind::GenericFunction, ctx, result, properties, + params.size(), info), + Signature(sig) { std::uninitialized_copy(params.begin(), params.end(), getTrailingObjects()); if (info) { @@ -4388,17 +4387,11 @@ ArrayRef GenericFunctionType::getRequirements() const { } void SILFunctionType::Profile( - llvm::FoldingSetNodeID &id, - GenericSignature genericParams, - ExtInfo info, - SILCoroutineKind coroutineKind, - ParameterConvention calleeConvention, - ArrayRef params, - ArrayRef yields, - ArrayRef results, - llvm::Optional errorResult, - ProtocolConformanceRef conformance, - SubstitutionMap patternSubs, + llvm::FoldingSetNodeID &id, GenericSignature genericParams, ExtInfo info, + SILCoroutineKind coroutineKind, ParameterConvention calleeConvention, + ArrayRef params, ArrayRef yields, + ArrayRef results, llvm::Optional errorResult, + ProtocolConformanceRef conformance, SubstitutionMap patternSubs, SubstitutionMap invocationSubs) { id.AddPointer(genericParams.getPointer()); auto infoKey = info.getFuncAttrKey(); @@ -4427,17 +4420,11 @@ void SILFunctionType::Profile( } SILFunctionType::SILFunctionType( - GenericSignature genericSig, - ExtInfo ext, - SILCoroutineKind coroutineKind, - ParameterConvention calleeConvention, - ArrayRef params, - ArrayRef yields, - ArrayRef normalResults, - llvm::Optional errorResult, - SubstitutionMap patternSubs, - SubstitutionMap invocationSubs, - const ASTContext &ctx, + GenericSignature genericSig, ExtInfo ext, SILCoroutineKind coroutineKind, + ParameterConvention calleeConvention, ArrayRef params, + ArrayRef yields, ArrayRef normalResults, + llvm::Optional errorResult, SubstitutionMap patternSubs, + SubstitutionMap invocationSubs, const ASTContext &ctx, RecursiveTypeProperties properties, ProtocolConformanceRef witnessMethodConformance) : TypeBase(TypeKind::SILFunction, &ctx, properties), @@ -4643,16 +4630,11 @@ CanSILBlockStorageType SILBlockStorageType::get(CanType captureType) { } CanSILFunctionType SILFunctionType::get( - GenericSignature genericSig, - ExtInfo ext, SILCoroutineKind coroutineKind, - ParameterConvention callee, - ArrayRef params, - ArrayRef yields, - ArrayRef normalResults, - llvm::Optional errorResult, - SubstitutionMap patternSubs, - SubstitutionMap invocationSubs, - const ASTContext &ctx, + GenericSignature genericSig, ExtInfo ext, SILCoroutineKind coroutineKind, + ParameterConvention callee, ArrayRef params, + ArrayRef yields, ArrayRef normalResults, + llvm::Optional errorResult, SubstitutionMap patternSubs, + SubstitutionMap invocationSubs, const ASTContext &ctx, ProtocolConformanceRef witnessMethodConformance) { assert(coroutineKind == SILCoroutineKind::None || normalResults.empty()); assert(coroutineKind != SILCoroutineKind::None || yields.empty()); @@ -5716,10 +5698,8 @@ ASTContext::getClangFunctionType(ArrayRef params, return getClangTypeConverter().getFunctionType(params, resultTy, trueRep); } -const clang::Type * -ASTContext::getCanonicalClangFunctionType( - ArrayRef params, - llvm::Optional result, +const clang::Type *ASTContext::getCanonicalClangFunctionType( + ArrayRef params, llvm::Optional result, SILFunctionType::Representation trueRep) { auto *ty = getClangTypeConverter().getFunctionType(params, result, trueRep); return ty ? ty->getCanonicalTypeInternal().getTypePtr() : nullptr; diff --git a/lib/AST/ASTDemangler.cpp b/lib/AST/ASTDemangler.cpp index 41b98145774..ac3a70f789f 100644 --- a/lib/AST/ASTDemangler.cpp +++ b/lib/AST/ASTDemangler.cpp @@ -642,8 +642,8 @@ getMetatypeRepresentation(ImplMetatypeRepresentation repr) { llvm_unreachable("covered switch"); } -Type ASTBuilder::createExistentialMetatypeType(Type instance, - llvm::Optional repr) { +Type ASTBuilder::createExistentialMetatypeType( + Type instance, llvm::Optional repr) { if (auto existential = instance->getAs()) instance = existential->getConstraintType(); if (!instance->isAnyExistentialType()) @@ -695,8 +695,8 @@ Type ASTBuilder::createSymbolicExtendedExistentialType(NodePointer shapeNode, return Type(); } -Type ASTBuilder::createMetatypeType(Type instance, - llvm::Optional repr) { +Type ASTBuilder::createMetatypeType( + Type instance, llvm::Optional repr) { if (!repr) return MetatypeType::get(instance); diff --git a/lib/AST/ASTMangler.cpp b/lib/AST/ASTMangler.cpp index e8a38d1d356..63c9c1c632b 100644 --- a/lib/AST/ASTMangler.cpp +++ b/lib/AST/ASTMangler.cpp @@ -443,11 +443,8 @@ std::string ASTMangler::mangleReabstractionThunkHelper( } std::string ASTMangler::mangleObjCAsyncCompletionHandlerImpl( - CanSILFunctionType BlockType, - CanType ResultType, - CanGenericSignature Sig, - llvm::Optional ErrorOnZero, - bool predefined) { + CanSILFunctionType BlockType, CanType ResultType, CanGenericSignature Sig, + llvm::Optional ErrorOnZero, bool predefined) { beginMangling(); appendType(BlockType, Sig); appendType(ResultType, Sig); @@ -987,16 +984,18 @@ static StringRef getPrivateDiscriminatorIfNecessary(const Decl *decl) { /// specified name. /// /// \param useObjCProtocolNames When false, always returns \c None. -static llvm::Optional getOverriddenSwiftProtocolObjCName( - const ValueDecl *decl, - bool useObjCProtocolNames) { +static llvm::Optional +getOverriddenSwiftProtocolObjCName(const ValueDecl *decl, + bool useObjCProtocolNames) { if (!useObjCProtocolNames) return llvm::None; auto proto = dyn_cast(decl); - if (!proto) return llvm::None; + if (!proto) + return llvm::None; - if (!proto->isObjC()) return llvm::None; + if (!proto->isObjC()) + return llvm::None; // If there is an 'objc' attribute with a name, use that name. if (auto objc = proto->getAttrs().getAttribute()) { @@ -2296,7 +2295,8 @@ namespace { /// assumes that field and global-variable bindings always bind at /// least one name, which is probably a reasonable assumption but may /// not be adequately enforced. -static llvm::Optional findFirstVariable(PatternBindingDecl *binding) { +static llvm::Optional +findFirstVariable(PatternBindingDecl *binding) { for (auto idx : range(binding->getNumPatternEntries())) { auto var = FindFirstVariable().visit(binding->getPattern(idx)); if (var) return var; diff --git a/lib/AST/ASTScopeCreation.cpp b/lib/AST/ASTScopeCreation.cpp index 4e8f052d0e3..1a260aff654 100644 --- a/lib/AST/ASTScopeCreation.cpp +++ b/lib/AST/ASTScopeCreation.cpp @@ -190,10 +190,9 @@ public: /// \param endLoc Must be valid iff the pattern binding is in a local /// scope, in which case this is the last source location where the /// pattern bindings are going to be visible. - ASTScopeImpl * - addPatternBindingToScopeTree(PatternBindingDecl *patternBinding, - ASTScopeImpl *parent, - llvm::Optional endLoc); + ASTScopeImpl *addPatternBindingToScopeTree(PatternBindingDecl *patternBinding, + ASTScopeImpl *parent, + llvm::Optional endLoc); SWIFT_DEBUG_DUMP { print(llvm::errs()); } @@ -535,10 +534,8 @@ public: // These definitions are way down here so it can call into // NodeAdder -ASTScopeImpl * -ScopeCreator::addToScopeTreeAndReturnInsertionPoint(ASTNode n, - ASTScopeImpl *parent, - llvm::Optional endLoc) { +ASTScopeImpl *ScopeCreator::addToScopeTreeAndReturnInsertionPoint( + ASTNode n, ASTScopeImpl *parent, llvm::Optional endLoc) { if (!n) return parent; diff --git a/lib/AST/AbstractSourceFileDepGraphFactory.cpp b/lib/AST/AbstractSourceFileDepGraphFactory.cpp index 4af184410b9..59c58c6aa66 100644 --- a/lib/AST/AbstractSourceFileDepGraphFactory.cpp +++ b/lib/AST/AbstractSourceFileDepGraphFactory.cpp @@ -65,7 +65,8 @@ void AbstractSourceFileDepGraphFactory::addSourceFileNodesToGraph() { } void AbstractSourceFileDepGraphFactory::addADefinedDecl( - const DependencyKey &interfaceKey, llvm::Optional fingerprint) { + const DependencyKey &interfaceKey, + llvm::Optional fingerprint) { auto nodePair = g.findExistingNodePairOrCreateAndAddIfNew(interfaceKey, fingerprint); @@ -77,8 +78,8 @@ void AbstractSourceFileDepGraphFactory::addADefinedDecl( void AbstractSourceFileDepGraphFactory::addAUsedDecl( const DependencyKey &defKey, const DependencyKey &useKey) { - auto *defNode = - g.findExistingNodeOrCreateIfNew(defKey, llvm::None, false /* = !isProvides */); + auto *defNode = g.findExistingNodeOrCreateIfNew(defKey, llvm::None, + false /* = !isProvides */); // If the depended-upon node is defined in this file, then don't // create an arc to the user, when the user is the whole file. diff --git a/lib/AST/AccessNotes.cpp b/lib/AST/AccessNotes.cpp index 7496e7a1c17..930074d363b 100644 --- a/lib/AST/AccessNotes.cpp +++ b/lib/AST/AccessNotes.cpp @@ -28,7 +28,7 @@ namespace swift { AccessNoteDeclName::AccessNoteDeclName() - : parentNames(), name(), accessorKind(llvm::None) { } + : parentNames(), name(), accessorKind(llvm::None) {} AccessNoteDeclName::AccessNoteDeclName(ASTContext &ctx, StringRef str) { auto parsedName = parseDeclName(str); diff --git a/lib/AST/AccessRequests.cpp b/lib/AST/AccessRequests.cpp index fb6c185cb0a..2ed13f3370e 100644 --- a/lib/AST/AccessRequests.cpp +++ b/lib/AST/AccessRequests.cpp @@ -323,7 +323,7 @@ DefaultAndMaxAccessLevelRequest::evaluate(Evaluator &evaluator, // So we decode Max as the last (high) bit that is set, and Default as the first // (low). And add one to each, to map them back into AccessLevels. -llvm::Optional> +llvm::Optional> DefaultAndMaxAccessLevelRequest::getCachedResult() const { auto extensionDecl = std::get<0>(getStorage()); if (extensionDecl->hasDefaultAccessLevel()) { diff --git a/lib/AST/ArgumentList.cpp b/lib/AST/ArgumentList.cpp index 675e71c9cb5..d655fbfab8b 100644 --- a/lib/AST/ArgumentList.cpp +++ b/lib/AST/ArgumentList.cpp @@ -56,11 +56,10 @@ bool Argument::isConst() const { return ArgExpr->isSemanticallyConstExpr(); } -ArgumentList *ArgumentList::create(ASTContext &ctx, SourceLoc lParenLoc, - ArrayRef args, SourceLoc rParenLoc, - llvm::Optional firstTrailingClosureIndex, - bool isImplicit, ArgumentList *originalArgs, - AllocationArena arena) { +ArgumentList *ArgumentList::create( + ASTContext &ctx, SourceLoc lParenLoc, ArrayRef args, + SourceLoc rParenLoc, llvm::Optional firstTrailingClosureIndex, + bool isImplicit, ArgumentList *originalArgs, AllocationArena arena) { SmallVector exprs; SmallVector labels; SmallVector labelLocs; @@ -222,8 +221,8 @@ ArgumentList::getArgumentLabels(SmallVectorImpl &scratch) const { return scratch; } -llvm::Optional ArgumentList::findArgumentExpr(Expr *expr, - bool allowSemantic) const { +llvm::Optional +ArgumentList::findArgumentExpr(Expr *expr, bool allowSemantic) const { if (allowSemantic) expr = expr->getSemanticsProvidingExpr(); for (auto idx : indices(*this)) { diff --git a/lib/AST/Attr.cpp b/lib/AST/Attr.cpp index 83ff9b73c07..bdcb513c699 100644 --- a/lib/AST/Attr.cpp +++ b/lib/AST/Attr.cpp @@ -1634,9 +1634,8 @@ StringRef DeclAttribute::getAttrName() const { ObjCAttr::ObjCAttr(SourceLoc atLoc, SourceRange baseRange, llvm::Optional name, SourceRange parenRange, ArrayRef nameLocs) - : DeclAttribute(DAK_ObjC, atLoc, baseRange, /*Implicit=*/false), - NameData(nullptr) -{ + : DeclAttribute(DAK_ObjC, atLoc, baseRange, /*Implicit=*/false), + NameData(nullptr) { if (name) { // Store the name. assert(name->getNumSelectorPieces() == nameLocs.size()); @@ -1663,8 +1662,8 @@ ObjCAttr *ObjCAttr::create(ASTContext &Ctx, llvm::Optional name, ObjCAttr *ObjCAttr::createUnnamed(ASTContext &Ctx, SourceLoc AtLoc, SourceLoc ObjCLoc) { - return new (Ctx) ObjCAttr(AtLoc, SourceRange(ObjCLoc), llvm::None, - SourceRange(), { }); + return new (Ctx) + ObjCAttr(AtLoc, SourceRange(ObjCLoc), llvm::None, SourceRange(), {}); } ObjCAttr *ObjCAttr::createUnnamedImplicit(ASTContext &Ctx) { diff --git a/lib/AST/AutoDiff.cpp b/lib/AST/AutoDiff.cpp index 12fe0ad0b62..a88eb066808 100644 --- a/lib/AST/AutoDiff.cpp +++ b/lib/AST/AutoDiff.cpp @@ -22,9 +22,10 @@ using namespace swift; AutoDiffDerivativeFunctionKind::AutoDiffDerivativeFunctionKind( StringRef string) { - llvm::Optional result = llvm::StringSwitch>(string) - .Case("jvp", JVP) - .Case("vjp", VJP); + llvm::Optional result = + llvm::StringSwitch>(string) + .Case("jvp", JVP) + .Case("vjp", VJP); assert(result && "Invalid string"); rawValue = *result; } @@ -44,10 +45,11 @@ NormalDifferentiableFunctionTypeComponent:: NormalDifferentiableFunctionTypeComponent:: NormalDifferentiableFunctionTypeComponent(StringRef string) { - llvm::Optional result = llvm::StringSwitch>(string) - .Case("original", Original) - .Case("jvp", JVP) - .Case("vjp", VJP); + llvm::Optional result = + llvm::StringSwitch>(string) + .Case("original", Original) + .Case("jvp", JVP) + .Case("vjp", VJP); assert(result && "Invalid string"); rawValue = *result; } @@ -67,19 +69,21 @@ NormalDifferentiableFunctionTypeComponent::getAsDerivativeFunctionKind() const { LinearDifferentiableFunctionTypeComponent:: LinearDifferentiableFunctionTypeComponent(StringRef string) { - llvm::Optional result = llvm::StringSwitch>(string) - .Case("original", Original) - .Case("transpose", Transpose); + llvm::Optional result = + llvm::StringSwitch>(string) + .Case("original", Original) + .Case("transpose", Transpose); assert(result && "Invalid string"); rawValue = *result; } DifferentiabilityWitnessFunctionKind::DifferentiabilityWitnessFunctionKind( StringRef string) { - llvm::Optional result = llvm::StringSwitch>(string) - .Case("jvp", JVP) - .Case("vjp", VJP) - .Case("transpose", Transpose); + llvm::Optional result = + llvm::StringSwitch>(string) + .Case("jvp", JVP) + .Case("vjp", VJP) + .Case("transpose", Transpose); assert(result && "Invalid string"); rawValue = *result; } diff --git a/lib/AST/Availability.cpp b/lib/AST/Availability.cpp index f5b15a9aff5..556faf6db8c 100644 --- a/lib/AST/Availability.cpp +++ b/lib/AST/Availability.cpp @@ -44,7 +44,7 @@ namespace { struct InferredAvailability { PlatformAgnosticAvailabilityKind PlatformAgnostic = PlatformAgnosticAvailabilityKind::None; - + llvm::Optional Introduced; llvm::Optional Deprecated; llvm::Optional Obsoleted; @@ -255,9 +255,11 @@ SemanticAvailableRangeAttrRequest::evaluate(Evaluator &evaluator, return llvm::None; } -llvm::Optional Decl::getSemanticAvailableRangeAttr() const { +llvm::Optional +Decl::getSemanticAvailableRangeAttr() const { auto &eval = getASTContext().evaluator; - return evaluateOrDefault(eval, SemanticAvailableRangeAttrRequest{this}, llvm::None); + return evaluateOrDefault(eval, SemanticAvailableRangeAttrRequest{this}, + llvm::None); } llvm::Optional @@ -290,7 +292,8 @@ SemanticUnavailableAttrRequest::evaluate(Evaluator &evaluator, llvm::Optional Decl::getSemanticUnavailableAttr() const { auto &eval = getASTContext().evaluator; - return evaluateOrDefault(eval, SemanticUnavailableAttrRequest{this}, llvm::None); + return evaluateOrDefault(eval, SemanticUnavailableAttrRequest{this}, + llvm::None); } bool UnavailabilityReason::requiresDeploymentTargetOrEarlier( diff --git a/lib/AST/Builtins.cpp b/lib/AST/Builtins.cpp index 977e125e36f..035cbf9beee 100644 --- a/lib/AST/Builtins.cpp +++ b/lib/AST/Builtins.cpp @@ -809,7 +809,8 @@ makeBoundGenericType(NominalTypeDecl *decl, template static BuiltinFunctionBuilder::MetatypeGenerator -makeMetatype(const T &object, llvm::Optional repr = llvm::None) { +makeMetatype(const T &object, + llvm::Optional repr = llvm::None) { return { object, repr }; } diff --git a/lib/AST/ClangTypeConverter.cpp b/lib/AST/ClangTypeConverter.cpp index cced57ed93c..f593e17a04b 100644 --- a/lib/AST/ClangTypeConverter.cpp +++ b/lib/AST/ClangTypeConverter.cpp @@ -152,9 +152,10 @@ const clang::Type *ClangTypeConverter::getFunctionType( llvm_unreachable("invalid representation"); } -const clang::Type *ClangTypeConverter::getFunctionType( - ArrayRef params, llvm::Optional result, - SILFunctionType::Representation repr) { +const clang::Type * +ClangTypeConverter::getFunctionType(ArrayRef params, + llvm::Optional result, + SILFunctionType::Representation repr) { // Using the interface type is sufficient as type parameters get mapped to // `id`, since ObjC lightweight generics use type erasure. (See also: SE-0057) @@ -664,8 +665,9 @@ clang::QualType ClangTypeConverter::visitSILFunctionType(SILFunctionType *type) ? SILFunctionTypeRepresentation::Block : repr); auto results = type->getResults(); - auto optionalResult = - results.empty() ? llvm::None : llvm::Optional(results[0]); + auto optionalResult = results.empty() + ? llvm::None + : llvm::Optional(results[0]); clangTy = getFunctionType(type->getParameters(), optionalResult, newRepr); } return clang::QualType(clangTy, 0); diff --git a/lib/AST/ClangTypeConverter.h b/lib/AST/ClangTypeConverter.h index 867c190ade7..e50824fe162 100644 --- a/lib/AST/ClangTypeConverter.h +++ b/lib/AST/ClangTypeConverter.h @@ -75,9 +75,9 @@ public: AnyFunctionType::Representation repr); /// Compute the C function type for a SIL function type. - const clang::Type *getFunctionType( - ArrayRef params, llvm::Optional result, - SILFunctionType::Representation repr); + const clang::Type *getFunctionType(ArrayRef params, + llvm::Optional result, + SILFunctionType::Representation repr); /// Check whether the given Clang declaration is an export of a Swift /// declaration introduced by this converter, and if so, return the original diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index 5589806d058..af67bd4a6f2 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -905,9 +905,8 @@ static_assert(sizeof(checkSourceLocType(&ID##Decl::getLoc)) == 2, \ llvm::Optional Decl::getGlobalActorAttr() const { auto &ctx = getASTContext(); auto mutableThis = const_cast(this); - return evaluateOrDefault(ctx.evaluator, - GlobalActorAttributeRequest{mutableThis}, - llvm::None); + return evaluateOrDefault( + ctx.evaluator, GlobalActorAttributeRequest{mutableThis}, llvm::None); } bool Decl::preconcurrency() const { @@ -2955,8 +2954,9 @@ unsigned ValueDecl::getLocalDiscriminator() const { if (LocalDiscriminator == InvalidDiscriminator && (ctx.Diags.hadAnyError() || (getLoc().isValid() && - getModuleContext()->getSourceFileContainingLocation(getLoc()) - ->getFulfilledMacroRole() != llvm::None))) { + getModuleContext() + ->getSourceFileContainingLocation(getLoc()) + ->getFulfilledMacroRole() != llvm::None))) { auto discriminator = ctx.getNextDiscriminator(getDeclContext()); ctx.setMaxAssignedDiscriminator(getDeclContext(), discriminator + 1); const_cast(this)->LocalDiscriminator = discriminator; @@ -3632,8 +3632,8 @@ void ValueDecl::setInterfaceType(Type type) { std::move(type)); } -llvm::Optional ValueDecl::getObjCRuntimeName( - bool skipIsObjCResolution) const { +llvm::Optional +ValueDecl::getObjCRuntimeName(bool skipIsObjCResolution) const { if (auto func = dyn_cast(this)) return func->getObjCSelector(DeclName(), skipIsObjCResolution); @@ -4352,12 +4352,9 @@ static bool canResultTypeHaveCovariantGenericParameterResult(Type resultTy) { /// \param position The current position in terms of variance. /// \param skipParamIndex The index of the parameter that shall be skipped. static GenericParameterReferenceInfo findGenericParameterReferencesInFunction( - CanGenericSignature genericSig, - GenericTypeParamType *genericParam, - const AnyFunctionType *fnType, - TypePosition position, - bool treatNonResultCovarianceAsInvariant, - bool canBeCovariantResult, + CanGenericSignature genericSig, GenericTypeParamType *genericParam, + const AnyFunctionType *fnType, TypePosition position, + bool treatNonResultCovarianceAsInvariant, bool canBeCovariantResult, llvm::Optional skipParamIndex) { // If there are no type parameters, we're done. if (!isa(fnType) && !fnType->hasTypeParameter()) @@ -4595,11 +4592,12 @@ findGenericParameterReferences(CanGenericSignature genericSig, return GenericParameterReferenceInfo::forAssocTypeRef(position); } -GenericParameterReferenceInfo swift::findGenericParameterReferences( - const ValueDecl *value, CanGenericSignature sig, - GenericTypeParamType *genericParam, - bool treatNonResultCovarianceAsInvariant, - llvm::Optional skipParamIndex) { +GenericParameterReferenceInfo +swift::findGenericParameterReferences(const ValueDecl *value, + CanGenericSignature sig, + GenericTypeParamType *genericParam, + bool treatNonResultCovarianceAsInvariant, + llvm::Optional skipParamIndex) { assert(isa(value) == false); assert(sig->getGenericParamOrdinal(genericParam) < sig.getGenericParams().size()); @@ -4647,8 +4645,9 @@ GenericParameterReferenceInfo ValueDecl::findExistentialSelfReferences( GenericSignature()); auto genericParam = sig.getGenericParams().front(); - return findGenericParameterReferences( - this, sig, genericParam, treatNonResultCovariantSelfAsInvariant, llvm::None); + return findGenericParameterReferences(this, sig, genericParam, + treatNonResultCovariantSelfAsInvariant, + llvm::None); } Type TypeDecl::getDeclaredInterfaceType() const { @@ -6257,23 +6256,24 @@ StringRef ProtocolDecl::getObjCRuntimeName( ArrayRef ProtocolDecl::getStructuralRequirements() const { - return evaluateOrDefault(getASTContext().evaluator, - StructuralRequirementsRequest { const_cast(this) }, - {}); + return evaluateOrDefault( + getASTContext().evaluator, + StructuralRequirementsRequest{const_cast(this)}, {}); } ArrayRef ProtocolDecl::getTypeAliasRequirements() const { - return evaluateOrDefault(getASTContext().evaluator, - TypeAliasRequirementsRequest { const_cast(this) }, - {}); + return evaluateOrDefault( + getASTContext().evaluator, + TypeAliasRequirementsRequest{const_cast(this)}, {}); } ArrayRef ProtocolDecl::getProtocolDependencies() const { - return evaluateOrDefault(getASTContext().evaluator, - ProtocolDependenciesRequest { const_cast(this) }, - llvm::None); + return evaluateOrDefault( + getASTContext().evaluator, + ProtocolDependenciesRequest{const_cast(this)}, + llvm::None); } RequirementSignature ProtocolDecl::getRequirementSignature() const { @@ -6353,10 +6353,10 @@ void ProtocolDecl::computeKnownProtocolKind() const { } llvm::Optional - ProtocolDecl::getKnownDerivableProtocolKind() const { +ProtocolDecl::getKnownDerivableProtocolKind() const { const auto knownKind = getKnownProtocolKind(); if (!knownKind) - return llvm::None; + return llvm::None; switch (*knownKind) { case KnownProtocolKind::RawRepresentable: @@ -6391,7 +6391,8 @@ llvm::Optional return KnownDerivableProtocolKind::DistributedActor; case KnownProtocolKind::DistributedActorSystem: return KnownDerivableProtocolKind::DistributedActorSystem; - default: return llvm::None; + default: + return llvm::None; } } @@ -7480,9 +7481,7 @@ VarDecl::getPropertyWrapperMutability() const { auto &ctx = getASTContext(); auto mutableThis = const_cast(this); return evaluateOrDefault( - ctx.evaluator, - PropertyWrapperMutabilityRequest{mutableThis}, - llvm::None); + ctx.evaluator, PropertyWrapperMutabilityRequest{mutableThis}, llvm::None); } llvm::Optional @@ -7684,17 +7683,15 @@ clang::PointerAuthQualifier VarDecl::getPointerAuthQualifier() const { return clang::PointerAuthQualifier(); } -ParamDecl::ParamDecl(SourceLoc specifierLoc, - SourceLoc argumentNameLoc, Identifier argumentName, - SourceLoc parameterNameLoc, Identifier parameterName, - DeclContext *dc) +ParamDecl::ParamDecl(SourceLoc specifierLoc, SourceLoc argumentNameLoc, + Identifier argumentName, SourceLoc parameterNameLoc, + Identifier parameterName, DeclContext *dc) : VarDecl(DeclKind::Param, - /*IsStatic*/ false, - VarDecl::Introducer::Let, parameterNameLoc, parameterName, dc, - StorageIsNotMutable), + /*IsStatic*/ false, VarDecl::Introducer::Let, parameterNameLoc, + parameterName, dc, StorageIsNotMutable), ArgumentNameAndFlags(argumentName, llvm::None), - ParameterNameLoc(parameterNameLoc), - ArgumentNameLoc(argumentNameLoc), SpecifierLoc(specifierLoc) { + ParameterNameLoc(parameterNameLoc), ArgumentNameLoc(argumentNameLoc), + SpecifierLoc(specifierLoc) { Bits.ParamDecl.OwnershipSpecifier = 0; Bits.ParamDecl.defaultArgumentKind = static_cast(DefaultArgumentKind::None); @@ -7909,7 +7906,8 @@ AnyFunctionType::Param ParamDecl::toFunctionParam(Type type) const { return AnyFunctionType::Param(type, label, flags, internalLabel); } -llvm::Optional ParamDecl::getCachedDefaultArgumentInitContext() const { +llvm::Optional +ParamDecl::getCachedDefaultArgumentInitContext() const { if (auto *defaultInfo = DefaultValueAndFlags.getPointer()) if (auto *init = defaultInfo->InitContextAndIsTypeChecked.getPointer()) return init; @@ -8561,7 +8559,8 @@ static bool isPotentialCompletionHandler(const ParamDecl *param) { !paramType->isNoEscape() && !param->isAutoClosure(); } -llvm::Optional AbstractFunctionDecl::findPotentialCompletionHandlerParam( +llvm::Optional +AbstractFunctionDecl::findPotentialCompletionHandlerParam( const AbstractFunctionDecl *asyncAlternative) const { const ParameterList *params = getParameters(); if (params->size() == 0) @@ -8902,10 +8901,10 @@ AbstractFunctionDecl::getObjCSelector(DeclName preferredName, } // The number of selector pieces we'll have. - llvm::Optional asyncConvention - = getForeignAsyncConvention(); - llvm::Optional errorConvention - = getForeignErrorConvention(); + llvm::Optional asyncConvention = + getForeignAsyncConvention(); + llvm::Optional errorConvention = + getForeignErrorConvention(); unsigned numSelectorPieces = argNames.size() + (asyncConvention.has_value() ? 1 : 0) + (errorConvention.has_value() ? 1 : 0); @@ -9111,8 +9110,8 @@ GenericTypeParamDecl *OpaqueTypeDecl::getExplicitGenericParam( return genericParamType->getDecl(); } -llvm::Optional OpaqueTypeDecl::getAnonymousOpaqueParamOrdinal( - TypeRepr *repr) const { +llvm::Optional +OpaqueTypeDecl::getAnonymousOpaqueParamOrdinal(TypeRepr *repr) const { assert(NamingDeclAndHasOpaqueReturnTypeRepr.getInt() && "can't do opaque param lookup without underlying interface repr"); auto opaqueReprs = getOpaqueReturnTypeReprs(); @@ -10277,7 +10276,6 @@ SourceLoc swift::extractNearestSourceLoc(TypeOrExtensionDecl container) { return extractNearestSourceLoc(container.Decl); } - llvm::Optional ParseAbstractFunctionBodyRequest::getCachedResult() const { using BodyKind = AbstractFunctionDecl::BodyKind; diff --git a/lib/AST/DocComment.cpp b/lib/AST/DocComment.cpp index 7da157314c2..d5b780e62f2 100644 --- a/lib/AST/DocComment.cpp +++ b/lib/AST/DocComment.cpp @@ -35,9 +35,9 @@ void *DocComment::operator new(size_t Bytes, swift::markup::MarkupContext &MC, } namespace { -llvm::Optional extractParamOutlineItem( - swift::markup::MarkupContext &MC, - swift::markup::MarkupASTNode *Node) { +llvm::Optional +extractParamOutlineItem(swift::markup::MarkupContext &MC, + swift::markup::MarkupASTNode *Node) { auto Item = dyn_cast(Node); if (!Item) @@ -397,7 +397,7 @@ namespace { template class CommentProviderFinder final { using ResultWithDecl = std::pair; - using VisitFnTy = llvm::Optional(*)(const Decl *); + using VisitFnTy = llvm::Optional (*)(const Decl *); VisitFnTy VisitFn; diff --git a/lib/AST/ExistentialGeneralization.cpp b/lib/AST/ExistentialGeneralization.cpp index 47d0d2cebcd..e7d5a557f26 100644 --- a/lib/AST/ExistentialGeneralization.cpp +++ b/lib/AST/ExistentialGeneralization.cpp @@ -231,13 +231,14 @@ private: /// Generalize the given type by preserving its top-level structure /// but generalizing its component types. Type generalizeComponentTypes(CanType type) { - return type.transformRec([&](TypeBase *componentType) -> llvm::Optional { - // Ignore the top level. - if (componentType == type.getPointer()) - return llvm::None; + return type.transformRec( + [&](TypeBase *componentType) -> llvm::Optional { + // Ignore the top level. + if (componentType == type.getPointer()) + return llvm::None; - return generalizeComponentType(CanType(componentType)); - }); + return generalizeComponentType(CanType(componentType)); + }); } Type generalizeComponentType(CanType origArg) { diff --git a/lib/AST/ExtInfo.cpp b/lib/AST/ExtInfo.cpp index 014b2563c24..f1a78a554d6 100644 --- a/lib/AST/ExtInfo.cpp +++ b/lib/AST/ExtInfo.cpp @@ -60,9 +60,11 @@ void ClangTypeInfo::dump(llvm::raw_ostream &os, // MARK: - UnexpectedClangTypeError -llvm::Optional UnexpectedClangTypeError::checkClangType( - SILFunctionTypeRepresentation silRep, - const clang::Type *type, bool expectNonnullForCOrBlock, bool expectCanonical) { +llvm::Optional +UnexpectedClangTypeError::checkClangType(SILFunctionTypeRepresentation silRep, + const clang::Type *type, + bool expectNonnullForCOrBlock, + bool expectCanonical) { #ifdef NDEBUG return llvm::None; #else diff --git a/lib/AST/FineGrainedDependencies.cpp b/lib/AST/FineGrainedDependencies.cpp index 3b6bd31f51e..2eed0e9d1d2 100644 --- a/lib/AST/FineGrainedDependencies.cpp +++ b/lib/AST/FineGrainedDependencies.cpp @@ -114,7 +114,8 @@ void SourceFileDepGraph::forEachArc( InterfaceAndImplementationPair SourceFileDepGraph::findExistingNodePairOrCreateAndAddIfNew( - const DependencyKey &interfaceKey, llvm::Optional fingerprint) { + const DependencyKey &interfaceKey, + llvm::Optional fingerprint) { // Optimization for whole-file users: if (interfaceKey.getKind() == NodeKind::sourceFileProvide && diff --git a/lib/AST/FrontendSourceFileDepGraphFactory.cpp b/lib/AST/FrontendSourceFileDepGraphFactory.cpp index c95d405237d..5430161917e 100644 --- a/lib/AST/FrontendSourceFileDepGraphFactory.cpp +++ b/lib/AST/FrontendSourceFileDepGraphFactory.cpp @@ -531,8 +531,9 @@ class ExternalDependencyEnumerator { const DependencyKey sourceFileImplementation; public: - using UseEnumerator = llvm::function_ref)>; + using UseEnumerator = + llvm::function_ref)>; ExternalDependencyEnumerator(const DependencyTracker &depTracker, StringRef swiftDeps) diff --git a/lib/AST/GenericEnvironment.cpp b/lib/AST/GenericEnvironment.cpp index 6270b13ba51..142fdcc4054 100644 --- a/lib/AST/GenericEnvironment.cpp +++ b/lib/AST/GenericEnvironment.cpp @@ -320,8 +320,8 @@ void GenericEnvironment::addMapping(GenericParamKey key, getContextTypes()[index] = contextType; } -llvm::Optional GenericEnvironment::getMappingIfPresent( - GenericParamKey key) const { +llvm::Optional +GenericEnvironment::getMappingIfPresent(GenericParamKey key) const { // Find the index into the parallel arrays of generic parameters and // context types. auto genericParams = getGenericParams(); diff --git a/lib/AST/Identifier.cpp b/lib/AST/Identifier.cpp index bda1890eb06..58865340865 100644 --- a/lib/AST/Identifier.cpp +++ b/lib/AST/Identifier.cpp @@ -237,7 +237,8 @@ ObjCSelector::parse(ASTContext &ctx, StringRef string) { // If there is no colon, we have a nullary selector. if (colonPos == StringRef::npos) { - if (string.empty() || !Lexer::isIdentifier(string)) return llvm::None; + if (string.empty() || !Lexer::isIdentifier(string)) + return llvm::None; return ObjCSelector(ctx, 0, { ctx.getIdentifier(string) }); } @@ -248,7 +249,8 @@ ObjCSelector::parse(ASTContext &ctx, StringRef string) { if (piece.empty()) { pieces.push_back(Identifier()); } else { - if (!Lexer::isIdentifier(piece)) return llvm::None; + if (!Lexer::isIdentifier(piece)) + return llvm::None; pieces.push_back(ctx.getIdentifier(piece)); } @@ -258,7 +260,8 @@ ObjCSelector::parse(ASTContext &ctx, StringRef string) { } while (colonPos != StringRef::npos); // If anything remains of the string, it's not a selector. - if (!string.empty()) return llvm::None; + if (!string.empty()) + return llvm::None; return ObjCSelector(ctx, pieces.size(), pieces); } diff --git a/lib/AST/Module.cpp b/lib/AST/Module.cpp index 1a202ba6f03..6ac2b16dd1f 100644 --- a/lib/AST/Module.cpp +++ b/lib/AST/Module.cpp @@ -2085,7 +2085,7 @@ Fingerprint SourceFile::getInterfaceHash() const { auto *mutableThis = const_cast(this); llvm::Optional interfaceHasher = evaluateOrDefault(eval, ParseSourceFileRequest{mutableThis}, {}) - .InterfaceHasher; + .InterfaceHasher; return Fingerprint{StableHasher{interfaceHasher.value()}.finalize()}; } @@ -2468,8 +2468,9 @@ NominalTypeDecl *ModuleDecl::getMainTypeDecl() const { return nominalType; } -bool ModuleDecl::registerEntryPointFile(FileUnit *file, SourceLoc diagLoc, - llvm::Optional kind) { +bool ModuleDecl::registerEntryPointFile( + FileUnit *file, SourceLoc diagLoc, + llvm::Optional kind) { if (!EntryPointInfo.hasEntryPoint()) { EntryPointInfo.setEntryPointFile(file); return false; diff --git a/lib/AST/ModuleDependencies.cpp b/lib/AST/ModuleDependencies.cpp index dbb324fd443..4f6a81bc258 100644 --- a/lib/AST/ModuleDependencies.cpp +++ b/lib/AST/ModuleDependencies.cpp @@ -537,7 +537,8 @@ void SwiftDependencyScanningService::configureForContextHash(StringRef scanningC } } -llvm::Optional SwiftDependencyScanningService::findDependency( +llvm::Optional +SwiftDependencyScanningService::findDependency( StringRef moduleName, llvm::Optional kind, StringRef scanningContextHash) const { if (!kind) { @@ -616,7 +617,8 @@ ModuleDependenciesCache::ModuleDependenciesCache( } } -llvm::Optional ModuleDependenciesCache::findDependency( +llvm::Optional +ModuleDependenciesCache::findDependency( StringRef moduleName, llvm::Optional kind) const { auto optionalDep = globalScanningService.findDependency(moduleName, kind, scannerContextHash); diff --git a/lib/AST/NameLookupRequests.cpp b/lib/AST/NameLookupRequests.cpp index 9179e6ddafb..e0b6d35af46 100644 --- a/lib/AST/NameLookupRequests.cpp +++ b/lib/AST/NameLookupRequests.cpp @@ -131,7 +131,8 @@ void ProtocolRequirementsRequest::cacheResult(ArrayRef PDs) const { // Missing designated initializers computation //----------------------------------------------------------------------------// -llvm::Optional HasMissingDesignatedInitializersRequest::getCachedResult() const { +llvm::Optional +HasMissingDesignatedInitializersRequest::getCachedResult() const { auto classDecl = std::get<0>(getStorage()); return classDecl->getCachedHasMissingDesignatedInitializers(); } @@ -172,7 +173,8 @@ HasMissingDesignatedInitializersRequest::evaluate(Evaluator &evaluator, // Extended nominal computation. //----------------------------------------------------------------------------// -llvm::Optional ExtendedNominalRequest::getCachedResult() const { +llvm::Optional +ExtendedNominalRequest::getCachedResult() const { // Note: if we fail to compute any nominal declaration, it's considered // a cache miss. This allows us to recompute the extended nominal types // during extension binding. @@ -227,7 +229,8 @@ void GetDestructorRequest::cacheResult(DestructorDecl *value) const { // GenericParamListRequest computation. //----------------------------------------------------------------------------// -llvm::Optional GenericParamListRequest::getCachedResult() const { +llvm::Optional +GenericParamListRequest::getCachedResult() const { using GenericParamsState = GenericContext::GenericParamsState; auto *decl = std::get<0>(getStorage()); switch (decl->GenericParamsAndState.getInt()) { diff --git a/lib/AST/PlatformKind.cpp b/lib/AST/PlatformKind.cpp index bee5251da64..83ae9f4fcce 100644 --- a/lib/AST/PlatformKind.cpp +++ b/lib/AST/PlatformKind.cpp @@ -58,7 +58,8 @@ llvm::Optional swift::platformFromString(StringRef Name) { .Default(llvm::Optional()); } -llvm::Optional swift::closestCorrectedPlatformString(StringRef candidate) { +llvm::Optional +swift::closestCorrectedPlatformString(StringRef candidate) { auto lowerCasedCandidate = candidate.lower(); auto lowerCasedCandidateRef = StringRef(lowerCasedCandidate); auto minDistance = std::numeric_limits::max(); diff --git a/lib/AST/RequirementMachine/ConcreteContraction.cpp b/lib/AST/RequirementMachine/ConcreteContraction.cpp index 8ec70b3bac2..dd02e2a4284 100644 --- a/lib/AST/RequirementMachine/ConcreteContraction.cpp +++ b/lib/AST/RequirementMachine/ConcreteContraction.cpp @@ -200,7 +200,8 @@ class ConcreteContraction { Other }; - llvm::Optional substTypeParameterRec(Type type, Position position) const; + llvm::Optional substTypeParameterRec(Type type, + Position position) const; Type substTypeParameter(Type type, Position position) const; Type substType(Type type) const; Requirement substRequirement(const Requirement &req) const; @@ -233,8 +234,8 @@ public: /// to be some subclass of SomeClass which does conform to Sequence; /// this is perfectly valid, and we cannot substitute the 'T.Element' /// requirement. In this case, this method returns None. -llvm::Optional ConcreteContraction::substTypeParameterRec( - Type type, Position position) const { +llvm::Optional +ConcreteContraction::substTypeParameterRec(Type type, Position position) const { // If we have a superclass (T : C) or same-type requirement (T == C), // don't substitute T, since then we end up with 'C == C' or 'C : C', @@ -356,13 +357,12 @@ Type ConcreteContraction::substTypeParameter( /// Substitute all type parameters occurring in structural positions of \p type. Type ConcreteContraction::substType(Type type) const { - return type.transformRec( - [&](Type type) -> llvm::Optional { - if (!type->isTypeParameter()) - return llvm::None; + return type.transformRec([&](Type type) -> llvm::Optional { + if (!type->isTypeParameter()) + return llvm::None; - return substTypeParameter(type, Position::Other); - }); + return substTypeParameter(type, Position::Other); + }); } /// Substitute all type parameters occurring in the given requirement. diff --git a/lib/AST/RequirementMachine/Diagnostics.h b/lib/AST/RequirementMachine/Diagnostics.h index eb8547c12e3..721d38f194c 100644 --- a/lib/AST/RequirementMachine/Diagnostics.h +++ b/lib/AST/RequirementMachine/Diagnostics.h @@ -57,7 +57,8 @@ struct RequirementError { private: RequirementError(Kind kind, Requirement requirement, SourceLoc loc) - : kind(kind), requirement(requirement), conflictingRequirement(llvm::None), loc(loc) {} + : kind(kind), requirement(requirement), + conflictingRequirement(llvm::None), loc(loc) {} RequirementError(Kind kind, Requirement requirement, Requirement conflict, diff --git a/lib/AST/RequirementMachine/HomotopyReduction.cpp b/lib/AST/RequirementMachine/HomotopyReduction.cpp index 9e053d56de4..386099f9e2e 100644 --- a/lib/AST/RequirementMachine/HomotopyReduction.cpp +++ b/lib/AST/RequirementMachine/HomotopyReduction.cpp @@ -229,8 +229,8 @@ void RewriteSystem::computeRecursiveRules() { /// 3) Finally, redundant conformance rules are deleted, with /// \p redundantConformances equal to the set of conformance rules that are /// not minimal conformances. -llvm::Optional> RewriteSystem:: -findRuleToDelete(EliminationPredicate isRedundantRuleFn) { +llvm::Optional> +RewriteSystem::findRuleToDelete(EliminationPredicate isRedundantRuleFn) { SmallVector, 2> redundancyCandidates; for (unsigned loopID : indices(Loops)) { auto &loop = Loops[loopID]; diff --git a/lib/AST/RequirementMachine/PropertyMap.h b/lib/AST/RequirementMachine/PropertyMap.h index 8fee0133cf1..d8f38b98101 100644 --- a/lib/AST/RequirementMachine/PropertyMap.h +++ b/lib/AST/RequirementMachine/PropertyMap.h @@ -253,11 +253,10 @@ private: Symbol lhsProperty, unsigned lhsRuleID, Symbol rhsProperty, unsigned rhsRuleID); - void unifyConcreteTypes(Term key, - llvm::Optional &bestProperty, - llvm::SmallVectorImpl> & - existingRules, - Symbol property, unsigned ruleID); + void unifyConcreteTypes( + Term key, llvm::Optional &bestProperty, + llvm::SmallVectorImpl> &existingRules, + Symbol property, unsigned ruleID); void recordSuperclassRelation(Term key, Symbol superclassType, diff --git a/lib/AST/RequirementMachine/PropertyUnification.cpp b/lib/AST/RequirementMachine/PropertyUnification.cpp index 5c34a8943e2..4906914656a 100644 --- a/lib/AST/RequirementMachine/PropertyUnification.cpp +++ b/lib/AST/RequirementMachine/PropertyUnification.cpp @@ -544,8 +544,7 @@ void PropertyMap::unifyConcreteTypes(Term key, /// /// Used by addSuperclassProperty() and addConcreteTypeProperty(). void PropertyMap::unifyConcreteTypes( - Term key, - llvm::Optional &bestProperty, + Term key, llvm::Optional &bestProperty, llvm::SmallVectorImpl> &existingRules, Symbol property, unsigned ruleID) { // Unify this rule with all other concrete type rules we've seen so far, diff --git a/lib/AST/RequirementMachine/RequirementBuilder.cpp b/lib/AST/RequirementMachine/RequirementBuilder.cpp index 7ced299b7b9..a06085fb4d8 100644 --- a/lib/AST/RequirementMachine/RequirementBuilder.cpp +++ b/lib/AST/RequirementMachine/RequirementBuilder.cpp @@ -167,10 +167,10 @@ public: static Type replaceTypeParametersWithErrorTypes(Type type) { return type.transformRec([](Type t) -> llvm::Optional { - if (t->isTypeParameter()) - return ErrorType::get(t->getASTContext()); - return llvm::None; - }); + if (t->isTypeParameter()) + return ErrorType::get(t->getASTContext()); + return llvm::None; + }); } void RequirementBuilder::addRequirementRules(ArrayRef rules) { diff --git a/lib/AST/RequirementMachine/RewriteContext.cpp b/lib/AST/RequirementMachine/RewriteContext.cpp index 0e1e692517a..a73bdb3903e 100644 --- a/lib/AST/RequirementMachine/RewriteContext.cpp +++ b/lib/AST/RequirementMachine/RewriteContext.cpp @@ -159,28 +159,34 @@ static DebugOptions parseDebugFlags(StringRef debugFlags) { SmallVector debug; debugFlags.split(debug, ','); for (auto flagStr : debug) { - auto flag = llvm::StringSwitch>(flagStr) - .Case("simplify", DebugFlags::Simplify) - .Case("add", DebugFlags::Add) - .Case("completion", DebugFlags::Completion) - .Case("property-map", DebugFlags::PropertyMap) - .Case("concrete-unification", DebugFlags::ConcreteUnification) - .Case("concretize-nested-types", DebugFlags::ConcretizeNestedTypes) - .Case("conditional-requirements", DebugFlags::ConditionalRequirements) - .Case("homotopy-reduction", DebugFlags::HomotopyReduction) - .Case("homotopy-reduction-detail", DebugFlags::HomotopyReductionDetail) - .Case("minimal-conformances", DebugFlags::MinimalConformances) - .Case("minimal-conformances-detail", DebugFlags::MinimalConformancesDetail) - .Case("protocol-dependencies", DebugFlags::ProtocolDependencies) - .Case("minimization", DebugFlags::Minimization) - .Case("redundant-rules", DebugFlags::RedundantRules) - .Case("redundant-rules-detail", DebugFlags::RedundantRulesDetail) - .Case("concrete-contraction", DebugFlags::ConcreteContraction) - .Case("propagate-requirement-ids", DebugFlags::PropagateRequirementIDs) - .Case("timers", DebugFlags::Timers) - .Case("conflicting-rules", DebugFlags::ConflictingRules) - .Case("split-concrete-equiv-class", DebugFlags::SplitConcreteEquivalenceClass) - .Default(llvm::None); + auto flag = + llvm::StringSwitch>(flagStr) + .Case("simplify", DebugFlags::Simplify) + .Case("add", DebugFlags::Add) + .Case("completion", DebugFlags::Completion) + .Case("property-map", DebugFlags::PropertyMap) + .Case("concrete-unification", DebugFlags::ConcreteUnification) + .Case("concretize-nested-types", DebugFlags::ConcretizeNestedTypes) + .Case("conditional-requirements", + DebugFlags::ConditionalRequirements) + .Case("homotopy-reduction", DebugFlags::HomotopyReduction) + .Case("homotopy-reduction-detail", + DebugFlags::HomotopyReductionDetail) + .Case("minimal-conformances", DebugFlags::MinimalConformances) + .Case("minimal-conformances-detail", + DebugFlags::MinimalConformancesDetail) + .Case("protocol-dependencies", DebugFlags::ProtocolDependencies) + .Case("minimization", DebugFlags::Minimization) + .Case("redundant-rules", DebugFlags::RedundantRules) + .Case("redundant-rules-detail", DebugFlags::RedundantRulesDetail) + .Case("concrete-contraction", DebugFlags::ConcreteContraction) + .Case("propagate-requirement-ids", + DebugFlags::PropagateRequirementIDs) + .Case("timers", DebugFlags::Timers) + .Case("conflicting-rules", DebugFlags::ConflictingRules) + .Case("split-concrete-equiv-class", + DebugFlags::SplitConcreteEquivalenceClass) + .Default(llvm::None); if (!flag) { llvm::errs() << "Unknown debug flag in -debug-requirement-machine " << flagStr << "\n"; diff --git a/lib/AST/RequirementMachine/RewriteLoop.h b/lib/AST/RequirementMachine/RewriteLoop.h index ff3908f7d1e..cd2310549ed 100644 --- a/lib/AST/RequirementMachine/RewriteLoop.h +++ b/lib/AST/RequirementMachine/RewriteLoop.h @@ -25,7 +25,6 @@ namespace llvm { namespace swift { - namespace rewriting { class RewriteSystem; diff --git a/lib/AST/RequirementMachine/RewriteSystem.cpp b/lib/AST/RequirementMachine/RewriteSystem.cpp index b579349a504..145562f206a 100644 --- a/lib/AST/RequirementMachine/RewriteSystem.cpp +++ b/lib/AST/RequirementMachine/RewriteSystem.cpp @@ -308,7 +308,8 @@ bool RewriteSystem::addExplicitRule(MutableTerm lhs, MutableTerm rhs, void RewriteSystem::addRules( std::vector &&importedRules, std::vector> &&permanentRules, - std::vector>> &&requirementRules) { + std::vector>> + &&requirementRules) { unsigned ruleCount = Rules.size(); if (ruleCount == 0) { diff --git a/lib/AST/RequirementMachine/RewriteSystem.h b/lib/AST/RequirementMachine/RewriteSystem.h index 8d8e7809882..ad3e3421316 100644 --- a/lib/AST/RequirementMachine/RewriteSystem.h +++ b/lib/AST/RequirementMachine/RewriteSystem.h @@ -132,12 +132,13 @@ public: DebugOptions getDebugOptions() const { return Debug; } - void initialize(bool recordLoops, - ArrayRef protos, - std::vector &&writtenRequirements, - std::vector &&importedRules, - std::vector> &&permanentRules, - std::vector>> &&requirementRules); + void initialize( + bool recordLoops, ArrayRef protos, + std::vector &&writtenRequirements, + std::vector &&importedRules, + std::vector> &&permanentRules, + std::vector>> &&requirementRules); unsigned getLongestInitialRule() const { return LongestInitialRule; @@ -185,15 +186,17 @@ public: bool addExplicitRule(MutableTerm lhs, MutableTerm rhs, llvm::Optional requirementID); - void addRules(std::vector &&importedRules, - std::vector> &&permanentRules, - std::vector>> &&requirementRules); + void addRules( + std::vector &&importedRules, + std::vector> &&permanentRules, + std::vector>> &&requirementRules); bool simplify(MutableTerm &term, RewritePath *path=nullptr) const; - llvm::Optional - simplifySubstitutions(Term baseTerm, Symbol symbol, const PropertyMap *map, - RewritePath *path=nullptr); + llvm::Optional simplifySubstitutions(Term baseTerm, Symbol symbol, + const PropertyMap *map, + RewritePath *path = nullptr); ////////////////////////////////////////////////////////////////////////////// /// @@ -306,10 +309,9 @@ private: public: unsigned recordTypeDifference(const TypeDifference &difference); - bool - computeTypeDifference(Term term, Symbol lhs, Symbol rhs, - llvm::Optional &lhsDifferenceID, - llvm::Optional &rhsDifferenceID); + bool computeTypeDifference(Term term, Symbol lhs, Symbol rhs, + llvm::Optional &lhsDifferenceID, + llvm::Optional &rhsDifferenceID); const TypeDifference &getTypeDifference(unsigned index) const; diff --git a/lib/AST/RequirementMachine/Rule.cpp b/lib/AST/RequirementMachine/Rule.cpp index 4ad0ab5aa30..e10c3a3cb0f 100644 --- a/lib/AST/RequirementMachine/Rule.cpp +++ b/lib/AST/RequirementMachine/Rule.cpp @@ -263,7 +263,8 @@ unsigned Rule::getNesting() const { } /// Linear order on rules; compares LHS followed by RHS. -llvm::Optional Rule::compare(const Rule &other, RewriteContext &ctx) const { +llvm::Optional Rule::compare(const Rule &other, + RewriteContext &ctx) const { llvm::Optional compare = LHS.compare(other.LHS, ctx); if (!compare.has_value() || *compare != 0) return compare; diff --git a/lib/AST/RequirementMachine/RuleBuilder.h b/lib/AST/RequirementMachine/RuleBuilder.h index 2e106320502..95753e227a9 100644 --- a/lib/AST/RequirementMachine/RuleBuilder.h +++ b/lib/AST/RequirementMachine/RuleBuilder.h @@ -111,10 +111,9 @@ private: void addPermanentProtocolRules(const ProtocolDecl *proto); void addAssociatedType(const AssociatedTypeDecl *type, const ProtocolDecl *proto); - void addRequirement(const Requirement &req, - const ProtocolDecl *proto, - llvm::Optional> substitutions=llvm::None, - llvm::Optional requirementID=llvm::None); + void addRequirement(const Requirement &req, const ProtocolDecl *proto, + llvm::Optional> substitutions = llvm::None, + llvm::Optional requirementID = llvm::None); void addRequirement(const StructuralRequirement &req, const ProtocolDecl *proto); void addTypeAlias(const ProtocolTypeAlias &alias, diff --git a/lib/AST/RequirementMachine/SimplifySubstitutions.cpp b/lib/AST/RequirementMachine/SimplifySubstitutions.cpp index d55780e21ef..c9305607574 100644 --- a/lib/AST/RequirementMachine/SimplifySubstitutions.cpp +++ b/lib/AST/RequirementMachine/SimplifySubstitutions.cpp @@ -281,10 +281,8 @@ void RewriteSystem::processTypeDifference(const TypeDifference &difference, /// /// Otherwise returns an index which can be passed to /// RewriteSystem::getTypeDifference(). -llvm::Optional -RewriteSystem::simplifySubstitutions(Term baseTerm, Symbol symbol, - const PropertyMap *map, - RewritePath *path) { +llvm::Optional RewriteSystem::simplifySubstitutions( + Term baseTerm, Symbol symbol, const PropertyMap *map, RewritePath *path) { assert(symbol.hasSubstitutions()); // Fast path if the type is fully concrete. diff --git a/lib/AST/RequirementMachine/Symbol.h b/lib/AST/RequirementMachine/Symbol.h index 2250bdc84fd..228e75112c9 100644 --- a/lib/AST/RequirementMachine/Symbol.h +++ b/lib/AST/RequirementMachine/Symbol.h @@ -12,8 +12,8 @@ #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/StringRef.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/StringRef.h" #ifndef SWIFT_RQM_SYMBOL_H #define SWIFT_RQM_SYMBOL_H @@ -209,8 +209,7 @@ public: static Symbol forLayout(LayoutConstraint layout, RewriteContext &ctx); - static Symbol forSuperclass(CanType type, - llvm::ArrayRef substitutions, + static Symbol forSuperclass(CanType type, llvm::ArrayRef substitutions, RewriteContext &ctx); static Symbol forConcreteType(CanType type, @@ -226,9 +225,8 @@ public: llvm::Optional compare(Symbol other, RewriteContext &ctx) const; - Symbol withConcreteSubstitutions( - llvm::ArrayRef substitutions, - RewriteContext &ctx) const; + Symbol withConcreteSubstitutions(llvm::ArrayRef substitutions, + RewriteContext &ctx) const; Symbol transformConcreteSubstitutions( llvm::function_ref fn, diff --git a/lib/AST/RequirementMachine/Term.cpp b/lib/AST/RequirementMachine/Term.cpp index 911b1ef558c..56f604af25b 100644 --- a/lib/AST/RequirementMachine/Term.cpp +++ b/lib/AST/RequirementMachine/Term.cpp @@ -128,10 +128,11 @@ bool Term::containsUnresolvedSymbols() const { /// /// This is used to implement Term::compare() and MutableTerm::compare() /// below. -static llvm::Optional -shortlexCompare(const Symbol *lhsBegin, const Symbol *lhsEnd, - const Symbol *rhsBegin, const Symbol *rhsEnd, - RewriteContext &ctx) { +static llvm::Optional shortlexCompare(const Symbol *lhsBegin, + const Symbol *lhsEnd, + const Symbol *rhsBegin, + const Symbol *rhsEnd, + RewriteContext &ctx) { // First, compare the number of name symbols. unsigned lhsNameCount = 0; for (auto *iter = lhsBegin; iter != lhsEnd; ++iter) { @@ -179,15 +180,14 @@ shortlexCompare(const Symbol *lhsBegin, const Symbol *lhsEnd, /// Shortlex order on terms. Returns None if the terms are identical except /// for an incomparable superclass or concrete type symbol at the end. -llvm::Optional -Term::compare(Term other, RewriteContext &ctx) const { +llvm::Optional Term::compare(Term other, RewriteContext &ctx) const { return shortlexCompare(begin(), end(), other.begin(), other.end(), ctx); } /// Shortlex order on mutable terms. Returns None if the terms are identical /// except for an incomparable superclass or concrete type symbol at the end. -llvm::Optional -MutableTerm::compare(const MutableTerm &other, RewriteContext &ctx) const { +llvm::Optional MutableTerm::compare(const MutableTerm &other, + RewriteContext &ctx) const { return shortlexCompare(begin(), end(), other.begin(), other.end(), ctx); } diff --git a/lib/AST/RequirementMachine/Term.h b/lib/AST/RequirementMachine/Term.h index 599191782dd..d543ad6cee2 100644 --- a/lib/AST/RequirementMachine/Term.h +++ b/lib/AST/RequirementMachine/Term.h @@ -10,10 +10,10 @@ // //===----------------------------------------------------------------------===// -#include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/Optional.h" #include "Symbol.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/SmallVector.h" #ifndef SWIFT_RQM_TERM_H #define SWIFT_RQM_TERM_H @@ -124,7 +124,7 @@ public: : Symbols(std::move(symbols)) {} explicit MutableTerm(llvm::ArrayRef symbols) - : Symbols(symbols.begin(), symbols.end()) {} + : Symbols(symbols.begin(), symbols.end()) {} explicit MutableTerm(Term term) : Symbols(term.begin(), term.end()) {} @@ -145,7 +145,8 @@ public: Symbols.append(from, to); } - llvm::Optional compare(const MutableTerm &other, RewriteContext &ctx) const; + llvm::Optional compare(const MutableTerm &other, + RewriteContext &ctx) const; bool empty() const { return Symbols.empty(); } diff --git a/lib/AST/RequirementMachine/Trie.h b/lib/AST/RequirementMachine/Trie.h index 895fcefdf28..6ef63444612 100644 --- a/lib/AST/RequirementMachine/Trie.h +++ b/lib/AST/RequirementMachine/Trie.h @@ -73,7 +73,7 @@ public: /// Returns the old value if the trie already had an entry for this key; /// this is actually an invariant violation, but we can produce a better /// assertion further up the stack. - template + template llvm::Optional insert(Iter begin, Iter end, ValueType value) { assert(begin != end); auto *node = &Root; @@ -100,9 +100,8 @@ public: /// Find the shortest or longest prefix of the range given by [begin,end), /// depending on whether the Kind template parameter was bound to /// MatchKind::Shortest or MatchKind::Longest. - template - llvm::Optional - find(Iter begin, Iter end) const { + template + llvm::Optional find(Iter begin, Iter end) const { assert(begin != end); auto *node = &Root; diff --git a/lib/AST/RequirementMachine/TypeDifference.cpp b/lib/AST/RequirementMachine/TypeDifference.cpp index 8f9ef5a1cb8..e72a8cf1e3c 100644 --- a/lib/AST/RequirementMachine/TypeDifference.cpp +++ b/lib/AST/RequirementMachine/TypeDifference.cpp @@ -415,10 +415,10 @@ const TypeDifference &RewriteSystem::getTypeDifference(unsigned index) const { /// /// See the comment at the top of TypeDifference in TypeDifference.h for a /// description of the actual transformations. -bool -RewriteSystem::computeTypeDifference(Term baseTerm, Symbol lhs, Symbol rhs, - llvm::Optional &lhsDifferenceID, - llvm::Optional &rhsDifferenceID) { +bool RewriteSystem::computeTypeDifference( + Term baseTerm, Symbol lhs, Symbol rhs, + llvm::Optional &lhsDifferenceID, + llvm::Optional &rhsDifferenceID) { assert(lhs.getKind() == rhs.getKind()); lhsDifferenceID = llvm::None; diff --git a/lib/AST/Stmt.cpp b/lib/AST/Stmt.cpp index 710b34b725b..b5b35b51de7 100644 --- a/lib/AST/Stmt.cpp +++ b/lib/AST/Stmt.cpp @@ -175,11 +175,10 @@ SourceLoc Stmt::getEndLoc() const { llvm_unreachable("statement type not handled!"); } -BraceStmt::BraceStmt(SourceLoc lbloc, ArrayRef elts, - SourceLoc rbloc, llvm::Optional implicit) - : Stmt(StmtKind::Brace, getDefaultImplicitFlag(implicit, lbloc)), - LBLoc(lbloc), RBLoc(rbloc) -{ +BraceStmt::BraceStmt(SourceLoc lbloc, ArrayRef elts, SourceLoc rbloc, + llvm::Optional implicit) + : Stmt(StmtKind::Brace, getDefaultImplicitFlag(implicit, lbloc)), + LBLoc(lbloc), RBLoc(rbloc) { Bits.BraceStmt.NumElements = elts.size(); std::uninitialized_copy(elts.begin(), elts.end(), getTrailingObjects()); @@ -353,7 +352,7 @@ SourceLoc ReturnStmt::getEndLoc() const { } YieldStmt *YieldStmt::create(const ASTContext &ctx, SourceLoc yieldLoc, - SourceLoc lpLoc, ArrayRef yields, + SourceLoc lpLoc, ArrayRef yields, SourceLoc rpLoc, llvm::Optional implicit) { void *buffer = ctx.Allocate(totalSizeToAlloc(yields.size()), alignof(YieldStmt)); @@ -621,9 +620,8 @@ static StmtCondition exprToCond(Expr *C, ASTContext &Ctx) { IfStmt::IfStmt(SourceLoc IfLoc, Expr *Cond, Stmt *Then, SourceLoc ElseLoc, Stmt *Else, llvm::Optional implicit, ASTContext &Ctx) - : IfStmt(LabeledStmtInfo(), IfLoc, exprToCond(Cond, Ctx), Then, ElseLoc, Else, - implicit) { -} + : IfStmt(LabeledStmtInfo(), IfLoc, exprToCond(Cond, Ctx), Then, ElseLoc, + Else, implicit) {} ArrayRef IfStmt::getBranches(SmallVectorImpl &scratch) const { assert(scratch.empty()); @@ -660,11 +658,7 @@ bool IfStmt::isSyntacticallyExhaustive() const { GuardStmt::GuardStmt(SourceLoc GuardLoc, Expr *Cond, BraceStmt *Body, llvm::Optional implicit, ASTContext &Ctx) - : GuardStmt(GuardLoc, exprToCond(Cond, Ctx), Body, implicit) { - -} - - + : GuardStmt(GuardLoc, exprToCond(Cond, Ctx), Body, implicit) {} SourceLoc RepeatWhileStmt::getEndLoc() const { return Cond->getEndLoc(); } @@ -719,14 +713,13 @@ CaseStmt::CaseStmt(CaseParentKind parentKind, SourceLoc itemIntroducerLoc, } } -CaseStmt *CaseStmt::create(ASTContext &ctx, CaseParentKind ParentKind, - SourceLoc caseLoc, - ArrayRef caseLabelItems, - SourceLoc unknownAttrLoc, SourceLoc colonLoc, - BraceStmt *body, - llvm::Optional> caseVarDecls, - llvm::Optional implicit, - NullablePtr fallthroughStmt) { +CaseStmt * +CaseStmt::create(ASTContext &ctx, CaseParentKind ParentKind, SourceLoc caseLoc, + ArrayRef caseLabelItems, + SourceLoc unknownAttrLoc, SourceLoc colonLoc, BraceStmt *body, + llvm::Optional> caseVarDecls, + llvm::Optional implicit, + NullablePtr fallthroughStmt) { void *mem = ctx.Allocate(totalSizeToAlloc( fallthroughStmt.isNonNull(), caseLabelItems.size()), diff --git a/lib/AST/SubstitutionMap.cpp b/lib/AST/SubstitutionMap.cpp index 7b4f9ed7159..4e2c64783b8 100644 --- a/lib/AST/SubstitutionMap.cpp +++ b/lib/AST/SubstitutionMap.cpp @@ -352,7 +352,8 @@ SubstitutionMap::lookupConformance(CanType type, ProtocolDecl *proto) const { auto genericSig = getGenericSignature(); auto getSignatureConformance = - [&](Type type, ProtocolDecl *proto) -> llvm::Optional { + [&](Type type, + ProtocolDecl *proto) -> llvm::Optional { unsigned index = 0; for (auto reqt : genericSig.getRequirements()) { if (reqt.getKind() == RequirementKind::Conformance) { diff --git a/lib/AST/Type.cpp b/lib/AST/Type.cpp index 7674247880f..ccb64354851 100644 --- a/lib/AST/Type.cpp +++ b/lib/AST/Type.cpp @@ -4034,11 +4034,10 @@ bool SILFunctionType::hasNonDerivableClangType() { if (clangTypeInfo.empty()) return false; auto results = getResults(); - auto computedClangType = - getASTContext().getCanonicalClangFunctionType( - getParameters(), - results.empty() ? llvm::None : llvm::Optional(results[0]), - getRepresentation()); + auto computedClangType = getASTContext().getCanonicalClangFunctionType( + getParameters(), + results.empty() ? llvm::None : llvm::Optional(results[0]), + getRepresentation()); assert(computedClangType && "Failed to compute Clang type."); return clangTypeInfo != ClangTypeInfo(computedClangType); } @@ -4135,19 +4134,20 @@ static bool transformSILParameter( } Type Type::transform(llvm::function_ref fn) const { - return transformWithPosition(TypePosition::Invariant, - [fn](TypeBase *type, auto) -> llvm::Optional { - Type transformed = fn(Type(type)); - if (!transformed) - return Type(); + return transformWithPosition( + TypePosition::Invariant, + [fn](TypeBase *type, auto) -> llvm::Optional { + Type transformed = fn(Type(type)); + if (!transformed) + return Type(); - // If the function didn't change the type at - // all, let transformRec() recurse. - if (transformed.getPointer() == type) - return llvm::None; + // If the function didn't change the type at + // all, let transformRec() recurse. + if (transformed.getPointer() == type) + return llvm::None; - return transformed; - }); + return transformed; + }); } static PackType *getTransformedPack(Type substType) { @@ -4175,7 +4175,8 @@ Type Type::transformRec( Type Type::transformWithPosition( TypePosition pos, - llvm::function_ref(TypeBase *, TypePosition)> fn) const { + llvm::function_ref(TypeBase *, TypePosition)> fn) + const { if (!isa(getPointer())) { // Transform this type node. if (llvm::Optional transformed = fn(getPointer(), pos)) diff --git a/lib/AST/TypeCheckRequests.cpp b/lib/AST/TypeCheckRequests.cpp index cbfc5aacee2..42b95b86909 100644 --- a/lib/AST/TypeCheckRequests.cpp +++ b/lib/AST/TypeCheckRequests.cpp @@ -697,8 +697,7 @@ void StorageImplInfoRequest::cacheResult(StorageImplInfo value) const { // RequiresOpaqueAccessorsRequest computation. //----------------------------------------------------------------------------// -llvm::Optional -RequiresOpaqueAccessorsRequest::getCachedResult() const { +llvm::Optional RequiresOpaqueAccessorsRequest::getCachedResult() const { auto *storage = std::get<0>(getStorage()); if (storage->LazySemanticInfo.RequiresOpaqueAccessorsComputed) return storage->LazySemanticInfo.RequiresOpaqueAccessors; @@ -733,8 +732,7 @@ void RequiresOpaqueModifyCoroutineRequest::cacheResult(bool value) const { // IsAccessorTransparentRequest computation. //----------------------------------------------------------------------------// -llvm::Optional -IsAccessorTransparentRequest::getCachedResult() const { +llvm::Optional IsAccessorTransparentRequest::getCachedResult() const { auto *accessor = std::get<0>(getStorage()); return accessor->getCachedIsTransparent(); } @@ -795,7 +793,8 @@ void IsImplicitlyUnwrappedOptionalRequest::cacheResult(bool value) const { // GenericSignatureRequest computation. //----------------------------------------------------------------------------// -llvm::Optional GenericSignatureRequest::getCachedResult() const { +llvm::Optional +GenericSignatureRequest::getCachedResult() const { auto *GC = std::get<0>(getStorage()); if (GC->GenericSigAndBit.getInt()) { return GC->GenericSigAndBit.getPointer(); @@ -840,8 +839,7 @@ void InferredGenericSignatureRequest::noteCycleStep(DiagnosticEngine &d) const { // UnderlyingTypeRequest computation. //----------------------------------------------------------------------------// -llvm::Optional -UnderlyingTypeRequest::getCachedResult() const { +llvm::Optional UnderlyingTypeRequest::getCachedResult() const { auto *typeAlias = std::get<0>(getStorage()); if (auto type = typeAlias->UnderlyingTy.getType()) return type; @@ -879,7 +877,8 @@ bool EnumRawValuesRequest::isCached() const { return std::get<1>(getStorage()) == TypeResolutionStage::Interface; } -llvm::Optional EnumRawValuesRequest::getCachedResult() const { +llvm::Optional +EnumRawValuesRequest::getCachedResult() const { auto *ED = std::get<0>(getStorage()); if (ED->SemanticFlags.contains(EnumDecl::HasFixedRawValuesAndTypes)) return std::make_tuple<>(); @@ -1098,7 +1097,8 @@ void swift::simple_display(llvm::raw_ostream &out, // InheritsSuperclassInitializersRequest computation. //----------------------------------------------------------------------------// -llvm::Optional InheritsSuperclassInitializersRequest::getCachedResult() const { +llvm::Optional +InheritsSuperclassInitializersRequest::getCachedResult() const { auto *decl = std::get<0>(getStorage()); return decl->getCachedInheritsSuperclassInitializers(); } @@ -1270,7 +1270,8 @@ llvm::Optional DefaultArgumentTypeRequest::getCachedResult() const { if (!defaultInfo) return llvm::None; - return defaultInfo->ExprType ? llvm::Optional(defaultInfo->ExprType) : llvm::None; + return defaultInfo->ExprType ? llvm::Optional(defaultInfo->ExprType) + : llvm::None; } void DefaultArgumentTypeRequest::cacheResult(Type type) const { @@ -1282,7 +1283,8 @@ void DefaultArgumentTypeRequest::cacheResult(Type type) const { // CallerSideDefaultArgExprRequest computation. //----------------------------------------------------------------------------// -llvm::Optional CallerSideDefaultArgExprRequest::getCachedResult() const { +llvm::Optional +CallerSideDefaultArgExprRequest::getCachedResult() const { auto *defaultExpr = std::get<0>(getStorage()); auto storage = defaultExpr->ContextOrCallerSideExpr; assert(!storage.isNull()); @@ -1428,7 +1430,8 @@ void TypeCheckSourceFileRequest::cacheResult(evaluator::SideEffect) const { // TypeCheckFunctionBodyRequest computation. //----------------------------------------------------------------------------// -llvm::Optional TypeCheckFunctionBodyRequest::getCachedResult() const { +llvm::Optional +TypeCheckFunctionBodyRequest::getCachedResult() const { using BodyKind = AbstractFunctionDecl::BodyKind; auto *afd = std::get<0>(getStorage()); switch (afd->getBodyKind()) { diff --git a/lib/AST/TypeSubstitution.cpp b/lib/AST/TypeSubstitution.cpp index 6de30724ba0..f0e9d9000a9 100644 --- a/lib/AST/TypeSubstitution.cpp +++ b/lib/AST/TypeSubstitution.cpp @@ -509,7 +509,8 @@ static Type substType(Type derivedType, unsigned level, if (auto packExpansionTy = dyn_cast(type)) { auto eltTys = IFS.expandPackExpansionType(packExpansionTy); - if (eltTys.size() == 1) return eltTys[0]; + if (eltTys.size() == 1) + return eltTys[0]; return Type(PackType::get(packExpansionTy->getASTContext(), eltTys)); } @@ -575,8 +576,8 @@ static Type substType(Type derivedType, unsigned level, if (IFS.shouldSubstituteOpaqueArchetypes() && isa(substOrig) && known->getCanonicalType() == substOrig->getCanonicalType()) - return llvm::None; // Recursively process the substitutions of the opaque type - // archetype. + return llvm::None; // Recursively process the substitutions of the + // opaque type archetype. return known; } @@ -928,7 +929,7 @@ Type TypeBase::adjustSuperclassMemberDeclType(const ValueDecl *baseDecl, // Replacing opaque result archetypes with their underlying types //===----------------------------------------------------------------------===// -static llvm::Optional> +static llvm::Optional> getArchetypeAndRootOpaqueArchetype(Type maybeOpaqueType) { auto archetype = dyn_cast(maybeOpaqueType.getPointer()); if (!archetype) diff --git a/lib/Basic/FileSystem.cpp b/lib/Basic/FileSystem.cpp index 517603573a9..3d44e0a250c 100644 --- a/lib/Basic/FileSystem.cpp +++ b/lib/Basic/FileSystem.cpp @@ -13,10 +13,10 @@ #include "swift/Basic/FileSystem.h" #include "clang/Basic/FileManager.h" -#include "llvm/ADT/Twine.h" #include "llvm/ADT/Optional.h" -#include "llvm/ADT/StringRef.h" #include "llvm/ADT/SmallString.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/Twine.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" @@ -95,7 +95,8 @@ tryToOpenTemporaryFile(llvm::Optional &openedStream, // Then because some tools glob for build artifacts (such as clang's own // GlobalModuleIndex.cpp), also append .tmp. llvm::SmallString<128> tempPath; - const llvm::StringRef outputExtension = llvm::sys::path::extension(outputPath); + const llvm::StringRef outputExtension = + llvm::sys::path::extension(outputPath); tempPath = outputPath.drop_back(outputExtension.size()); tempPath += "-%%%%%%%%"; tempPath += outputExtension; diff --git a/lib/Basic/JSONSerialization.cpp b/lib/Basic/JSONSerialization.cpp index 8fbbe6e9cec..6b72c8b64eb 100644 --- a/lib/Basic/JSONSerialization.cpp +++ b/lib/Basic/JSONSerialization.cpp @@ -76,8 +76,8 @@ void Output::endObject() { Stream << "}"; } -bool Output::preflightKey(llvm::StringRef Key, bool Required, bool SameAsDefault, - bool &UseDefault, void *&) { +bool Output::preflightKey(llvm::StringRef Key, bool Required, + bool SameAsDefault, bool &UseDefault, void *&) { UseDefault = false; if (Required || !SameAsDefault) { if (StateStack.back() != ObjectFirstKey) { @@ -235,7 +235,8 @@ llvm::StringRef ScalarReferenceTraits::stringRef(const bool &Val) { return (Val ? "true" : "false"); } -llvm::StringRef ScalarReferenceTraits::stringRef(const llvm::StringRef &Val) { +llvm::StringRef +ScalarReferenceTraits::stringRef(const llvm::StringRef &Val) { return Val; } @@ -244,8 +245,7 @@ ScalarReferenceTraits::stringRef(const std::string &Val) { return Val; } -void ScalarTraits::output(const uint8_t &Val, - llvm::raw_ostream &Out) { +void ScalarTraits::output(const uint8_t &Val, llvm::raw_ostream &Out) { // use temp uin32_t because ostream thinks uint8_t is a character uint32_t Num = Val; Out << Num; @@ -279,18 +279,15 @@ void ScalarTraits::output(const int8_t &Val, llvm::raw_ostream &Out) { Out << Num; } -void ScalarTraits::output(const int16_t &Val, - llvm::raw_ostream &Out) { +void ScalarTraits::output(const int16_t &Val, llvm::raw_ostream &Out) { Out << Val; } -void ScalarTraits::output(const int32_t &Val, - llvm::raw_ostream &Out) { +void ScalarTraits::output(const int32_t &Val, llvm::raw_ostream &Out) { Out << Val; } -void ScalarTraits::output(const int64_t &Val, - llvm::raw_ostream &Out) { +void ScalarTraits::output(const int64_t &Val, llvm::raw_ostream &Out) { Out << Val; } diff --git a/lib/Basic/LangOptions.cpp b/lib/Basic/LangOptions.cpp index b4b4462f14e..76fae3bf42e 100644 --- a/lib/Basic/LangOptions.cpp +++ b/lib/Basic/LangOptions.cpp @@ -22,9 +22,9 @@ #include "swift/Basic/Range.h" #include "swift/Config.h" #include "llvm/ADT/Hashing.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringSwitch.h" -#include "llvm/ADT/Optional.h" #include "llvm/Support/raw_ostream.h" #include @@ -475,7 +475,7 @@ llvm::Optional swift::getUpcomingFeature(llvm::StringRef name) { #define UPCOMING_FEATURE(FeatureName, SENumber, Version) \ .Case(#FeatureName, Feature::FeatureName) #include "swift/Basic/Features.def" - .Default(llvm::None); + .Default(llvm::None); } llvm::Optional swift::getExperimentalFeature(llvm::StringRef name) { @@ -484,7 +484,7 @@ llvm::Optional swift::getExperimentalFeature(llvm::StringRef name) { #define EXPERIMENTAL_FEATURE(FeatureName, AvailableInProd) \ .Case(#FeatureName, Feature::FeatureName) #include "swift/Basic/Features.def" - .Default(llvm::None); + .Default(llvm::None); } llvm::Optional swift::getFeatureLanguageVersion(Feature feature) { @@ -493,7 +493,8 @@ llvm::Optional swift::getFeatureLanguageVersion(Feature feature) { #define UPCOMING_FEATURE(FeatureName, SENumber, Version) \ case Feature::FeatureName: return Version; #include "swift/Basic/Features.def" - default: return llvm::None; + default: + return llvm::None; } } diff --git a/lib/Basic/ParseableOutput.cpp b/lib/Basic/ParseableOutput.cpp index 2de9ce3954b..4ceb43e0db5 100644 --- a/lib/Basic/ParseableOutput.cpp +++ b/lib/Basic/ParseableOutput.cpp @@ -147,10 +147,11 @@ public: class SignalledMessage : public TaskOutputMessage { std::string ErrorMsg; llvm::Optional Signal; + public: - SignalledMessage(StringRef Name, std::string Output, - int64_t Pid, sys::TaskProcessInformation ProcInfo, - StringRef ErrorMsg, llvm::Optional Signal) + SignalledMessage(StringRef Name, std::string Output, int64_t Pid, + sys::TaskProcessInformation ProcInfo, StringRef ErrorMsg, + llvm::Optional Signal) : TaskOutputMessage("signalled", Name, Output, Pid, ProcInfo), ErrorMsg(ErrorMsg), Signal(Signal) {} @@ -214,11 +215,9 @@ void parseable_output::emitFinishedMessage( emitMessage(os, msg); } -void parseable_output::emitSignalledMessage(raw_ostream &os, StringRef Name, - StringRef ErrorMsg, - StringRef Output, - llvm::Optional Signal, int64_t Pid, - TaskProcessInformation ProcInfo) { +void parseable_output::emitSignalledMessage( + raw_ostream &os, StringRef Name, StringRef ErrorMsg, StringRef Output, + llvm::Optional Signal, int64_t Pid, TaskProcessInformation ProcInfo) { SignalledMessage msg(Name, Output.str(), Pid, ProcInfo, ErrorMsg, Signal); emitMessage(os, msg); } diff --git a/lib/Basic/Platform.cpp b/lib/Basic/Platform.cpp index fb7fefcc4d3..1de1426e540 100644 --- a/lib/Basic/Platform.cpp +++ b/lib/Basic/Platform.cpp @@ -339,11 +339,12 @@ static llvm::Optional getEnvironmentForAppleTargetSpecificModuleTriple(const llvm::Triple &triple) { auto tripleEnvironment = triple.getEnvironmentName(); return llvm::StringSwitch>(tripleEnvironment) - .Cases("unknown", "", llvm::None) - // These values are also supported, but are handled by the default case below: - // .Case ("simulator", StringRef("simulator")) - // .Case ("macabi", StringRef("macabi")) - .Default(tripleEnvironment); + .Cases("unknown", "", llvm::None) + // These values are also supported, but are handled by the default case + // below: + // .Case ("simulator", StringRef("simulator")) + // .Case ("macabi", StringRef("macabi")) + .Default(tripleEnvironment); } llvm::Triple swift::getTargetSpecificModuleTriple(const llvm::Triple &triple) { @@ -398,7 +399,7 @@ llvm::Triple swift::getUnversionedTriple(const llvm::Triple &triple) { llvm::Optional swift::getSwiftRuntimeCompatibilityVersionForTarget( const llvm::Triple &Triple) { - #define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) if (Triple.isMacOSX()) { llvm::VersionTuple OSVersion; diff --git a/lib/Basic/SourceLoc.cpp b/lib/Basic/SourceLoc.cpp index 22d27073c28..98d8e270f83 100644 --- a/lib/Basic/SourceLoc.cpp +++ b/lib/Basic/SourceLoc.cpp @@ -398,9 +398,8 @@ bool SourceManager::hasGeneratedSourceInfo(unsigned bufferID) { return GeneratedSourceInfos.count(bufferID); } -llvm::Optional SourceManager::getGeneratedSourceInfo( - unsigned bufferID -) const { +llvm::Optional +SourceManager::getGeneratedSourceInfo(unsigned bufferID) const { auto known = GeneratedSourceInfos.find(bufferID); if (known == GeneratedSourceInfos.end()) return llvm::None; diff --git a/lib/Basic/StringExtras.cpp b/lib/Basic/StringExtras.cpp index da92818a88e..ffc953d03a4 100644 --- a/lib/Basic/StringExtras.cpp +++ b/lib/Basic/StringExtras.cpp @@ -348,7 +348,8 @@ size_t camel_case::findWord(StringRef string, StringRef word) { /// Skip a type suffix that can be dropped. static llvm::Optional skipTypeSuffix(StringRef typeName) { - if (typeName.empty()) return llvm::None; + if (typeName.empty()) + return llvm::None; auto lastWord = camel_case::getLastWord(typeName); @@ -1212,18 +1213,14 @@ static bool splitBaseName(StringRef &baseName, StringRef &argName, return false; } -bool swift::omitNeedlessWords(StringRef &baseName, - MutableArrayRef argNames, - StringRef firstParamName, - OmissionTypeName givenResultType, - OmissionTypeName contextType, - ArrayRef paramTypes, - bool returnsSelf, - bool isProperty, - const InheritedNameSet *allPropertyNames, - llvm::Optional completionHandlerIndex, - llvm::Optional completionHandlerName, - StringScratchSpace &scratch) { +bool swift::omitNeedlessWords( + StringRef &baseName, MutableArrayRef argNames, + StringRef firstParamName, OmissionTypeName givenResultType, + OmissionTypeName contextType, ArrayRef paramTypes, + bool returnsSelf, bool isProperty, const InheritedNameSet *allPropertyNames, + llvm::Optional completionHandlerIndex, + llvm::Optional completionHandlerName, + StringScratchSpace &scratch) { bool anyChanges = false; OmissionTypeName resultType = returnsSelf ? contextType : givenResultType; @@ -1370,7 +1367,8 @@ bool swift::omitNeedlessWords(StringRef &baseName, return lowercaseAcronymsForReturn(); } -llvm::Optional swift::stripWithCompletionHandlerSuffix(StringRef name) { +llvm::Optional +swift::stripWithCompletionHandlerSuffix(StringRef name) { if (name.endswith("WithCompletionHandler")) { return name.drop_back(strlen("WithCompletionHandler")); } diff --git a/lib/Basic/UUID.cpp b/lib/Basic/UUID.cpp index 2a762e298e3..0acb5cc6b2d 100644 --- a/lib/Basic/UUID.cpp +++ b/lib/Basic/UUID.cpp @@ -16,9 +16,9 @@ //===----------------------------------------------------------------------===// #include "swift/Basic/UUID.h" +#include "llvm/ADT/None.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" -#include "llvm/ADT/None.h" // WIN32 doesn't natively support . Instead, we use Win32 APIs. #if defined(_WIN32) diff --git a/lib/Basic/Version.cpp b/lib/Basic/Version.cpp index af83c44003d..6820d019486 100644 --- a/lib/Basic/Version.cpp +++ b/lib/Basic/Version.cpp @@ -14,13 +14,13 @@ // //===----------------------------------------------------------------------===// +#include "swift/Basic/Version.h" +#include "swift/Basic/LLVM.h" #include "clang/Basic/CharInfo.h" -#include "llvm/Support/raw_ostream.h" +#include "llvm/ADT/None.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" -#include "llvm/ADT/None.h" -#include "swift/Basic/LLVM.h" -#include "swift/Basic/Version.h" +#include "llvm/Support/raw_ostream.h" #include diff --git a/lib/ClangImporter/ClangAdapter.cpp b/lib/ClangImporter/ClangAdapter.cpp index 9418f24521d..86f423ef7fb 100644 --- a/lib/ClangImporter/ClangAdapter.cpp +++ b/lib/ClangImporter/ClangAdapter.cpp @@ -274,7 +274,8 @@ OmissionTypeName importer::getClangTypeNameForOmission(clang::ASTContext &ctx, return OmissionTypeName(className, llvm::None, "Object"); return OmissionTypeName( - className, llvm::None, getClangTypeNameForOmission(ctx, typeArgs[0]).Name); + className, llvm::None, + getClangTypeNameForOmission(ctx, typeArgs[0]).Name); } // Objective-C "id" type. diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp index 5332dd3c6a5..90522a42acf 100644 --- a/lib/ClangImporter/ClangImporter.cpp +++ b/lib/ClangImporter/ClangImporter.cpp @@ -105,16 +105,12 @@ namespace { const_cast(imported)); } - void InclusionDirective(clang::SourceLocation HashLoc, - const clang::Token &IncludeTok, - StringRef FileName, - bool IsAngled, - clang::CharSourceRange FilenameRange, - llvm::Optional File, - StringRef SearchPath, - StringRef RelativePath, - const clang::Module *Imported, - clang::SrcMgr::CharacteristicKind FileType) override { + void InclusionDirective( + clang::SourceLocation HashLoc, const clang::Token &IncludeTok, + StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, + llvm::Optional File, StringRef SearchPath, + StringRef RelativePath, const clang::Module *Imported, + clang::SrcMgr::CharacteristicKind FileType) override { handleImport(Imported); } @@ -285,15 +281,12 @@ private: } void InclusionDirective(clang::SourceLocation HashLoc, - const clang::Token &IncludeTok, - StringRef FileName, - bool IsAngled, - clang::CharSourceRange FilenameRange, + const clang::Token &IncludeTok, StringRef FileName, + bool IsAngled, clang::CharSourceRange FilenameRange, llvm::Optional File, - StringRef SearchPath, - StringRef RelativePath, + StringRef SearchPath, StringRef RelativePath, const clang::Module *Imported, - clang::SrcMgr::CharacteristicKind FileType) override{ + clang::SrcMgr::CharacteristicKind FileType) override { if (!Imported) { if (File) Impl.BridgeHeaderFiles.insert(*File); diff --git a/lib/ClangImporter/ClangIncludePaths.h b/lib/ClangImporter/ClangIncludePaths.h index 71d214c9b24..5be426d9825 100644 --- a/lib/ClangImporter/ClangIncludePaths.h +++ b/lib/ClangImporter/ClangIncludePaths.h @@ -17,8 +17,8 @@ namespace swift { -llvm::Optional> getCxxShimModuleMapPath(SearchPathOptions &opts, - const llvm::Triple &triple); +llvm::Optional> +getCxxShimModuleMapPath(SearchPathOptions &opts, const llvm::Triple &triple); } // namespace swift diff --git a/lib/ClangImporter/ClangModuleDependencyScanner.cpp b/lib/ClangImporter/ClangModuleDependencyScanner.cpp index 00b8fe603bd..cea3f120bdd 100644 --- a/lib/ClangImporter/ClangModuleDependencyScanner.cpp +++ b/lib/ClangImporter/ClangModuleDependencyScanner.cpp @@ -79,8 +79,7 @@ static void addSearchPathInvocationArguments( /// Create the command line for Clang dependency scanning. static std::vector getClangDepScanningInvocationArguments( - ASTContext &ctx, - llvm::Optional sourceFileName = llvm::None) { + ASTContext &ctx, llvm::Optional sourceFileName = llvm::None) { std::vector commandLineArgs = ClangImporter::getClangArguments(ctx); addSearchPathInvocationArguments(commandLineArgs, ctx); @@ -400,9 +399,11 @@ computeClangWorkingDirectory(const std::vector &commandLineArgs, return workingDir; } -llvm::Optional ClangImporter::getModuleDependencies( - StringRef moduleName, ModuleDependenciesCache &cache, - InterfaceSubContextDelegate &delegate, bool isTestableImport) { +llvm::Optional +ClangImporter::getModuleDependencies(StringRef moduleName, + ModuleDependenciesCache &cache, + InterfaceSubContextDelegate &delegate, + bool isTestableImport) { auto &ctx = Impl.SwiftContext; // Determine the command-line arguments for dependency scanning. std::vector commandLineArgs = diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp index 066706cc0fa..61a8dbf3cae 100644 --- a/lib/ClangImporter/ImportDecl.cpp +++ b/lib/ClangImporter/ImportDecl.cpp @@ -96,14 +96,12 @@ static bool isInSystemModule(const DeclContext *D) { return cast(D->getModuleScopeContext())->isSystemModule(); } -static FuncDecl *createFuncOrAccessor(ClangImporter::Implementation &impl, - SourceLoc funcLoc, - llvm::Optional accessorInfo, - DeclName name, SourceLoc nameLoc, - GenericParamList *genericParams, - ParameterList *bodyParams, Type resultTy, - bool async, bool throws, DeclContext *dc, - ClangNode clangNode) { +static FuncDecl * +createFuncOrAccessor(ClangImporter::Implementation &impl, SourceLoc funcLoc, + llvm::Optional accessorInfo, DeclName name, + SourceLoc nameLoc, GenericParamList *genericParams, + ParameterList *bodyParams, Type resultTy, bool async, + bool throws, DeclContext *dc, ClangNode clangNode) { FuncDecl *decl; if (accessorInfo) { decl = AccessorDecl::create( @@ -1571,8 +1569,8 @@ namespace { return nullptr; auto Loc = Impl.importSourceLoc(decl->getLocation()); - auto structDecl = Impl.createDeclWithClangNode(decl, - AccessLevel::Public, Loc, name, Loc, llvm::None, nullptr, dc); + auto structDecl = Impl.createDeclWithClangNode( + decl, AccessLevel::Public, Loc, name, Loc, llvm::None, nullptr, dc); auto options = getDefaultMakeStructRawValuedOptions(); options |= MakeStructRawValuedFlags::MakeUnlabeledValueInit; @@ -1620,7 +1618,8 @@ namespace { (errorCodeProto = C.getProtocol(KnownProtocolKind::ErrorCodeProtocol))) { // Create the wrapper struct. - errorWrapper = new (C) StructDecl(loc, name, loc, llvm::None, nullptr, dc); + errorWrapper = + new (C) StructDecl(loc, name, loc, llvm::None, nullptr, dc); errorWrapper->setAccess(AccessLevel::Public); errorWrapper->getAttrs().add( new (Impl.SwiftContext) FrozenAttr(/*IsImplicit*/true)); @@ -1688,7 +1687,8 @@ namespace { // Create the enumeration. auto enumDecl = Impl.createDeclWithClangNode( decl, AccessLevel::Public, loc, enumName, - Impl.importSourceLoc(decl->getLocation()), llvm::None, nullptr, enumDC); + Impl.importSourceLoc(decl->getLocation()), llvm::None, nullptr, + enumDC); enumDecl->setHasFixedRawValues(); // Annotate as 'frozen' if appropriate. @@ -3077,11 +3077,12 @@ namespace { return result; } - ParameterList *getNonSelfParamList( - DeclContext *dc, const clang::FunctionDecl *decl, - llvm::Optional selfIdx, ArrayRef argNames, - bool allowNSUIntegerAsInt, bool isAccessor, - ArrayRef genericParams) { + ParameterList * + getNonSelfParamList(DeclContext *dc, const clang::FunctionDecl *decl, + llvm::Optional selfIdx, + ArrayRef argNames, + bool allowNSUIntegerAsInt, bool isAccessor, + ArrayRef genericParams) { if (bool(selfIdx)) { assert(((decl->getNumParams() == argNames.size() + 1) || isAccessor) && (*selfIdx < decl->getNumParams()) && "where's self?"); @@ -3102,10 +3103,10 @@ namespace { argNames, genericParams, /*resultType=*/nullptr); } - Decl *importGlobalAsInitializer(const clang::FunctionDecl *decl, - DeclName name, DeclContext *dc, - CtorInitializerKind initKind, - llvm::Optional correctSwiftName); + Decl * + importGlobalAsInitializer(const clang::FunctionDecl *decl, DeclName name, + DeclContext *dc, CtorInitializerKind initKind, + llvm::Optional correctSwiftName); /// Create an implicit property given the imported name of one of /// the accessors. @@ -3182,7 +3183,8 @@ namespace { return property->getParsedAccessor(AccessorKind::Set); } - return importFunctionDecl(decl, importedName, correctSwiftName, llvm::None); + return importFunctionDecl(decl, importedName, correctSwiftName, + llvm::None); } Decl *importFunctionDecl( @@ -3832,7 +3834,8 @@ namespace { Impl.SwiftContext, loc, genericParams, loc); auto structDecl = Impl.createDeclWithClangNode( - decl, AccessLevel::Public, loc, name, loc, llvm::None, genericParamList, dc); + decl, AccessLevel::Public, loc, name, loc, llvm::None, + genericParamList, dc); auto attr = AvailableAttr::createPlatformAgnostic( Impl.SwiftContext, "Un-specialized class templates are not currently " @@ -4012,14 +4015,15 @@ namespace { } Decl *importObjCMethodDecl(const clang::ObjCMethodDecl *decl, - DeclContext *dc, - llvm::Optional accessorInfo) { + DeclContext *dc, + llvm::Optional accessorInfo) { return importObjCMethodDecl(decl, dc, false, accessorInfo); } private: - static bool isAcceptableResultOrNull(Decl *fn, - llvm::Optional accessorInfo) { + static bool + isAcceptableResultOrNull(Decl *fn, + llvm::Optional accessorInfo) { if (nullptr == fn) return true; @@ -4107,9 +4111,8 @@ namespace { } Decl *importObjCMethodDecl(const clang::ObjCMethodDecl *decl, - DeclContext *dc, - bool forceClassMethod, - llvm::Optional accessorInfo) { + DeclContext *dc, bool forceClassMethod, + llvm::Optional accessorInfo) { // If we have an init method, import it as an initializer. if (isInitMethod(decl)) { // Cannot import initializers as accessors. @@ -4192,12 +4195,11 @@ namespace { return result; } - Decl *importNonInitObjCMethodDecl(const clang::ObjCMethodDecl *decl, - DeclContext *dc, - ImportedName importedName, - ObjCSelector selector, - bool forceClassMethod, - llvm::Optional accessorInfo) { + Decl * + importNonInitObjCMethodDecl(const clang::ObjCMethodDecl *decl, + DeclContext *dc, ImportedName importedName, + ObjCSelector selector, bool forceClassMethod, + llvm::Optional accessorInfo) { assert(dc->isTypeContext() && "Method in non-type context?"); assert(isa(dc->getModuleScopeContext()) && "Clang method in Swift context?"); @@ -4392,8 +4394,8 @@ namespace { // method, do so and mark the result as an alternate // declaration. if (auto imported = importObjCMethodDecl(decl, dc, - /*forceClassMethod=*/true, - /*accessor*/llvm::None)) + /*forceClassMethod=*/true, + /*accessor*/ llvm::None)) Impl.addAlternateDecl(result, cast(imported)); } } @@ -4415,8 +4417,7 @@ namespace { /// NSArray(capacity: 1024) /// \endcode ConstructorDecl *importConstructor(const clang::ObjCMethodDecl *objcMethod, - const DeclContext *dc, - bool implicit, + const DeclContext *dc, bool implicit, llvm::Optional kind, bool required); @@ -4788,7 +4789,7 @@ namespace { auto result = Impl.createDeclWithClangNode( decl, AccessLevel::Public, Impl.getClangModuleForDecl(decl->getCanonicalDecl(), - /*allowForwardDeclaration=*/true), + /*allowForwardDeclaration=*/true), Impl.importSourceLoc(decl->getBeginLoc()), Impl.importSourceLoc(decl->getLocation()), name, ArrayRef(), llvm::None, @@ -4872,12 +4873,10 @@ namespace { /*allowForwardDeclaration=*/true); } - auto result = Impl.createDeclWithClangNode(decl, - AccessLevel::Public, - SourceLoc(), name, - SourceLoc(), llvm::None, - nullptr, dc, - /*isActor*/false); + auto result = Impl.createDeclWithClangNode( + decl, AccessLevel::Public, SourceLoc(), name, SourceLoc(), + llvm::None, nullptr, dc, + /*isActor*/ false); if (cacheResult) Impl.ImportedDecls[{decl->getCanonicalDecl(), getVersion()}] = result; @@ -4990,7 +4989,7 @@ namespace { auto result = Impl.createDeclWithClangNode( decl, access, Impl.importSourceLoc(decl->getBeginLoc()), name, Impl.importSourceLoc(decl->getLocation()), llvm::None, nullptr, dc, - /*isActor*/false); + /*isActor*/ false); // Import generic arguments, if any. if (auto gpImportResult = importObjCGenericParams(decl, dc)) { @@ -5447,8 +5446,8 @@ SwiftDeclConverter::importCFClassType(const clang::TypedefNameDecl *decl, // TODO: try to find a non-mutable type to use as the superclass. auto theClass = Impl.createDeclWithClangNode( - decl, AccessLevel::Public, SourceLoc(), className, SourceLoc(), llvm::None, - nullptr, dc, /*isActor*/false); + decl, AccessLevel::Public, SourceLoc(), className, SourceLoc(), + llvm::None, nullptr, dc, /*isActor*/ false); theClass->setSuperclass(superclass); theClass->setAddedImplicitInitializers(); // suppress all initializers theClass->setHasMissingVTableEntries(false); @@ -5920,9 +5919,7 @@ SwiftDeclConverter::importAsOptionSetType(DeclContext *dc, Identifier name, } Decl *SwiftDeclConverter::importGlobalAsInitializer( - const clang::FunctionDecl *decl, - DeclName name, - DeclContext *dc, + const clang::FunctionDecl *decl, DeclName name, DeclContext *dc, CtorInitializerKind initKind, llvm::Optional correctSwiftName) { // TODO: Should this be an error? How can this come up? @@ -5998,7 +5995,6 @@ Decl *SwiftDeclConverter::importGlobalAsInitializer( return result; } - /// Create an implicit property given the imported name of one of /// the accessors. VarDecl * @@ -6215,8 +6211,8 @@ SwiftDeclConverter::getImplicitProperty(ImportedName importedName, } ConstructorDecl *SwiftDeclConverter::importConstructor( - const clang::ObjCMethodDecl *objcMethod, const DeclContext *dc, bool implicit, - llvm::Optional kind, bool required) { + const clang::ObjCMethodDecl *objcMethod, const DeclContext *dc, + bool implicit, llvm::Optional kind, bool required) { // Only methods in the 'init' family can become constructors. assert(isInitMethod(objcMethod) && "Not a real init method"); @@ -7535,8 +7531,7 @@ void SwiftDeclConverter::importInheritedConstructors( } llvm::Optional ClangImporter::Implementation::importDeclCached( - const clang::NamedDecl *ClangDecl, - ImportNameVersion version, + const clang::NamedDecl *ClangDecl, ImportNameVersion version, bool UseCanonical) { auto Known = ImportedDecls.find( { UseCanonical? ClangDecl->getCanonicalDecl(): ClangDecl, version }); @@ -7668,8 +7663,8 @@ SourceFile &ClangImporter::Implementation::getClangSwiftAttrSourceFile( if (known != ClangSwiftAttrSourceFiles.end()) return *known->second; - auto sourceFile = new (SwiftContext) SourceFile( - module, SourceFileKind::Library, llvm::None); + auto sourceFile = new (SwiftContext) + SourceFile(module, SourceFileKind::Library, llvm::None); ClangSwiftAttrSourceFiles.insert({&module, sourceFile}); return *sourceFile; } @@ -7984,22 +7979,22 @@ void ClangImporter::Implementation::importAttributes( continue; auto platformK = - llvm::StringSwitch>(Platform) - .Case("ios", PlatformKind::iOS) - .Case("macos", PlatformKind::macOS) - .Case("maccatalyst", PlatformKind::macCatalyst) - .Case("tvos", PlatformKind::tvOS) - .Case("watchos", PlatformKind::watchOS) - .Case("ios_app_extension", PlatformKind::iOSApplicationExtension) - .Case("maccatalyst_app_extension", - PlatformKind::macCatalystApplicationExtension) - .Case("macos_app_extension", - PlatformKind::macOSApplicationExtension) - .Case("tvos_app_extension", - PlatformKind::tvOSApplicationExtension) - .Case("watchos_app_extension", - PlatformKind::watchOSApplicationExtension) - .Default(llvm::None); + llvm::StringSwitch>(Platform) + .Case("ios", PlatformKind::iOS) + .Case("macos", PlatformKind::macOS) + .Case("maccatalyst", PlatformKind::macCatalyst) + .Case("tvos", PlatformKind::tvOS) + .Case("watchos", PlatformKind::watchOS) + .Case("ios_app_extension", PlatformKind::iOSApplicationExtension) + .Case("maccatalyst_app_extension", + PlatformKind::macCatalystApplicationExtension) + .Case("macos_app_extension", + PlatformKind::macOSApplicationExtension) + .Case("tvos_app_extension", + PlatformKind::tvOSApplicationExtension) + .Case("watchos_app_extension", + PlatformKind::watchOSApplicationExtension) + .Default(llvm::None); if (!platformK) continue; @@ -8492,7 +8487,8 @@ ClangImporter::Implementation::importMirroredDecl(const clang::NamedDecl *decl, SwiftDeclConverter converter(*this, version); Decl *result; if (auto method = dyn_cast(decl)) { - result = converter.importObjCMethodDecl(method, dc, /*accessor*/llvm::None); + result = + converter.importObjCMethodDecl(method, dc, /*accessor*/ llvm::None); } else if (auto prop = dyn_cast(decl)) { result = converter.importObjCPropertyDecl(prop, dc); } else { @@ -9181,7 +9177,8 @@ void ClangImporter::Implementation::loadAllConformances( } llvm::Optional -ClangImporter::Implementation::getSpecialTypedefKind(clang::TypedefNameDecl *decl) { +ClangImporter::Implementation::getSpecialTypedefKind( + clang::TypedefNameDecl *decl) { auto iter = SpecialTypedefNames.find(decl->getCanonicalDecl()); if (iter == SpecialTypedefNames.end()) return llvm::None; diff --git a/lib/ClangImporter/ImportMacro.cpp b/lib/ClangImporter/ImportMacro.cpp index 11c9c6b4652..48adaadebcd 100644 --- a/lib/ClangImporter/ImportMacro.cpp +++ b/lib/ClangImporter/ImportMacro.cpp @@ -52,8 +52,8 @@ static bool isInSystemModule(DeclContext *D) { return cast(D->getModuleScopeContext())->isSystemModule(); } -static llvm::Optional getTokenSpelling(ClangImporter::Implementation &impl, - const clang::Token &tok) { +static llvm::Optional +getTokenSpelling(ClangImporter::Implementation &impl, const clang::Token &tok) { bool tokenInvalid = false; llvm::SmallString<32> spellingBuffer; StringRef tokenSpelling = impl.getClangPreprocessor().getSpelling( @@ -271,8 +271,8 @@ static bool isSignToken(const clang::Token &tok) { tok.is(clang::tok::tilde); } -static llvm::Optional builtinTypeForToken(const clang::Token &tok, - const clang::ASTContext &context) { +static llvm::Optional +builtinTypeForToken(const clang::Token &tok, const clang::ASTContext &context) { switch (tok.getKind()) { case clang::tok::kw_short: return clang::QualType(context.ShortTy); @@ -310,10 +310,9 @@ static llvm::Optional builtinTypeForToken(const clang::Token &t } static llvm::Optional> - getIntegerConstantForMacroToken(ClangImporter::Implementation &impl, - const clang::MacroInfo *macro, - DeclContext *DC, - const clang::Token &token) { +getIntegerConstantForMacroToken(ClangImporter::Implementation &impl, + const clang::MacroInfo *macro, DeclContext *DC, + const clang::Token &token) { // Integer literal. if (token.is(clang::tok::numeric_constant)) { diff --git a/lib/ClangImporter/ImportName.cpp b/lib/ClangImporter/ImportName.cpp index 6d93235ddd4..5fabf481b94 100644 --- a/lib/ClangImporter/ImportName.cpp +++ b/lib/ClangImporter/ImportName.cpp @@ -472,11 +472,13 @@ StringRef importer::stripNotification(StringRef name) { static llvm::Optional matchFactoryAsInitName(const clang::ObjCMethodDecl *method) { // Only class methods can be mapped to initializers in this way. - if (!method->isClassMethod()) return llvm::None; + if (!method->isClassMethod()) + return llvm::None; // Said class methods must be in an actual class. auto objcClass = method->getClassInterface(); - if (!objcClass) return llvm::None; + if (!objcClass) + return llvm::None; // See if we can match the class name to the beginning of the first // selector piece. @@ -511,7 +513,8 @@ determineFactoryInitializerKind(const clang::ObjCMethodDecl *method) { if (auto objcPtr = method->getReturnType() ->getAs()) { auto objcClass = method->getClassInterface(); - if (!objcClass) return llvm::None; + if (!objcClass) + return llvm::None; if (objcPtr->getInterfaceDecl() != objcClass) { // FIXME: Could allow a subclass here, but the rest of the compiler @@ -600,7 +603,8 @@ checkVersionedSwiftName(VersionedSwiftNameInfo info, static llvm::Optional findSwiftNameAttr(const clang::Decl *decl, ImportNameVersion version) { #ifndef NDEBUG - if (llvm::Optional def = getDefinitionForClangTypeDecl(decl)) { + if (llvm::Optional def = + getDefinitionForClangTypeDecl(decl)) { assert((*def == nullptr || *def == decl) && "swift_name should only appear on the definition"); } @@ -715,11 +719,13 @@ findSwiftNameAttr(const clang::Decl *decl, ImportNameVersion version) { // The remainder of this function emulates the limited form of swift_name // supported in Swift 2. auto attr = decl->getAttr(); - if (!attr) return llvm::None; + if (!attr) + return llvm::None; // API notes produce attributes with no source location; ignore them because // they weren't used for naming in Swift 2. - if (attr->getLocation().isInvalid()) return llvm::None; + if (attr->getLocation().isInvalid()) + return llvm::None; // Hardcode certain kinds of explicitly-written Swift names that were // permitted and used in Swift 2. All others are ignored, so that we are @@ -768,8 +774,8 @@ getFactoryAsInit(const clang::ObjCInterfaceDecl *classDecl, return FactoryAsInitKind::Infer; } -llvm::Optional determineCtorInitializerKind( - const clang::ObjCMethodDecl *method) { +llvm::Optional +determineCtorInitializerKind(const clang::ObjCMethodDecl *method) { const clang::ObjCInterfaceDecl *interface = method->getClassInterface(); if (isInitMethod(method)) { @@ -845,9 +851,10 @@ static bool omitNeedlessWordsInFunctionName( StringRef &baseName, SmallVectorImpl &argumentNames, ArrayRef params, clang::QualType resultType, const clang::DeclContext *dc, const SmallBitVector &nonNullArgs, - llvm::Optional errorParamIndex, bool returnsSelf, bool isInstanceMethod, - llvm::Optional completionHandlerIndex, - llvm::Optional completionHandlerName, NameImporter &nameImporter) { + llvm::Optional errorParamIndex, bool returnsSelf, + bool isInstanceMethod, llvm::Optional completionHandlerIndex, + llvm::Optional completionHandlerName, + NameImporter &nameImporter) { clang::ASTContext &clangCtx = nameImporter.getClangContext(); // Collect the parameter type names. @@ -1106,11 +1113,12 @@ static bool shouldBeSwiftPrivate(NameImporter &nameImporter, return false; } -llvm::Optional NameImporter::considerErrorImport( - const clang::ObjCMethodDecl *clangDecl, StringRef &baseName, - SmallVectorImpl ¶mNames, - ArrayRef params, bool isInitializer, - bool hasCustomName) { +llvm::Optional +NameImporter::considerErrorImport(const clang::ObjCMethodDecl *clangDecl, + StringRef &baseName, + SmallVectorImpl ¶mNames, + ArrayRef params, + bool isInitializer, bool hasCustomName) { // If the declaration name isn't parallel to the actual parameter // list (e.g. if the method has C-style parameter declarations), // don't try to apply error conventions. @@ -1132,7 +1140,8 @@ llvm::Optional NameImporter::considerErrorImport( auto errorKind = classifyMethodErrorHandling(clangDecl, getResultOptionality(clangDecl)); - if (!errorKind) return llvm::None; + if (!errorKind) + return llvm::None; // Consider adjusting the imported declaration name to remove the // parameter. @@ -1175,9 +1184,9 @@ llvm::Optional NameImporter::considerErrorImport( if (index == 0 && suffixToStrip.empty()) { return llvm::None; - // If there was a conflict stripping an error suffix, adjust the - // name but don't change the base name. This avoids creating a - // spurious _: () argument. + // If there was a conflict stripping an error suffix, adjust the + // name but don't change the base name. This avoids creating a + // spurious _: () argument. } else if (index == 0 && !suffixToStrip.empty()) { suffixToStrip = {}; baseName = origBaseName; @@ -1241,13 +1250,10 @@ static bool isNullableNSErrorType( return true; } -llvm::Optional -NameImporter::considerAsyncImport( - const clang::ObjCMethodDecl *clangDecl, - StringRef baseName, +llvm::Optional NameImporter::considerAsyncImport( + const clang::ObjCMethodDecl *clangDecl, StringRef baseName, SmallVectorImpl ¶mNames, - ArrayRef params, - bool isInitializer, + ArrayRef params, bool isInitializer, llvm::Optional explicitCompletionHandlerParamIndex, CustomAsyncName customName, llvm::Optional completionHandlerFlagParamIndex, @@ -1319,8 +1325,8 @@ NameImporter::considerAsyncImport( // Used for returns once we've determined that the method cannot be // imported as async, even though it has what looks like a completion handler // parameter. - auto notAsync = [&](const char *reason) -> - llvm::Optional { + auto notAsync = + [&](const char *reason) -> llvm::Optional { #ifdef ASYNC_IMPORT_DEBUG llvm::errs() << "*** failed async import: " << reason << "\n"; clangDecl->dump(llvm::errs()); @@ -2353,18 +2359,19 @@ ImportedName NameImporter::importNameImpl(const clang::NamedDecl *D, baseName, argumentNames, params, method->getReturnType(), method->getDeclContext(), getNonNullArgs(method, params), result.getErrorInfo() - ? llvm::Optional(result.getErrorInfo()->ErrorParameterIndex) + ? llvm::Optional( + result.getErrorInfo()->ErrorParameterIndex) : llvm::None, method->hasRelatedResultType(), method->isInstanceMethod(), result.getAsyncInfo().transform( - [](const ForeignAsyncConvention::Info &info) { - return info.completionHandlerParamIndex(); - }), + [](const ForeignAsyncConvention::Info &info) { + return info.completionHandlerParamIndex(); + }), result.getAsyncInfo().transform( - [&](const ForeignAsyncConvention::Info &info) { - return method->getDeclName().getObjCSelector().getNameForSlot( - info.completionHandlerParamIndex()); - }), + [&](const ForeignAsyncConvention::Info &info) { + return method->getDeclName().getObjCSelector().getNameForSlot( + info.completionHandlerParamIndex()); + }), *this); } diff --git a/lib/ClangImporter/ImportName.h b/lib/ClangImporter/ImportName.h index b5356046744..5a8a6e40bd4 100644 --- a/lib/ClangImporter/ImportName.h +++ b/lib/ClangImporter/ImportName.h @@ -485,17 +485,15 @@ private: ArrayRef params, bool isInitializer, bool hasCustomName); - llvm::Optional - considerAsyncImport(const clang::ObjCMethodDecl *clangDecl, - StringRef baseName, - SmallVectorImpl ¶mNames, - ArrayRef params, - bool isInitializer, - llvm::Optional explicitCompletionHandlerParamIndex, - CustomAsyncName customName, - llvm::Optional completionHandlerFlagParamIndex, - bool completionHandlerFlagIsZeroOnError, - llvm::Optional errorInfo); + llvm::Optional considerAsyncImport( + const clang::ObjCMethodDecl *clangDecl, StringRef baseName, + SmallVectorImpl ¶mNames, + ArrayRef params, bool isInitializer, + llvm::Optional explicitCompletionHandlerParamIndex, + CustomAsyncName customName, + llvm::Optional completionHandlerFlagParamIndex, + bool completionHandlerFlagIsZeroOnError, + llvm::Optional errorInfo); EffectiveClangContext determineEffectiveContext(const clang::NamedDecl *, const clang::DeclContext *, diff --git a/lib/ClangImporter/ImportType.cpp b/lib/ClangImporter/ImportType.cpp index caf4ccb03a8..07ab54390d5 100644 --- a/lib/ClangImporter/ImportType.cpp +++ b/lib/ClangImporter/ImportType.cpp @@ -210,16 +210,16 @@ namespace { llvm::Optional CompletionHandlerErrorParamIndex; public: - SwiftTypeConverter(ClangImporter::Implementation &impl, - llvm::function_ref addDiag, - bool allowNSUIntegerAsInt, - Bridgeability bridging, - const clang::FunctionType *completionHandlerType, - llvm::Optional completionHandlerErrorParamIndex) - : Impl(impl), addImportDiagnostic(addDiag), - AllowNSUIntegerAsInt(allowNSUIntegerAsInt), Bridging(bridging), - CompletionHandlerType(completionHandlerType), - CompletionHandlerErrorParamIndex(completionHandlerErrorParamIndex) {} + SwiftTypeConverter( + ClangImporter::Implementation &impl, + llvm::function_ref addDiag, + bool allowNSUIntegerAsInt, Bridgeability bridging, + const clang::FunctionType *completionHandlerType, + llvm::Optional completionHandlerErrorParamIndex) + : Impl(impl), addImportDiagnostic(addDiag), + AllowNSUIntegerAsInt(allowNSUIntegerAsInt), Bridging(bridging), + CompletionHandlerType(completionHandlerType), + CompletionHandlerErrorParamIndex(completionHandlerErrorParamIndex) {} using TypeVisitor::Visit; ImportResult Visit(clang::QualType type) { @@ -1633,9 +1633,8 @@ static ImportedType adjustTypeForConcreteImport( ImportedType ClangImporter::Implementation::importType( clang::QualType type, ImportTypeKind importKind, llvm::function_ref addImportDiagnosticFn, - bool allowNSUIntegerAsInt, Bridgeability bridging, - ImportTypeAttrs attrs, OptionalTypeKind optionality, - bool resugarNSErrorPointer, + bool allowNSUIntegerAsInt, Bridgeability bridging, ImportTypeAttrs attrs, + OptionalTypeKind optionality, bool resugarNSErrorPointer, llvm::Optional completionHandlerErrorParamIndex) { if (type.isNull()) return {Type(), false}; @@ -1856,15 +1855,16 @@ private: Result recurse(Type ty) { bool anyFound = false; - Type newTy = ty.transformRec([&](TypeBase *childTy) -> llvm::Optional { - // We want to visit the first level of children. - if (childTy == ty.getPointer()) - return llvm::None; + Type newTy = + ty.transformRec([&](TypeBase *childTy) -> llvm::Optional { + // We want to visit the first level of children. + if (childTy == ty.getPointer()) + return llvm::None; - auto result = this->visit(childTy); - anyFound |= result.second; - return result.first; - }); + auto result = this->visit(childTy); + anyFound |= result.second; + return result.first; + }); return { newTy, anyFound }; } @@ -2507,12 +2507,13 @@ ParameterList *ClangImporter::Implementation::importFunctionParameterList( ImportDiagnosticAdder paramAddDiag(*this, clangDecl, param->getLocation()); - auto swiftParamTyOpt = importParameterType( - param, optionalityOfParam, allowNSUIntegerAsInt, - /*isNSDictionarySubscriptGetter=*/false, - /*paramIsError=*/false, - /*paramIsCompletionHandler=*/false, - /*completionHandlerErrorParamIndex=*/llvm::None, genericParams, paramAddDiag); + auto swiftParamTyOpt = + importParameterType(param, optionalityOfParam, allowNSUIntegerAsInt, + /*isNSDictionarySubscriptGetter=*/false, + /*paramIsError=*/false, + /*paramIsCompletionHandler=*/false, + /*completionHandlerErrorParamIndex=*/llvm::None, + genericParams, paramAddDiag); if (!swiftParamTyOpt) { addImportDiagnostic(param, Diagnostic(diag::parameter_type_not_imported, param), @@ -3131,10 +3132,12 @@ ImportedType ClangImporter::Implementation::importMethodParamsAndReturnType( ImportTypeKind importKind = getImportTypeKindForParam(param); // Import the original completion handler type without adjustments. - Type origSwiftParamTy = importType( - paramTy, importKind, paramAddDiag, allowNSUIntegerAsIntInParam, - Bridgeability::Full, ImportTypeAttrs(), optionalityOfParam, - /*resugarNSErrorPointer=*/!paramIsError, llvm::None).getType(); + Type origSwiftParamTy = + importType(paramTy, importKind, paramAddDiag, + allowNSUIntegerAsIntInParam, Bridgeability::Full, + ImportTypeAttrs(), optionalityOfParam, + /*resugarNSErrorPointer=*/!paramIsError, llvm::None) + .getType(); completionHandlerType = mapGenericArgs(origDC, dc, origSwiftParamTy) ->getCanonicalType(); continue; diff --git a/lib/ClangImporter/ImporterImpl.h b/lib/ClangImporter/ImporterImpl.h index 1997c88f981..ab0cca4a929 100644 --- a/lib/ClangImporter/ImporterImpl.h +++ b/lib/ClangImporter/ImporterImpl.h @@ -1033,8 +1033,8 @@ public: /// If we already imported a given decl, return the corresponding Swift decl. /// Otherwise, return nullptr. llvm::Optional importDeclCached(const clang::NamedDecl *ClangDecl, - Version version, - bool UseCanonicalDecl = true); + Version version, + bool UseCanonicalDecl = true); Decl *importDeclImpl(const clang::NamedDecl *ClangDecl, Version version, bool &TypedefIsSuperfluous, bool &HadForwardDeclaration); @@ -1083,7 +1083,8 @@ public: const ClassDecl *classDecl, SmallVectorImpl &newMembers); void importMirroredProtocolMembers(const clang::ObjCContainerDecl *decl, - DeclContext *dc, llvm::Optional name, + DeclContext *dc, + llvm::Optional name, SmallVectorImpl &members); /// Utility function for building simple generic signatures. @@ -1298,14 +1299,14 @@ public: /// indicates if the Optional is implicitly unwrapped. If /// the type cannot be represented in Swift, then the type /// field will be null. - ImportedType - importType(clang::QualType type, ImportTypeKind kind, - llvm::function_ref addImportDiagnosticFn, - bool allowNSUIntegerAsInt, Bridgeability topLevelBridgeability, - ImportTypeAttrs attrs, - OptionalTypeKind optional = OTK_ImplicitlyUnwrappedOptional, - bool resugarNSErrorPointer = true, - llvm::Optional completionHandlerErrorParamIndex = llvm::None); + ImportedType importType( + clang::QualType type, ImportTypeKind kind, + llvm::function_ref addImportDiagnosticFn, + bool allowNSUIntegerAsInt, Bridgeability topLevelBridgeability, + ImportTypeAttrs attrs, + OptionalTypeKind optional = OTK_ImplicitlyUnwrappedOptional, + bool resugarNSErrorPointer = true, + llvm::Optional completionHandlerErrorParamIndex = llvm::None); /// Import the given Clang type into Swift. /// @@ -1477,17 +1478,14 @@ public: /// /// \returns the imported result type, or null if the type cannot be /// imported. - ImportedType - importMethodParamsAndReturnType(const DeclContext *dc, - const clang::ObjCMethodDecl *clangDecl, - ArrayRef params, - bool isVariadic, - bool isFromSystemModule, - ParameterList **bodyParams, - importer::ImportedName importedName, - llvm::Optional &asyncConv, - llvm::Optional &errorConv, - SpecialMethodKind kind); + ImportedType importMethodParamsAndReturnType( + const DeclContext *dc, const clang::ObjCMethodDecl *clangDecl, + ArrayRef params, bool isVariadic, + bool isFromSystemModule, ParameterList **bodyParams, + importer::ImportedName importedName, + llvm::Optional &asyncConv, + llvm::Optional &errorConv, + SpecialMethodKind kind); /// Import the type of an Objective-C method that will be imported as an /// accessor for \p property. @@ -1927,9 +1925,9 @@ static inline Type applyToFunctionType( return type; } -inline llvm::Optional findAnonymousEnumForTypedef( - const ASTContext &ctx, - const clang::TypedefType *typedefType) { +inline llvm::Optional +findAnonymousEnumForTypedef(const ASTContext &ctx, + const clang::TypedefType *typedefType) { auto *typedefDecl = typedefType->getDecl(); auto *lookupTable = ctx.getClangModuleLoader()->findLookupTable(typedefDecl->getOwningModule()); diff --git a/lib/ClangImporter/Serializability.cpp b/lib/ClangImporter/Serializability.cpp index b826eb6495a..5aab282bbfb 100644 --- a/lib/ClangImporter/Serializability.cpp +++ b/lib/ClangImporter/Serializability.cpp @@ -67,7 +67,7 @@ private: StableSerializationPath findImportedPath(const clang::NamedDecl *decl) { // We've almost certainly imported this declaration, look for it. llvm::Optional swiftDeclOpt = - Impl.importDeclCached(decl, Impl.CurrentVersion); + Impl.importDeclCached(decl, Impl.CurrentVersion); if (swiftDeclOpt.has_value() && swiftDeclOpt.value()) { auto swiftDecl = swiftDeclOpt.value(); // The serialization code doesn't allow us to cross-reference diff --git a/lib/ClangImporter/SwiftLookupTable.cpp b/lib/ClangImporter/SwiftLookupTable.cpp index bd0850d8185..c19dccc69ee 100644 --- a/lib/ClangImporter/SwiftLookupTable.cpp +++ b/lib/ClangImporter/SwiftLookupTable.cpp @@ -684,13 +684,15 @@ SwiftLookupTable::allGlobalsAsMembersInContext(StoredContext context) { } SmallVector -SwiftLookupTable::lookupGlobalsAsMembers(SerializedSwiftName baseName, - llvm::Optional searchContext) { +SwiftLookupTable::lookupGlobalsAsMembers( + SerializedSwiftName baseName, + llvm::Optional searchContext) { // Propagate the null search context. if (!searchContext) return lookupGlobalsAsMembersImpl(baseName, llvm::None); - llvm::Optional storedContext = translateContext(*searchContext); + llvm::Optional storedContext = + translateContext(*searchContext); if (!storedContext) return { }; return lookupGlobalsAsMembersImpl(baseName, *storedContext); diff --git a/lib/Demangling/ManglingUtils.cpp b/lib/Demangling/ManglingUtils.cpp index 44a877a2b44..1dd2937c3fd 100644 --- a/lib/Demangling/ManglingUtils.cpp +++ b/lib/Demangling/ManglingUtils.cpp @@ -11,8 +11,8 @@ //===----------------------------------------------------------------------===// #include "swift/Demangling/ManglingUtils.h" -#include "llvm/ADT/Optional.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" using namespace swift; using namespace Mangle; diff --git a/lib/Demangling/OldDemangler.cpp b/lib/Demangling/OldDemangler.cpp index e8866817d67..2ec4c333f12 100644 --- a/lib/Demangling/OldDemangler.cpp +++ b/lib/Demangling/OldDemangler.cpp @@ -18,14 +18,14 @@ #include "swift/Demangling/Demangler.h" #include "swift/Demangling/ManglingMacros.h" #include "swift/Demangling/ManglingUtils.h" -#include "swift/Strings.h" #include "swift/Demangling/Punycode.h" -#include "llvm/ADT/Optional.h" +#include "swift/Strings.h" #include "llvm/ADT/None.h" -#include -#include +#include "llvm/ADT/Optional.h" #include #include +#include +#include using namespace swift; using namespace Demangle; diff --git a/lib/DependencyScan/ModuleDependencyCacheSerialization.cpp b/lib/DependencyScan/ModuleDependencyCacheSerialization.cpp index c1e6ffb3b78..554d9adccdf 100644 --- a/lib/DependencyScan/ModuleDependencyCacheSerialization.cpp +++ b/lib/DependencyScan/ModuleDependencyCacheSerialization.cpp @@ -894,9 +894,9 @@ void ModuleDependenciesCacheSerializer::writeArraysOfIdentifiers() { } } -void ModuleDependenciesCacheSerializer::writeModuleInfo(ModuleDependencyID moduleID, - llvm::Optional contextHash, - const ModuleDependencyInfo &dependencyInfo) { +void ModuleDependenciesCacheSerializer::writeModuleInfo( + ModuleDependencyID moduleID, llvm::Optional contextHash, + const ModuleDependencyInfo &dependencyInfo) { using namespace graph_block; auto contextHashStrID = contextHash.has_value() ? getIdentifier(contextHash.value()) : 0; diff --git a/lib/DependencyScan/ScanDependencies.cpp b/lib/DependencyScan/ScanDependencies.cpp index 34db18b3528..b10180b8f54 100644 --- a/lib/DependencyScan/ScanDependencies.cpp +++ b/lib/DependencyScan/ScanDependencies.cpp @@ -2089,7 +2089,7 @@ swift::dependencies::performBatchModuleScan( FEOpts.SerializeModuleInterfaceDependencyHashes, FEOpts.shouldTrackSystemDependencies(), RequireOSSAModules_t(instance.getSILOptions())); - llvm::Optional rootDeps; + llvm::Optional rootDeps; if (isClang) { // Loading the clang module using Clang importer. // This action will populate the cache with the main module's @@ -2157,7 +2157,7 @@ swift::dependencies::performBatchModulePrescan( FEOpts.SerializeModuleInterfaceDependencyHashes, FEOpts.shouldTrackSystemDependencies(), RequireOSSAModules_t(instance.getSILOptions())); - llvm::Optional rootDeps; + llvm::Optional rootDeps; if (isClang) { // Loading the clang module using Clang importer. // This action will populate the cache with the main module's diff --git a/lib/Driver/Compilation.cpp b/lib/Driver/Compilation.cpp index ed5f9fdcb2c..cd6ac304f12 100644 --- a/lib/Driver/Compilation.cpp +++ b/lib/Driver/Compilation.cpp @@ -795,7 +795,8 @@ namespace driver { TaskFinishedResponse taskSignalled(ProcessId Pid, StringRef ErrorMsg, StringRef Output, StringRef Errors, - void *Context, llvm::Optional Signal, + void *Context, + llvm::Optional Signal, TaskProcessInformation ProcInfo) { const Job *SignalledCmd = (const Job *)Context; diff --git a/lib/Driver/CompilationRecord.h b/lib/Driver/CompilationRecord.h index d955d7e4614..364151340ac 100644 --- a/lib/Driver/CompilationRecord.h +++ b/lib/Driver/CompilationRecord.h @@ -78,10 +78,10 @@ inline static llvm::Optional getInfoStatusForIdentifier(StringRef Identifier) { using InputStatus = CompileJobAction::InputInfo::Status; return llvm::StringSwitch>(Identifier) - .Case("", InputStatus::UpToDate) - .Case("!dirty", InputStatus::NeedsCascadingBuild) - .Case("!private", InputStatus::NeedsNonCascadingBuild) - .Default(llvm::None); + .Case("", InputStatus::UpToDate) + .Case("!dirty", InputStatus::NeedsCascadingBuild) + .Case("!private", InputStatus::NeedsNonCascadingBuild) + .Default(llvm::None); } } // end namespace compilation_record diff --git a/lib/Driver/DarwinToolChains.cpp b/lib/Driver/DarwinToolChains.cpp index 21506e0c589..476ec734d9a 100644 --- a/lib/Driver/DarwinToolChains.cpp +++ b/lib/Driver/DarwinToolChains.cpp @@ -339,7 +339,7 @@ toolchains::Darwin::addArgsToLinkStdlib(ArgStringList &Arguments, SmallString<128> SharedResourceDirPath; getResourceDirPath(SharedResourceDirPath, context.Args, /*Shared=*/true); llvm::Optional runtimeCompatibilityVersion; - + if (context.Args.hasArg(options::OPT_runtime_compatibility_version)) { auto value = context.Args.getLastArgValue( options::OPT_runtime_compatibility_version); diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp index 85a0a3239a9..04f9684eb85 100644 --- a/lib/Driver/Driver.cpp +++ b/lib/Driver/Driver.cpp @@ -787,9 +787,7 @@ getDriverBatchSeed(llvm::opt::InputArgList &ArgList, } static llvm::Optional -getDriverBatchCount(llvm::opt::InputArgList &ArgList, - DiagnosticEngine &Diags) -{ +getDriverBatchCount(llvm::opt::InputArgList &ArgList, DiagnosticEngine &Diags) { if (const Arg *A = ArgList.getLastArg(options::OPT_driver_batch_count)) { unsigned Count = 0; if (StringRef(A->getValue()).getAsInteger(10, Count)) { @@ -887,8 +885,7 @@ computeContinueBuildingAfterErrors(const bool BatchMode, static llvm::Optional getDriverBatchSizeLimit(llvm::opt::InputArgList &ArgList, - DiagnosticEngine &Diags) -{ + DiagnosticEngine &Diags) { if (const Arg *A = ArgList.getLastArg(options::OPT_driver_batch_size_limit)) { unsigned Limit = 0; if (StringRef(A->getValue()).getAsInteger(10, Limit)) { @@ -960,8 +957,8 @@ Driver::buildCompilation(const ToolChain &TC, // REPL mode expects no input files, so suppress the error. SuppressNoInputFilesError = true; - llvm::Optional OFM = buildOutputFileMap( - *TranslatedArgList, workingDirectory); + llvm::Optional OFM = + buildOutputFileMap(*TranslatedArgList, workingDirectory); if (Diags.hadAnyError() && !AllowErrors) return nullptr; @@ -1038,7 +1035,7 @@ Driver::buildCompilation(const ToolChain &TC, const llvm::Optional DriverBatchCount = getDriverBatchCount(*ArgList, Diags); const llvm::Optional DriverBatchSizeLimit = - getDriverBatchSizeLimit(*ArgList, Diags); + getDriverBatchSizeLimit(*ArgList, Diags); const bool SaveTemps = ArgList->hasArg(options::OPT_save_temps); const bool ShowDriverTimeCompilation = ArgList->hasArg(options::OPT_driver_time_compilation); @@ -1842,7 +1839,8 @@ void Driver::buildOutputInfo(const ToolChain &TC, const DerivedArgList &Args, if (TC.getTriple().isOSWindows()) { if (const Arg *A = Args.getLastArg(options::OPT_libc)) { OI.RuntimeVariant = - llvm::StringSwitch>(A->getValue()) + llvm::StringSwitch>( + A->getValue()) .Cases("MD", "MultiThreadedDLL", "shared-ucrt", OutputInfo::MSVCRuntime::MultiThreadedDLL) .Cases("MDd", "MultiThreadedDebugDLL", "shared-debug-ucrt", @@ -3231,13 +3229,11 @@ void Driver::chooseSwiftModuleOutputPath(Compilation &C, } } -static void chooseModuleAuxiliaryOutputFilePath(Compilation &C, - const TypeToPathMap *OutputMap, - StringRef workingDirectory, - CommandOutput *Output, - file_types::ID fileID, - bool shouldUseProjectFolder = false, - llvm::Optional optId = llvm::None) { +static void chooseModuleAuxiliaryOutputFilePath( + Compilation &C, const TypeToPathMap *OutputMap, StringRef workingDirectory, + CommandOutput *Output, file_types::ID fileID, + bool shouldUseProjectFolder = false, + llvm::Optional optId = llvm::None) { if (hasExistingAdditionalOutput(*Output, fileID)) return; // Honor driver option for this path if it's given diff --git a/lib/Driver/FineGrainedDependencyDriverGraph.cpp b/lib/Driver/FineGrainedDependencyDriverGraph.cpp index 8bb9501df5b..18b05323078 100644 --- a/lib/Driver/FineGrainedDependencyDriverGraph.cpp +++ b/lib/Driver/FineGrainedDependencyDriverGraph.cpp @@ -117,7 +117,7 @@ ModuleDepGraph::Changes ModuleDepGraph::loadFromSwiftModuleBuffer( "loading fine-grained dependency graph from swiftmodule", buffer.getBufferIdentifier()); - llvm::Optional sourceFileDepGraph = + llvm::Optional sourceFileDepGraph = SourceFileDepGraph::loadFromSwiftModuleBuffer(buffer); if (!sourceFileDepGraph) return llvm::None; @@ -627,7 +627,8 @@ void ModuleDepGraph::verifyNodeIsInRightEntryInNodeMap( const ModuleDepGraphNode *const n) const { const DependencyKey &nodeKey = n->getKey(); const llvm::Optional swiftDeps = - swiftDepsString.empty() ? llvm::None : llvm::Optional(swiftDepsString); + swiftDepsString.empty() ? llvm::None + : llvm::Optional(swiftDepsString); (void)nodeKey; (void)swiftDeps; assert(n->getSwiftDeps() == swiftDeps || diff --git a/lib/Driver/ToolChains.h b/lib/Driver/ToolChains.h index 6125ea63545..c552d6b8124 100644 --- a/lib/Driver/ToolChains.h +++ b/lib/Driver/ToolChains.h @@ -80,7 +80,7 @@ protected: /// Retrieve the target SDK version for the given target triple. llvm::Optional - getTargetSDKVersion(const llvm::Triple &triple) const ; + getTargetSDKVersion(const llvm::Triple &triple) const; /// Information about the SDK that the application is being built against. /// This information is only used by the linker, so it is only populated @@ -91,8 +91,8 @@ protected: public: Darwin(const Driver &D, const llvm::Triple &Triple, - const llvm::Optional &TargetVariant) : - ToolChain(D, Triple), TargetVariant(TargetVariant) {} + const llvm::Optional &TargetVariant) + : ToolChain(D, Triple), TargetVariant(TargetVariant) {} ~Darwin() = default; std::string sanitizerRuntimeLibName(StringRef Sanitizer, diff --git a/lib/DriverTool/sil_opt_main.cpp b/lib/DriverTool/sil_opt_main.cpp index c8cd78d2178..9e6f8ef1176 100644 --- a/lib/DriverTool/sil_opt_main.cpp +++ b/lib/DriverTool/sil_opt_main.cpp @@ -81,8 +81,9 @@ enum class EnforceExclusivityMode { namespace llvm { -inline raw_ostream &operator<<(raw_ostream &os, - const llvm::Optional option) { +inline raw_ostream & +operator<<(raw_ostream &os, + const llvm::Optional option) { if (option) { switch (*option) { case CopyPropagationOption::Off: @@ -482,8 +483,9 @@ struct SILOptOptions { llvm::cl::desc("Ignore [always_inline] attribute."), llvm::cl::init(false)); using CPStateOpt = - llvm::cl::opt, /*ExternalStorage*/ false, - llvm::cl::parser>>; + llvm::cl::opt, + /*ExternalStorage*/ false, + llvm::cl::parser>>; CPStateOpt CopyPropagationState = CPStateOpt( "enable-copy-propagation", @@ -525,7 +527,8 @@ namespace { using ASTVerifierOverrideKind = LangOptions::ASTVerifierOverrideKind; } // end anonymous namespace -static llvm::Optional getASTOverrideKind(const SILOptOptions &options) { +static llvm::Optional +getASTOverrideKind(const SILOptOptions &options) { assert(!(options.EnableASTVerifier && options.DisableASTVerifier) && "Can only set one of EnableASTVerifier/DisableASTVerifier?!"); if (options.EnableASTVerifier) diff --git a/lib/DriverTool/swift_api_digester_main.cpp b/lib/DriverTool/swift_api_digester_main.cpp index 8ac0cf4c462..5cc8b25c313 100644 --- a/lib/DriverTool/swift_api_digester_main.cpp +++ b/lib/DriverTool/swift_api_digester_main.cpp @@ -136,7 +136,7 @@ class BestMatchMatcher : public NodeMatcher { return MatchedRight.count(R) == 0 && CanMatch(L, R); } - llvm::Optional findBestMatch(NodePtr Pin, NodeVector& Candidates) { + llvm::Optional findBestMatch(NodePtr Pin, NodeVector &Candidates) { llvm::Optional Best; for (auto Can : Candidates) { if (!internalCanMatch(Pin, Can)) @@ -1799,7 +1799,7 @@ public: } }; -static llvm::Optional findSelfIndex(SDKNode* Node) { +static llvm::Optional findSelfIndex(SDKNode *Node) { if (auto func = dyn_cast(Node)) { return func->getSelfIndexOptional(); } else if (auto vd = dyn_cast(Node)) { @@ -1829,13 +1829,16 @@ static void findTypeMemberDiffs(NodePtr leftSDKRoot, NodePtr rightSDKRoot, // index, old printed name) TypeMemberDiffItem item = { right->getAs()->getUsr(), - rightParent->getKind() == SDKNodeKind::Root ? - StringRef() : rightParent->getAs()->getFullyQualifiedName(), - right->getPrintedName(), findSelfIndex(right), llvm::None, - leftParent->getKind() == SDKNodeKind::Root ? - StringRef() : leftParent->getAs()->getFullyQualifiedName(), - left->getPrintedName() - }; + rightParent->getKind() == SDKNodeKind::Root + ? StringRef() + : rightParent->getAs()->getFullyQualifiedName(), + right->getPrintedName(), + findSelfIndex(right), + llvm::None, + leftParent->getKind() == SDKNodeKind::Root + ? StringRef() + : leftParent->getAs()->getFullyQualifiedName(), + left->getPrintedName()}; out.emplace_back(item); Detector.workOn(left, right); } diff --git a/lib/DriverTool/swift_llvm_opt_main.cpp b/lib/DriverTool/swift_llvm_opt_main.cpp index 75854fe98af..06cf46adbc7 100644 --- a/lib/DriverTool/swift_llvm_opt_main.cpp +++ b/lib/DriverTool/swift_llvm_opt_main.cpp @@ -143,7 +143,8 @@ getTargetMachine(llvm::Triple TheTriple, StringRef CPUStr, return TheTarget->createTargetMachine( TheTriple.getTriple(), CPUStr, FeaturesStr, targetOptions, - llvm::Optional(llvm::codegen::getExplicitRelocModel()), + llvm::Optional( + llvm::codegen::getExplicitRelocModel()), llvm::codegen::getExplicitCodeModel(), GetCodeGenOptLevel(options)); } diff --git a/lib/Frontend/ArgsToFrontendInputsConverter.cpp b/lib/Frontend/ArgsToFrontendInputsConverter.cpp index aae07312007..d7c368c4727 100644 --- a/lib/Frontend/ArgsToFrontendInputsConverter.cpp +++ b/lib/Frontend/ArgsToFrontendInputsConverter.cpp @@ -188,7 +188,7 @@ ArgsToFrontendInputsConverter::createInputFilesConsumingPrimaries( if (!Files.empty() && !hasAnyPrimaryFiles) { llvm::Optional> userSuppliedNamesOrErr = OutputFilesComputer::getOutputFilenamesFromCommandLineOrFilelist( - Args, Diags, options::OPT_o, options::OPT_output_filelist); + Args, Diags, options::OPT_o, options::OPT_output_filelist); if (userSuppliedNamesOrErr && userSuppliedNamesOrErr->size() == 1) result.setIsSingleThreadedWMO(true); } diff --git a/lib/Frontend/ArgsToFrontendInputsConverter.h b/lib/Frontend/ArgsToFrontendInputsConverter.h index cabad83c000..ce6e7b990a1 100644 --- a/lib/Frontend/ArgsToFrontendInputsConverter.h +++ b/lib/Frontend/ArgsToFrontendInputsConverter.h @@ -65,8 +65,8 @@ public: /// \param buffers If present, buffers read in the processing of the frontend /// inputs will be saved here. These should only be used for debugging /// purposes. - llvm::Optional convert( - SmallVectorImpl> *buffers); + llvm::Optional + convert(SmallVectorImpl> *buffers); private: bool enforceFilelistExclusion(); diff --git a/lib/Frontend/ArgsToFrontendOptionsConverter.cpp b/lib/Frontend/ArgsToFrontendOptionsConverter.cpp index b195db5f7b7..d1470daf5ed 100644 --- a/lib/Frontend/ArgsToFrontendOptionsConverter.cpp +++ b/lib/Frontend/ArgsToFrontendOptionsConverter.cpp @@ -668,7 +668,7 @@ bool ArgsToFrontendOptionsConverter::computeFallbackModuleName() { } llvm::Optional> outputFilenames = OutputFilesComputer::getOutputFilenamesFromCommandLineOrFilelist( - Args, Diags, options::OPT_o, options::OPT_output_filelist); + Args, Diags, options::OPT_o, options::OPT_output_filelist); std::string nameToStem = outputFilenames && outputFilenames->size() == 1 && diff --git a/lib/Frontend/ArgsToFrontendOutputsConverter.cpp b/lib/Frontend/ArgsToFrontendOutputsConverter.cpp index 37e413f7d37..9ad436912bf 100644 --- a/lib/Frontend/ArgsToFrontendOutputsConverter.cpp +++ b/lib/Frontend/ArgsToFrontendOutputsConverter.cpp @@ -37,10 +37,9 @@ bool ArgsToFrontendOutputsConverter::convert( std::vector &mainOutputsForIndexUnits, std::vector &supplementaryOutputs) { - llvm::Optional ofc = - OutputFilesComputer::create(Args, Diags, InputsAndOutputs, { - "output", options::OPT_o, options::OPT_output_filelist, "-o" - }); + llvm::Optional ofc = OutputFilesComputer::create( + Args, Diags, InputsAndOutputs, + {"output", options::OPT_o, options::OPT_output_filelist, "-o"}); if (!ofc) return true; llvm::Optional> mains = ofc->computeOutputFiles(); @@ -50,12 +49,11 @@ bool ArgsToFrontendOutputsConverter::convert( llvm::Optional> indexMains; if (Args.hasArg(options::OPT_index_unit_output_path, options::OPT_index_unit_output_path_filelist)) { - llvm::Optional iuofc = - OutputFilesComputer::create(Args, Diags, InputsAndOutputs, { - "index unit output path", options::OPT_index_unit_output_path, - options::OPT_index_unit_output_path_filelist, - "-index-unit-output-path" - }); + llvm::Optional iuofc = OutputFilesComputer::create( + Args, Diags, InputsAndOutputs, + {"index unit output path", options::OPT_index_unit_output_path, + options::OPT_index_unit_output_path_filelist, + "-index-unit-output-path"}); if (!iuofc) return true; indexMains = iuofc->computeOutputFiles(); @@ -110,11 +108,9 @@ OutputFilesComputer::getOutputFilenamesFromCommandLineOrFilelist( return args.getAllArgValues(singleOpt); } -llvm::Optional -OutputFilesComputer::create(const llvm::opt::ArgList &args, - DiagnosticEngine &diags, - const FrontendInputsAndOutputs &inputsAndOutputs, - OutputOptInfo optInfo) { +llvm::Optional OutputFilesComputer::create( + const llvm::opt::ArgList &args, DiagnosticEngine &diags, + const FrontendInputsAndOutputs &inputsAndOutputs, OutputOptInfo optInfo) { llvm::Optional> outputArguments = getOutputFilenamesFromCommandLineOrFilelist(args, diags, optInfo.SingleID, optInfo.FilelistID); @@ -183,13 +179,15 @@ OutputFilesComputer::computeOutputFiles() const { ? StringRef() : StringRef(OutputFileArguments[i++]); - llvm::Optional outputFile = computeOutputFile(outputArg, input); + llvm::Optional outputFile = + computeOutputFile(outputArg, input); if (!outputFile) return true; outputFiles.push_back(*outputFile); return false; }); - return hadError ? llvm::None : llvm::Optional>(outputFiles); + return hadError ? llvm::None + : llvm::Optional>(outputFiles); } llvm::Optional diff --git a/lib/Frontend/ArgsToFrontendOutputsConverter.h b/lib/Frontend/ArgsToFrontendOutputsConverter.h index 5aac8f05e5b..f4d32d7e826 100644 --- a/lib/Frontend/ArgsToFrontendOutputsConverter.h +++ b/lib/Frontend/ArgsToFrontendOutputsConverter.h @@ -100,7 +100,7 @@ public: private: llvm::Optional computeOutputFile(StringRef outputArg, - const InputFile &input) const; + const InputFile &input) const; /// \return the correct output filename when none was specified. /// @@ -108,7 +108,8 @@ private: /// without the driver, /// because the driver will always pass -o with an appropriate filename /// if output is required for the requested action. - llvm::Optional deriveOutputFileFromInput(const InputFile &input) const; + llvm::Optional + deriveOutputFileFromInput(const InputFile &input) const; /// \return the correct output filename when a directory was specified. /// @@ -137,7 +138,8 @@ public: const llvm::opt::ArgList &args, DiagnosticEngine &diags, const FrontendInputsAndOutputs &inputsAndOutputs, ArrayRef outputFiles, StringRef moduleName); - llvm::Optional> computeOutputPaths() const; + llvm::Optional> + computeOutputPaths() const; private: /// \Return a set of supplementary output paths for each input that might diff --git a/lib/Frontend/CompileJobCacheKey.cpp b/lib/Frontend/CompileJobCacheKey.cpp index f656826fb3d..a143acd7140 100644 --- a/lib/Frontend/CompileJobCacheKey.cpp +++ b/lib/Frontend/CompileJobCacheKey.cpp @@ -84,7 +84,8 @@ llvm::Expected swift::createCompileJobBaseCacheKey( Builder.push(*CMD, llvm::cas::TreeEntry::Regular, "command-line"); // FIXME: The version is maybe insufficient... - auto Version = CAS.storeFromString(llvm::None, version::getSwiftFullVersion()); + auto Version = + CAS.storeFromString(llvm::None, version::getSwiftFullVersion()); if (!Version) return Version.takeError(); Builder.push(*Version, llvm::cas::TreeEntry::Regular, "version"); diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp index 0db9e97b6a6..31c45c876d6 100644 --- a/lib/Frontend/CompilerInvocation.cpp +++ b/lib/Frontend/CompilerInvocation.cpp @@ -323,8 +323,9 @@ static bool ParseFrontendArgs( return converter.convert(buffers); } -static void diagnoseSwiftVersion(llvm::Optional &vers, Arg *verArg, - ArgList &Args, DiagnosticEngine &diags) { +static void diagnoseSwiftVersion(llvm::Optional &vers, + Arg *verArg, ArgList &Args, + DiagnosticEngine &diags) { // General invalid version error diags.diagnose(SourceLoc(), diag::error_invalid_arg_value, verArg->getAsString(Args), verArg->getValue()); @@ -630,7 +631,8 @@ static bool ParseLangArgs(LangOptions &Opts, ArgList &Args, if (const Arg *A = Args.getLastArg(OPT_unavailable_decl_optimization_EQ)) { auto value = - llvm::StringSwitch>(A->getValue()) + llvm::StringSwitch>( + A->getValue()) .Case("none", UnavailableDeclOptimization::None) .Case("stub", UnavailableDeclOptimization::Stub) .Case("complete", UnavailableDeclOptimization::Complete) @@ -911,11 +913,12 @@ static bool ParseLangArgs(LangOptions &Opts, ArgList &Args, if (Opts.isSwiftVersionAtLeast(6)) { Opts.StrictConcurrencyLevel = StrictConcurrency::Complete; } else if (const Arg *A = Args.getLastArg(OPT_strict_concurrency)) { - auto value = llvm::StringSwitch>(A->getValue()) - .Case("minimal", StrictConcurrency::Minimal) - .Case("targeted", StrictConcurrency::Targeted) - .Case("complete", StrictConcurrency::Complete) - .Default(llvm::None); + auto value = + llvm::StringSwitch>(A->getValue()) + .Case("minimal", StrictConcurrency::Minimal) + .Case("targeted", StrictConcurrency::Targeted) + .Case("complete", StrictConcurrency::Complete) + .Default(llvm::None); if (value) Opts.StrictConcurrencyLevel = *value; @@ -951,12 +954,15 @@ static bool ParseLangArgs(LangOptions &Opts, ArgList &Args, generateOptimizationRemarkRegex(Diags, Args, A); if (Arg *A = Args.getLastArg(OPT_Raccess_note)) { - auto value = llvm::StringSwitch>(A->getValue()) - .Case("none", AccessNoteDiagnosticBehavior::Ignore) - .Case("failures", AccessNoteDiagnosticBehavior::RemarkOnFailure) - .Case("all", AccessNoteDiagnosticBehavior::RemarkOnFailureOrSuccess) - .Case("all-validate", AccessNoteDiagnosticBehavior::ErrorOnFailureRemarkOnSuccess) - .Default(llvm::None); + auto value = + llvm::StringSwitch>( + A->getValue()) + .Case("none", AccessNoteDiagnosticBehavior::Ignore) + .Case("failures", AccessNoteDiagnosticBehavior::RemarkOnFailure) + .Case("all", AccessNoteDiagnosticBehavior::RemarkOnFailureOrSuccess) + .Case("all-validate", + AccessNoteDiagnosticBehavior::ErrorOnFailureRemarkOnSuccess) + .Default(llvm::None); if (value) Opts.AccessNoteBehavior = *value; @@ -1098,7 +1104,8 @@ static bool ParseLangArgs(LangOptions &Opts, ArgList &Args, getDefaultMinimumInliningTargetVersion(Opts.Target); // Parse OS version number arguments. - auto parseVersionArg = [&](OptSpecifier opt) -> llvm::Optional { + auto parseVersionArg = + [&](OptSpecifier opt) -> llvm::Optional { Arg *A = Args.getLastArg(opt); if (!A) return llvm::None; @@ -1948,11 +1955,11 @@ static bool ParseSILArgs(SILOptions &Opts, ArgList &Args, llvm::Optional specifiedDestroyHoistingOption; if (Arg *A = Args.getLastArg(OPT_enable_destroy_hoisting)) { - specifiedDestroyHoistingOption = + specifiedDestroyHoistingOption = llvm::StringSwitch>(A->getValue()) - .Case("true", DestroyHoistingOption::On) - .Case("false", DestroyHoistingOption::Off) - .Default(llvm::None); + .Case("true", DestroyHoistingOption::On) + .Case("false", DestroyHoistingOption::Off) + .Default(llvm::None); } llvm::Optional specifiedCopyPropagationOption; @@ -2469,7 +2476,8 @@ static bool ParseIRGenArgs(IRGenOptions &Opts, ArgList &Args, Opts.UseJIT = true; if (const Arg *A = Args.getLastArg(OPT_dump_jit)) { llvm::Optional artifact = - llvm::StringSwitch>(A->getValue()) + llvm::StringSwitch>( + A->getValue()) .Case("llvm-ir", JITDebugArtifact::LLVMIR) .Case("object", JITDebugArtifact::Object) .Default(llvm::None); @@ -2652,7 +2660,7 @@ static bool ParseIRGenArgs(IRGenOptions &Opts, ArgList &Args, } } - auto getRuntimeCompatVersion = [&] () -> llvm::Optional { + auto getRuntimeCompatVersion = [&]() -> llvm::Optional { llvm::Optional runtimeCompatibilityVersion; if (auto versionArg = Args.getLastArg( options::OPT_runtime_compatibility_version)) { diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp index e6d3e731d62..4ed5a62f07c 100644 --- a/lib/Frontend/Frontend.cpp +++ b/lib/Frontend/Frontend.cpp @@ -899,8 +899,8 @@ CompilerInstance::getRecordedBufferID(const InputFile &input, return bufferID; } -llvm::Optional CompilerInstance::getInputBuffersIfPresent( - const InputFile &input) { +llvm::Optional +CompilerInstance::getInputBuffersIfPresent(const InputFile &input) { if (auto b = input.getBuffer()) { return ModuleBuffers(llvm::MemoryBuffer::getMemBufferCopy(b->getBuffer(), b->getBufferIdentifier())); @@ -1558,8 +1558,8 @@ CompilerInstance::getSourceFileParsingOptions(bool forPrimary) const { } SourceFile *CompilerInstance::createSourceFileForMainModule( - ModuleDecl *mod, SourceFileKind fileKind, - llvm::Optional bufferID, bool isMainBuffer) const { + ModuleDecl *mod, SourceFileKind fileKind, llvm::Optional bufferID, + bool isMainBuffer) const { auto isPrimary = bufferID && isPrimaryInput(*bufferID); auto opts = getSourceFileParsingOptions(isPrimary); diff --git a/lib/Frontend/ModuleInterfaceBuilder.cpp b/lib/Frontend/ModuleInterfaceBuilder.cpp index c2f2fcbc387..60937775943 100644 --- a/lib/Frontend/ModuleInterfaceBuilder.cpp +++ b/lib/Frontend/ModuleInterfaceBuilder.cpp @@ -45,7 +45,7 @@ namespace path = llvm::sys::path; /// If the file dependency in \p FullDepPath is inside the \p Base directory, /// this returns its path relative to \p Base. Otherwise it returns None. static llvm::Optional getRelativeDepPath(StringRef DepPath, - StringRef Base) { + StringRef Base) { // If Base is the root directory, or DepPath does not start with Base, bail. if (Base.size() <= 1 || !DepPath.startswith(Base)) { return llvm::None; @@ -123,7 +123,8 @@ bool ExplicitModuleInterfaceBuilder::collectDepsForSerialization( assert(moduleCachePath.empty() || !DepName.startswith(moduleCachePath)); // Serialize the paths of dependencies in the SDK relative to it. - llvm::Optional SDKRelativePath = getRelativeDepPath(DepName, SDKPath); + llvm::Optional SDKRelativePath = + getRelativeDepPath(DepName, SDKPath); StringRef DepNameToStore = SDKRelativePath.value_or(DepName); bool IsSDKRelative = SDKRelativePath.has_value(); diff --git a/lib/Frontend/ModuleInterfaceSupport.cpp b/lib/Frontend/ModuleInterfaceSupport.cpp index 637b004c594..7287deb0ff0 100644 --- a/lib/Frontend/ModuleInterfaceSupport.cpp +++ b/lib/Frontend/ModuleInterfaceSupport.cpp @@ -425,7 +425,8 @@ class InheritedProtocolCollector { /// Helper to extract the `@available` attributes on a decl. static AvailableAttrList - getAvailabilityAttrs(const Decl *D, llvm::Optional &cache) { + getAvailabilityAttrs(const Decl *D, + llvm::Optional &cache) { if (cache.has_value()) return cache.value(); diff --git a/lib/FrontendTool/FrontendTool.cpp b/lib/FrontendTool/FrontendTool.cpp index ae5f6e2a589..8f337d0abb6 100644 --- a/lib/FrontendTool/FrontendTool.cpp +++ b/lib/FrontendTool/FrontendTool.cpp @@ -2181,13 +2181,13 @@ int swift::performFrontend(ArrayRef Args, // initialized by iterating over the buffers we collected above. auto configurationFileStackTraces = std::make_unique[]>( - configurationFileBuffers.size()); + configurationFileBuffers.size()); for_each(configurationFileBuffers.begin(), configurationFileBuffers.end(), &configurationFileStackTraces[0], [](const std::unique_ptr &buffer, llvm::Optional &trace) { - trace.emplace(*buffer); - }); + trace.emplace(*buffer); + }); // Setting DWARF Version depend on platform IRGenOptions &IRGenOpts = Invocation.getIRGenOptions(); diff --git a/lib/IDE/APIDigesterData.cpp b/lib/IDE/APIDigesterData.cpp index d30d9e6a1e8..6ec0085c0c7 100644 --- a/lib/IDE/APIDigesterData.cpp +++ b/lib/IDE/APIDigesterData.cpp @@ -66,12 +66,12 @@ raw_ostream &swift::ide::api::operator<<(raw_ostream &Out, const DeclKind Value) return Out << getDeclKindStrRaw(Value); } -llvm::Optional swift::ide::api::parseSDKNodeKind(StringRef Content) { +llvm::Optional +swift::ide::api::parseSDKNodeKind(StringRef Content) { return llvm::StringSwitch>(Content) #define NODE_KIND(NAME, VALUE) .Case(#VALUE, SDKNodeKind::NAME) #include "swift/IDE/DigesterEnums.def" - .Default(llvm::None) - ; + .Default(llvm::None); } NodeAnnotation swift::ide::api::parseSDKNodeAnnotation(StringRef Content) { diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp index 87a8cd908b0..2cc7a2477e9 100644 --- a/lib/IDE/CodeCompletion.cpp +++ b/lib/IDE/CodeCompletion.cpp @@ -589,8 +589,8 @@ void CodeCompletionCallbacksImpl::completeReturnStmt(CodeCompletionExpr *E) { Kind = CompletionKind::ReturnStmtExpr; } -void CodeCompletionCallbacksImpl::completeYieldStmt(CodeCompletionExpr *E, - llvm::Optional index) { +void CodeCompletionCallbacksImpl::completeYieldStmt( + CodeCompletionExpr *E, llvm::Optional index) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; // TODO: use a different completion kind when completing without an index @@ -715,8 +715,9 @@ static void addDeclKeywords(CodeCompletionResultSink &Sink, DeclContext *DC, } return false; }; - auto isTopLevelOnlyDeclIntroducer = [](CodeCompletionKeywordKind Kind, - llvm::Optional DAK) -> bool { + auto isTopLevelOnlyDeclIntroducer = + [](CodeCompletionKeywordKind Kind, + llvm::Optional DAK) -> bool { switch (Kind) { case CodeCompletionKeywordKind::kw_operator: case CodeCompletionKeywordKind::kw_precedencegroup: diff --git a/lib/IDE/CodeCompletionString.cpp b/lib/IDE/CodeCompletionString.cpp index e83187a84e4..ed5469e2295 100644 --- a/lib/IDE/CodeCompletionString.cpp +++ b/lib/IDE/CodeCompletionString.cpp @@ -109,7 +109,8 @@ llvm::Optional CodeCompletionString::getFirstTextChunkIndex( StringRef CodeCompletionString::getFirstTextChunk(bool includeLeadingPunctuation) const { - llvm::Optional Idx = getFirstTextChunkIndex(includeLeadingPunctuation); + llvm::Optional Idx = + getFirstTextChunkIndex(includeLeadingPunctuation); if (Idx.has_value()) return getChunks()[*Idx].getText(); return StringRef(); diff --git a/lib/IDE/CodeCompletionStringPrinter.cpp b/lib/IDE/CodeCompletionStringPrinter.cpp index f5a7a5bbf9c..05a9ae67d98 100644 --- a/lib/IDE/CodeCompletionStringPrinter.cpp +++ b/lib/IDE/CodeCompletionStringPrinter.cpp @@ -47,7 +47,8 @@ CodeCompletionStringPrinter::getChunkKindForPrintNameContext( } } -llvm::Optional CodeCompletionStringPrinter::getChunkKindForStructureKind( +llvm::Optional +CodeCompletionStringPrinter::getChunkKindForStructureKind( PrintStructureKind Kind) const { switch (Kind) { case PrintStructureKind::FunctionParameter: diff --git a/lib/IDE/CompletionLookup.cpp b/lib/IDE/CompletionLookup.cpp index 61b034d4e92..a6513136c4b 100644 --- a/lib/IDE/CompletionLookup.cpp +++ b/lib/IDE/CompletionLookup.cpp @@ -1497,8 +1497,8 @@ void CompletionLookup::addConstructorCall(const ConstructorDecl *CD, DeclVisibilityKind Reason, DynamicLookupInfo dynamicLookupInfo, llvm::Optional BaseType, - llvm::Optional Result, bool IsOnType, - Identifier addName) { + llvm::Optional Result, + bool IsOnType, Identifier addName) { foundFunction(CD); Type MemberType = getTypeOfMember(CD, BaseType.value_or(ExprType)); AnyFunctionType *ConstructorType = nullptr; @@ -2032,7 +2032,8 @@ void CompletionLookup::foundDecl(ValueDecl *D, DeclVisibilityKind Reason, return; } if (IsSelfRefExpr || IsSuperRefExpr) - addConstructorCall(CD, Reason, dynamicLookupInfo, llvm::None, llvm::None, + addConstructorCall(CD, Reason, dynamicLookupInfo, llvm::None, + llvm::None, /*IsOnType=*/false); } return; @@ -2994,8 +2995,8 @@ bool CompletionLookup::canUseAttributeOnDecl(DeclAttrKind DAK, bool IsInSil, return DeclAttribute::canAttributeAppearOnDeclKind(DAK, DK.value()); } -void CompletionLookup::getAttributeDeclCompletions(bool IsInSil, - llvm::Optional DK) { +void CompletionLookup::getAttributeDeclCompletions( + bool IsInSil, llvm::Optional DK) { // FIXME: also include user-defined attribute keywords StringRef TargetName = "Declaration"; if (DK.has_value()) { diff --git a/lib/IDE/CompletionOverrideLookup.cpp b/lib/IDE/CompletionOverrideLookup.cpp index 73c38d42728..b422a045c19 100644 --- a/lib/IDE/CompletionOverrideLookup.cpp +++ b/lib/IDE/CompletionOverrideLookup.cpp @@ -493,8 +493,8 @@ void CompletionOverrideLookup::addResultBuilderBuildCompletion( std::string declStringWithoutFunc; { llvm::raw_string_ostream out(declStringWithoutFunc); - printResultBuilderBuildFunction(builder, componentType, function, llvm::None, - out); + printResultBuilderBuildFunction(builder, componentType, function, + llvm::None, out); } Builder.addTextChunk(declStringWithoutFunc); Builder.addBraceStmtWithCursor(); diff --git a/lib/IDE/Formatting.cpp b/lib/IDE/Formatting.cpp index 08eee861542..320ad64b35a 100644 --- a/lib/IDE/Formatting.cpp +++ b/lib/IDE/Formatting.cpp @@ -70,8 +70,8 @@ static bool isLineAtLocEmpty(SourceManager &SM, SourceLoc Loc) { } /// \returns the first token after the token at \c Loc. -static llvm::Optional -getTokenAfter(SourceManager &SM, SourceLoc Loc, bool SkipComments = true) { +static llvm::Optional getTokenAfter(SourceManager &SM, SourceLoc Loc, + bool SkipComments = true) { assert(Loc.isValid()); CommentRetentionMode Mode = SkipComments ? CommentRetentionMode::None @@ -86,9 +86,10 @@ getTokenAfter(SourceManager &SM, SourceLoc Loc, bool SkipComments = true) { /// \returns the last token of the given kind in the open range between \c From /// and \c To. -static llvm::Optional -getLastTokenOfKindInOpenRange(SourceManager &SM, tok Kind, - SourceLoc From, SourceLoc To) { +static llvm::Optional getLastTokenOfKindInOpenRange(SourceManager &SM, + tok Kind, + SourceLoc From, + SourceLoc To) { llvm::Optional Match; while (auto Next = getTokenAfter(SM, From)) { if (!Next || !SM.isBeforeInBuffer(Next->getLoc(), To)) @@ -283,12 +284,10 @@ class FormatContext { bool InCommentLine; public: - FormatContext(SourceManager &SM, - llvm::Optional IndentCtx, - bool InDocCommentBlock = false, - bool InCommentLine = false) - :SM(SM), InnermostCtx(IndentCtx), InDocCommentBlock(InDocCommentBlock), - InCommentLine(InCommentLine) { } + FormatContext(SourceManager &SM, llvm::Optional IndentCtx, + bool InDocCommentBlock = false, bool InCommentLine = false) + : SM(SM), InnermostCtx(IndentCtx), InDocCommentBlock(InDocCommentBlock), + InCommentLine(InCommentLine) {} bool IsInDocCommentBlock() { return InDocCommentBlock; @@ -927,7 +926,8 @@ private: /// after such a node. class TrailingInfo { llvm::Optional TrailingToken; - TrailingInfo(llvm::Optional TrailingToken) : TrailingToken(TrailingToken) {} + TrailingInfo(llvm::Optional TrailingToken) + : TrailingToken(TrailingToken) {} public: /// Whether the trailing target is on an empty line. @@ -944,9 +944,9 @@ public: /// Checks if the target location immediately follows the provided \p EndLoc, /// optionally allowing for a single comma in between. - static llvm::Optional - find(SourceManager &SM, SourceLoc EndLoc, SourceLoc TargetLoc, - bool LookPastTrailingComma = true) { + static llvm::Optional find(SourceManager &SM, SourceLoc EndLoc, + SourceLoc TargetLoc, + bool LookPastTrailingComma = true) { // If the target is before the end of the end token, it's not trailing. SourceLoc TokenEndLoc = Lexer::getLocForEndOfToken(SM, EndLoc); if (SM.isBeforeInBuffer(TargetLoc, TokenEndLoc)) @@ -955,7 +955,7 @@ public: // If there is no next token, the target directly trails the end token. auto Next = getTokenAfter(SM, EndLoc, /*SkipComments=*/false); if (!Next) - return TrailingInfo {llvm::None}; + return TrailingInfo{llvm::None}; // If the target is before or at the next token's locations, it directly // trails the end token. @@ -963,7 +963,7 @@ public: if (NextTokLoc == TargetLoc) return TrailingInfo {Next}; if (SM.isBeforeInBuffer(TargetLoc, Next->getLoc())) - return TrailingInfo {llvm::None}; + return TrailingInfo{llvm::None}; // The target does not directly trail the end token. If we should look past // trailing commas, do so. @@ -1250,7 +1250,6 @@ public: } private: - llvm::Optional indentWithinStringLiteral() { assert(StringLiteralRange.isValid() && "Target is not within a string literal"); @@ -1565,7 +1564,8 @@ private: if (Start.isInvalid()) return {VisitAction::VisitChildren, llvm::None}; - llvm::Optional Trailing = TrailingInfo::find(SM, End, TargetLocation); + llvm::Optional Trailing = + TrailingInfo::find(SM, End, TargetLocation); scanTokensUntil(Start); if (!isTargetContext(Start, End) && !Trailing) @@ -1963,9 +1963,9 @@ private: return Aligner.getContextAndSetAlignment(CtxOverride); } - llvm::Optional - getIndentContextFrom(TrailingWhereClause *TWC, SourceLoc ContextLoc, - Decl *WalkableParent) { + llvm::Optional getIndentContextFrom(TrailingWhereClause *TWC, + SourceLoc ContextLoc, + Decl *WalkableParent) { if (!TWC) return llvm::None; return getIndentContextFromWhereClause(TWC->getRequirements(), @@ -1973,9 +1973,9 @@ private: ContextLoc, WalkableParent); } - llvm::Optional - getIndentContextFrom(GenericParamList *GP, SourceLoc ContextLoc, - Decl *WalkableParent) { + llvm::Optional getIndentContextFrom(GenericParamList *GP, + SourceLoc ContextLoc, + Decl *WalkableParent) { if (!GP) return llvm::None; @@ -2036,8 +2036,8 @@ private: template llvm::Optional - getIndentContextFromBraces(SourceLoc Open, SourceLoc Close, SourceLoc ContextLoc, - T* WalkableParent) { + getIndentContextFromBraces(SourceLoc Open, SourceLoc Close, + SourceLoc ContextLoc, T *WalkableParent) { SourceLoc L = getLocIfKind(SM, Open, tok::l_brace); SourceLoc R = getLocIfKind(SM, Close, tok::r_brace); if (L.isInvalid() || !overlapsTarget(L, R)) @@ -2051,9 +2051,9 @@ private: } template - llvm::Optional - getIndentContextFromBraces(SourceRange Braces, SourceLoc ContextLoc, - T* WalkableParent) { + llvm::Optional getIndentContextFromBraces(SourceRange Braces, + SourceLoc ContextLoc, + T *WalkableParent) { return getIndentContextFromBraces(Braces.Start, Braces.End, ContextLoc, WalkableParent); } @@ -2323,8 +2323,8 @@ private: } template - llvm::Optional - getIndentContextFrom(PoundAvailableInfo *A, T *WalkableParent) { + llvm::Optional getIndentContextFrom(PoundAvailableInfo *A, + T *WalkableParent) { SourceLoc ContextLoc = A->getStartLoc(); SourceLoc L = A->getLParenLoc(); SourceLoc R = getLocIfKind(SM, A->getRParenLoc(), tok::r_paren); @@ -2507,7 +2507,8 @@ private: } llvm::Optional - getIndentContextFrom(AbstractClosureExpr *ACE, SourceLoc ContextLoc = SourceLoc(), + getIndentContextFrom(AbstractClosureExpr *ACE, + SourceLoc ContextLoc = SourceLoc(), CaptureListExpr *ParentCapture = nullptr) { // Explicit capture lists should always have an explicit ClosureExpr as // their subexpression. @@ -2680,10 +2681,9 @@ private: return Aligner.getContextAndSetAlignment(CtxOverride); } - llvm::Optional - getIndentContextFromTrailingClosure(ArgumentList *Args, - llvm::Optional TrailingTarget, - SourceLoc ContextLoc) { + llvm::Optional getIndentContextFromTrailingClosure( + ArgumentList *Args, llvm::Optional TrailingTarget, + SourceLoc ContextLoc) { if (!Args->hasAnyTrailingClosures()) return llvm::None; @@ -2760,7 +2760,8 @@ private: #pragma mark TypeRepr indent contexts llvm::Optional - getIndentContextFrom(TypeRepr *T, llvm::Optional TrailingTarget) { + getIndentContextFrom(TypeRepr *T, + llvm::Optional TrailingTarget) { if (TrailingTarget) return llvm::None; @@ -2851,7 +2852,8 @@ private: #pragma mark Pattern indent contexts llvm::Optional - getIndentContextFrom(Pattern *P, llvm::Optional TrailingTarget) { + getIndentContextFrom(Pattern *P, + llvm::Optional TrailingTarget) { if (TrailingTarget) return llvm::None; diff --git a/lib/IDE/IDERequests.cpp b/lib/IDE/IDERequests.cpp index 8fe30835c4a..cc5e71bf763 100644 --- a/lib/IDE/IDERequests.cpp +++ b/lib/IDE/IDERequests.cpp @@ -151,7 +151,8 @@ bool CursorInfoResolver::tryResolve(ValueDecl *D, TypeDecl *CtorTyRef, SmallVector ReceiverTypes; bool IsDynamic = false; - llvm::Optional> CustomAttrRef = llvm::None; + llvm::Optional> CustomAttrRef = + llvm::None; if (Expr *BaseE = getBase(ExprStack)) { if (isDynamicRef(BaseE, D)) { IsDynamic = true; diff --git a/lib/IDE/ModuleInterfacePrinting.cpp b/lib/IDE/ModuleInterfacePrinting.cpp index 51c761052b3..b3fda4762d8 100644 --- a/lib/IDE/ModuleInterfacePrinting.cpp +++ b/lib/IDE/ModuleInterfacePrinting.cpp @@ -53,8 +53,10 @@ public: ClangLoader(ClangLoader) {} private: - void printDeclPre(const Decl *D, llvm::Optional Bracket) override; - void printDeclPost(const Decl *D, llvm::Optional Bracket) override; + void printDeclPre(const Decl *D, + llvm::Optional Bracket) override; + void printDeclPost(const Decl *D, + llvm::Optional Bracket) override; void avoidPrintDeclPost(const Decl *D) override; // Forwarding implementations. @@ -83,16 +85,15 @@ private: void printModuleRef(ModuleEntity Mod, Identifier Name) override { return OtherPrinter.printModuleRef(Mod, Name); } - void printSynthesizedExtensionPre(const ExtensionDecl *ED, - TypeOrExtensionDecl Target, - llvm::Optional Bracket) override { + void printSynthesizedExtensionPre( + const ExtensionDecl *ED, TypeOrExtensionDecl Target, + llvm::Optional Bracket) override { return OtherPrinter.printSynthesizedExtensionPre(ED, Target, Bracket); } - void - printSynthesizedExtensionPost(const ExtensionDecl *ED, - TypeOrExtensionDecl Target, - llvm::Optional Bracket) override { + void printSynthesizedExtensionPost( + const ExtensionDecl *ED, TypeOrExtensionDecl Target, + llvm::Optional Bracket) override { return OtherPrinter.printSynthesizedExtensionPost(ED, Target, Bracket); } @@ -219,8 +220,8 @@ static bool extensionHasClangNode(ExtensionDecl *ext) { return static_cast(swift::ide::extensionGetClangNode(ext)); } -llvm::Optional -swift::ide::findGroupNameForUSR(ModuleDecl *M, StringRef USR) { +llvm::Optional swift::ide::findGroupNameForUSR(ModuleDecl *M, + StringRef USR) { for (auto File : M->getTopLevelModule()->getFiles()) { if (auto Name = File->getGroupNameByUSR(USR)) { return Name; @@ -967,8 +968,8 @@ void ClangCommentPrinter::printDeclPre(const Decl *D, return OtherPrinter.printDeclPre(D, Bracket); } -void ClangCommentPrinter::printDeclPost(const Decl *D, - llvm::Optional Bracket) { +void ClangCommentPrinter::printDeclPost( + const Decl *D, llvm::Optional Bracket) { OtherPrinter.printDeclPost(D, Bracket); // Skip parameters; see printDeclPre(). diff --git a/lib/IDE/SourceEntityWalker.cpp b/lib/IDE/SourceEntityWalker.cpp index 280f62e6b14..232932640a0 100644 --- a/lib/IDE/SourceEntityWalker.cpp +++ b/lib/IDE/SourceEntityWalker.cpp @@ -216,8 +216,9 @@ ASTWalker::PreWalkAction SemaAnnotator::walkToDeclPreProper(Decl *D) { if (auto *macro = dyn_cast_or_null(MD->getMacroRef().getDecl())) { auto macroRefType = macro->getDeclaredInterfaceType(); - if (!passReference(macro, macroRefType, MD->getMacroNameLoc(), - ReferenceMetaData(SemaReferenceKind::DeclRef, llvm::None))) + if (!passReference( + macro, macroRefType, MD->getMacroNameLoc(), + ReferenceMetaData(SemaReferenceKind::DeclRef, llvm::None))) return Action::Stop(); } } @@ -427,8 +428,8 @@ ASTWalker::PreWalkResult SemaAnnotator::walkToExprPre(Expr *E) { NewOpAccess = OpAccess; } - llvm::SaveAndRestore> - C(this->OpAccess, NewOpAccess); + llvm::SaveAndRestore> C(this->OpAccess, + NewOpAccess); // Visit in source order. if (!MRE->getBase()->walk(*this)) @@ -523,8 +524,8 @@ ASTWalker::PreWalkResult SemaAnnotator::walkToExprPre(Expr *E) { // We already visited the children. return doSkipChildren(); } else if (auto IOE = dyn_cast(E)) { - llvm::SaveAndRestore> - C(this->OpAccess, AccessKind::ReadWrite); + llvm::SaveAndRestore> C(this->OpAccess, + AccessKind::ReadWrite); if (!IOE->getSubExpr()->walk(*this)) return Action::Stop(); @@ -532,8 +533,8 @@ ASTWalker::PreWalkResult SemaAnnotator::walkToExprPre(Expr *E) { // We already visited the children. return doSkipChildren(); } else if (auto LE = dyn_cast(E)) { - llvm::SaveAndRestore> - C(this->OpAccess, AccessKind::Read); + llvm::SaveAndRestore> C(this->OpAccess, + AccessKind::Read); if (!LE->getSubExpr()->walk(*this)) return Action::Stop(); @@ -542,8 +543,8 @@ ASTWalker::PreWalkResult SemaAnnotator::walkToExprPre(Expr *E) { return doSkipChildren(); } else if (auto AE = dyn_cast(E)) { { - llvm::SaveAndRestore> - C(this->OpAccess, AccessKind::Write); + llvm::SaveAndRestore> C(this->OpAccess, + AccessKind::Write); if (AE->getDest() && !AE->getDest()->walk(*this)) return Action::Stop(); @@ -644,9 +645,9 @@ ASTWalker::PreWalkAction SemaAnnotator::walkToTypeReprPre(TypeRepr *T) { auto Continue = passReference(ModD, {ident, IdT->getLoc()}); return Action::StopIf(!Continue); } - auto Continue = - passReference(VD, Type(), IdT->getNameLoc(), - ReferenceMetaData(SemaReferenceKind::TypeRef, llvm::None)); + auto Continue = passReference( + VD, Type(), IdT->getNameLoc(), + ReferenceMetaData(SemaReferenceKind::TypeRef, llvm::None)); return Action::StopIf(!Continue); } } else if (auto FT = dyn_cast(T)) { @@ -794,8 +795,9 @@ bool SemaAnnotator::handleImports(ImportDecl *Import) { if (Decls.size() == 1) { // FIXME: ImportDecl should store a DeclNameLoc. // FIXME: Handle overloaded funcs too by passing a reference for each? - if (!passReference(Decls.front(), Type(), DeclNameLoc(Import->getEndLoc()), - ReferenceMetaData(SemaReferenceKind::DeclRef, llvm::None))) + if (!passReference( + Decls.front(), Type(), DeclNameLoc(Import->getEndLoc()), + ReferenceMetaData(SemaReferenceKind::DeclRef, llvm::None))) return false; } diff --git a/lib/IDE/SwiftSourceDocInfo.cpp b/lib/IDE/SwiftSourceDocInfo.cpp index e1a5ac9b294..9a1f54ab62a 100644 --- a/lib/IDE/SwiftSourceDocInfo.cpp +++ b/lib/IDE/SwiftSourceDocInfo.cpp @@ -102,9 +102,14 @@ std::vector NameMatcher::resolve(ArrayRef Locs, Arra checkComments(); // handle any unresolved locs past the end of the last AST node or comment - std::vector Remaining(Locs.size() - ResolvedLocs.size(), { - ASTWalker::ParentTy(), CharSourceRange(), {}, llvm::None, LabelRangeType::None, - /*isActice*/true, /*isInSelector*/false}); + std::vector Remaining(Locs.size() - ResolvedLocs.size(), + {ASTWalker::ParentTy(), + CharSourceRange(), + {}, + llvm::None, + LabelRangeType::None, + /*isActice*/ true, + /*isInSelector*/ false}); ResolvedLocs.insert(ResolvedLocs.end(), Remaining.begin(), Remaining.end()); // return in the original order @@ -243,7 +248,8 @@ ASTWalker::PreWalkAction NameMatcher::walkToDeclPre(Decl *D) { tryResolve(ASTWalker::ParentTy(D), D->getLoc(), LabelRangeType::Param, LabelRanges, llvm::None); } else if (SubscriptDecl *SD = dyn_cast(D)) { - tryResolve(ASTWalker::ParentTy(D), D->getLoc(), LabelRangeType::NoncollapsibleParam, + tryResolve(ASTWalker::ParentTy(D), D->getLoc(), + LabelRangeType::NoncollapsibleParam, getLabelRanges(SD->getIndices(), getSourceMgr()), llvm::None); } else if (EnumElementDecl *EED = dyn_cast(D)) { if (auto *ParamList = EED->getParameterList()) { @@ -534,8 +540,13 @@ void NameMatcher::skipLocsBefore(SourceLoc Start) { while (!isDone() && getSourceMgr().isBeforeInBuffer(nextLoc(), Start)) { if (!checkComments()) { LocsToResolve.pop_back(); - ResolvedLocs.push_back({ASTWalker::ParentTy(), CharSourceRange(), {}, - llvm::None, LabelRangeType::None, isActive(), isInSelector()}); + ResolvedLocs.push_back({ASTWalker::ParentTy(), + CharSourceRange(), + {}, + llvm::None, + LabelRangeType::None, + isActive(), + isInSelector()}); } } } @@ -627,7 +638,8 @@ bool NameMatcher::tryResolve(ASTWalker::ParentTy Node, DeclNameLoc NameLoc, bool NameMatcher::tryResolve(ASTWalker::ParentTy Node, SourceLoc NameLoc) { assert(!isDone()); - return tryResolve(Node, NameLoc, LabelRangeType::None, llvm::None, llvm::None); + return tryResolve(Node, NameLoc, LabelRangeType::None, llvm::None, + llvm::None); } bool NameMatcher::tryResolve(ASTWalker::ParentTy Node, SourceLoc NameLoc, @@ -660,8 +672,13 @@ bool NameMatcher::tryResolve(ASTWalker::ParentTy Node, SourceLoc NameLoc, Range.getByteLength() - 1); if (NewRange.getStart() == Next.Loc) { LocsToResolve.pop_back(); - ResolvedLocs.push_back({Node, NewRange, {}, llvm::None, LabelRangeType::None, - isActive(), isInSelector()}); + ResolvedLocs.push_back({Node, + NewRange, + {}, + llvm::None, + LabelRangeType::None, + isActive(), + isInSelector()}); WasResolved = true; } } diff --git a/lib/IDE/SyntaxModel.cpp b/lib/IDE/SyntaxModel.cpp index 240e2ffe3ca..29a3100f6fc 100644 --- a/lib/IDE/SyntaxModel.cpp +++ b/lib/IDE/SyntaxModel.cpp @@ -351,7 +351,7 @@ class ModelASTWalker : public ASTWalker { static const std::regex &getURLRegex(StringRef Protocol); llvm::Optional parseFieldNode(StringRef Text, StringRef OrigText, - SourceLoc OrigLoc); + SourceLoc OrigLoc); llvm::DenseSet NodesVisitedBefore; /// When non-zero, we should avoid passing tokens as syntax nodes since a parent of several tokens /// is considered as one, e.g. object literal expression. @@ -1699,8 +1699,8 @@ public: } // end anonymous namespace llvm::Optional ModelASTWalker::parseFieldNode(StringRef Text, - StringRef OrigText, - SourceLoc OrigLoc) { + StringRef OrigText, + SourceLoc OrigLoc) { llvm::Optional Node; DocFieldParser parser(Text); if (auto ident = parser.parseFieldName()) { diff --git a/lib/IDE/TypeContextInfo.cpp b/lib/IDE/TypeContextInfo.cpp index 2ca5abb67a9..1edff744269 100644 --- a/lib/IDE/TypeContextInfo.cpp +++ b/lib/IDE/TypeContextInfo.cpp @@ -73,8 +73,8 @@ void ContextInfoCallbacks::completeReturnStmt(CodeCompletionExpr *E) { CurDeclContext = P.CurDeclContext; ParsedExpr = E; } -void ContextInfoCallbacks::completeYieldStmt(CodeCompletionExpr *E, - llvm::Optional yieldIndex) { +void ContextInfoCallbacks::completeYieldStmt( + CodeCompletionExpr *E, llvm::Optional yieldIndex) { CurDeclContext = P.CurDeclContext; ParsedExpr = E; } diff --git a/lib/IDETool/CompileInstance.cpp b/lib/IDETool/CompileInstance.cpp index 73db14a68a5..9ef977faa31 100644 --- a/lib/IDETool/CompileInstance.cpp +++ b/lib/IDETool/CompileInstance.cpp @@ -218,9 +218,9 @@ bool CompileInstance::performCachedSemaIfPossible(DiagnosticConsumer *DiagC) { auto FS = SM.getFileSystem(); if (shouldCheckDependencies()) { - if (areAnyDependentFilesInvalidated(*CI, *FS, /*excludeBufferID=*/llvm::None, - DependencyCheckedTimestamp, - InMemoryDependencyHash)) { + if (areAnyDependentFilesInvalidated( + *CI, *FS, /*excludeBufferID=*/llvm::None, + DependencyCheckedTimestamp, InMemoryDependencyHash)) { return true; } DependencyCheckedTimestamp = std::chrono::system_clock::now(); diff --git a/lib/IDETool/DependencyChecking.cpp b/lib/IDETool/DependencyChecking.cpp index bbac06ae155..edac90fd4b5 100644 --- a/lib/IDETool/DependencyChecking.cpp +++ b/lib/IDETool/DependencyChecking.cpp @@ -62,9 +62,10 @@ forEachDependencyUntilTrue(CompilerInstance &CI, } /// Collect hash codes of the dependencies into \c Map. -static void cacheDependencyHashIfNeeded(CompilerInstance &CI, - llvm::Optional excludeBufferID, - llvm::StringMap &Map) { +static void +cacheDependencyHashIfNeeded(CompilerInstance &CI, + llvm::Optional excludeBufferID, + llvm::StringMap &Map) { auto &FS = CI.getFileSystem(); forEachDependencyUntilTrue(CI, excludeBufferID, [&](StringRef filename) { if (Map.count(filename)) diff --git a/lib/IDETool/IDEInspectionInstance.cpp b/lib/IDETool/IDEInspectionInstance.cpp index 1113e38ab7d..2bf86fea645 100644 --- a/lib/IDETool/IDEInspectionInstance.cpp +++ b/lib/IDETool/IDEInspectionInstance.cpp @@ -444,7 +444,8 @@ bool IDEInspectionInstance::performCachedOperationIfPossible( } void IDEInspectionInstance::performNewOperation( - llvm::Optional ArgsHash, swift::CompilerInvocation &Invocation, + llvm::Optional ArgsHash, + swift::CompilerInvocation &Invocation, llvm::IntrusiveRefCntPtr FileSystem, llvm::MemoryBuffer *ideInspectionTargetBuffer, unsigned int Offset, DiagnosticConsumer *DiagC, diff --git a/lib/IDETool/SyntacticMacroExpansion.cpp b/lib/IDETool/SyntacticMacroExpansion.cpp index 0bde8f776df..03d400fabb3 100644 --- a/lib/IDETool/SyntacticMacroExpansion.cpp +++ b/lib/IDETool/SyntacticMacroExpansion.cpp @@ -174,10 +174,10 @@ MacroDecl *SyntacticMacroExpansionInstance::getSynthesizedMacroDecl( } /// Create a unique name of the expansion. The result is *appended* to \p out. -static void addExpansionDiscriminator(SmallString<32> &out, - const SourceFile *SF, SourceLoc loc, - llvm::Optional supplementalLoc = llvm::None, - llvm::Optional role = llvm::None) { +static void addExpansionDiscriminator( + SmallString<32> &out, const SourceFile *SF, SourceLoc loc, + llvm::Optional supplementalLoc = llvm::None, + llvm::Optional role = llvm::None) { SourceManager &SM = SF->getASTContext().SourceMgr; StableHasher hasher = StableHasher::defaultHasher(); diff --git a/lib/IRGen/Fulfillment.cpp b/lib/IRGen/Fulfillment.cpp index c4771300cb7..10edc33c0bb 100644 --- a/lib/IRGen/Fulfillment.cpp +++ b/lib/IRGen/Fulfillment.cpp @@ -180,9 +180,9 @@ bool FulfillmentMap::searchTypeMetadata(IRGenModule &IGM, CanType type, return false; } -static CanType getSingletonPackExpansionParameter(CanPackType packType, - const FulfillmentMap::InterestingKeysCallback &keys, - llvm::Optional &packExpansionComponent) { +static CanType getSingletonPackExpansionParameter( + CanPackType packType, const FulfillmentMap::InterestingKeysCallback &keys, + llvm::Optional &packExpansionComponent) { if (auto expansion = packType.unwrapSingletonPackExpansion()) { if (keys.isInterestingPackExpansion(expansion)) { packExpansionComponent = 0; diff --git a/lib/IRGen/GenCall.cpp b/lib/IRGen/GenCall.cpp index c32195da2da..8a9df68c032 100644 --- a/lib/IRGen/GenCall.cpp +++ b/lib/IRGen/GenCall.cpp @@ -29,10 +29,10 @@ #include "clang/CodeGen/CodeGenABITypes.h" #include "clang/CodeGen/ModuleBuilder.h" #include "clang/Sema/Sema.h" +#include "llvm/ADT/Optional.h" #include "llvm/IR/GlobalPtrAuthInfo.h" #include "llvm/IR/GlobalValue.h" #include "llvm/Support/Compiler.h" -#include "llvm/ADT/Optional.h" #include "CallEmission.h" #include "EntryPointArgumentEmission.h" @@ -150,7 +150,8 @@ Alignment IRGenModule::getAsyncContextAlignment() const { llvm::Optional FunctionPointerKind::getStaticAsyncContextSize(IRGenModule &IGM) const { - if (!isSpecial()) return llvm::None; + if (!isSpecial()) + return llvm::None; auto headerSize = getAsyncContextHeaderSize(IGM); headerSize = headerSize.roundUpToAlignment(IGM.getPointerAlignment()); diff --git a/lib/IRGen/GenCast.cpp b/lib/IRGen/GenCast.cpp index acc8d1cebd7..9770f0e2fae 100644 --- a/lib/IRGen/GenCast.cpp +++ b/lib/IRGen/GenCast.cpp @@ -530,14 +530,10 @@ llvm::Value *irgen::emitMetatypeToAnyObjectDowncast(IRGenFunction &IGF, /// Emit a checked cast to a protocol or protocol composition. -void irgen::emitScalarExistentialDowncast(IRGenFunction &IGF, - llvm::Value *value, - SILType srcType, - SILType destType, - CheckedCastMode mode, - llvm::Optional metatypeKind, - GenericSignature fnSig, - Explosion &ex) { +void irgen::emitScalarExistentialDowncast( + IRGenFunction &IGF, llvm::Value *value, SILType srcType, SILType destType, + CheckedCastMode mode, llvm::Optional metatypeKind, + GenericSignature fnSig, Explosion &ex) { auto srcInstanceType = srcType.getASTType(); auto destInstanceType = destType.getASTType(); while (auto metatypeType = dyn_cast( @@ -1017,9 +1013,7 @@ void irgen::emitScalarCheckedCast(IRGenFunction &IGF, Explosion outRes; emitScalarExistentialDowncast(IGF, instance, sourceLoweredType, targetLoweredType, mode, - /*not a metatype*/ llvm::None, - fnSig, - outRes); + /*not a metatype*/ llvm::None, fnSig, outRes); returnNilCheckedResult(IGF.Builder, outRes); return; } diff --git a/lib/IRGen/GenCast.h b/lib/IRGen/GenCast.h index e977e06b5b0..921bc171fcb 100644 --- a/lib/IRGen/GenCast.h +++ b/lib/IRGen/GenCast.h @@ -96,14 +96,10 @@ namespace irgen { /// /// If a metatype kind is provided, the cast is done as a metatype cast. If /// not, the cast is done as a class instance cast. - void emitScalarExistentialDowncast(IRGenFunction &IGF, - llvm::Value *orig, - SILType srcType, - SILType destType, - CheckedCastMode mode, - llvm::Optional metatypeKind, - GenericSignature fnSig, - Explosion &ex); + void emitScalarExistentialDowncast( + IRGenFunction &IGF, llvm::Value *orig, SILType srcType, SILType destType, + CheckedCastMode mode, llvm::Optional metatypeKind, + GenericSignature fnSig, Explosion &ex); /// Emit a checked cast from a metatype to AnyObject. llvm::Value *emitMetatypeToAnyObjectDowncast(IRGenFunction &IGF, diff --git a/lib/IRGen/GenClass.cpp b/lib/IRGen/GenClass.cpp index 66368f9bacd..9658b4603de 100644 --- a/lib/IRGen/GenClass.cpp +++ b/lib/IRGen/GenClass.cpp @@ -136,9 +136,8 @@ namespace { ReferenceCounting refcounting, bool completelyFragileLayout, llvm::Optional> tailTypes = llvm::None) - : StructLayoutBuilder(IGM), - TailTypes(tailTypes), - CompletelyFragileLayout(completelyFragileLayout) { + : StructLayoutBuilder(IGM), TailTypes(tailTypes), + CompletelyFragileLayout(completelyFragileLayout) { // Start by adding a heap header. switch (refcounting) { case ReferenceCounting::Native: @@ -1346,7 +1345,8 @@ namespace { void buildMetaclassStub() { assert(FieldLayout && "can't build a metaclass from a category"); - llvm::Optional specializedGenericType = getSpecializedGenericType(); + llvm::Optional specializedGenericType = + getSpecializedGenericType(); // The isa is the metaclass pointer for the root class. auto rootClass = getRootClassForMetaclass(IGM, getClass()); diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp index 0f5edf2504a..8062188cf4c 100644 --- a/lib/IRGen/GenDecl.cpp +++ b/lib/IRGen/GenDecl.cpp @@ -512,8 +512,7 @@ void IRGenModule::emitSourceFile(SourceFile &SF) { // harmless aside from code size. if (!IRGen.Opts.UseJIT) { auto addBackDeployLib = [&](llvm::VersionTuple version, - StringRef libraryName, - bool forceLoad) { + StringRef libraryName, bool forceLoad) { llvm::Optional compatibilityVersion; if (libraryName == "swiftCompatibilityDynamicReplacements") { compatibilityVersion = IRGen.Opts. @@ -537,7 +536,7 @@ void IRGenModule::emitSourceFile(SourceFile &SF) { forceLoad)); }; - #define BACK_DEPLOYMENT_LIB(Version, Filter, LibraryName, ForceLoad) \ +#define BACK_DEPLOYMENT_LIB(Version, Filter, LibraryName, ForceLoad) \ addBackDeployLib(llvm::VersionTuple Version, LibraryName, ForceLoad); #include "swift/Frontend/BackDeploymentLibs.def" } @@ -2384,8 +2383,8 @@ llvm::Function *irgen::createFunction(IRGenModule &IGM, LinkInfo &linkInfo, /// Get or create an LLVM global variable with these linkage rules. llvm::GlobalVariable *swift::irgen::createVariable( IRGenModule &IGM, LinkInfo &linkInfo, llvm::Type *storageType, - Alignment alignment, DebugTypeInfo DbgTy, llvm::Optional DebugLoc, - StringRef DebugName) { + Alignment alignment, DebugTypeInfo DbgTy, + llvm::Optional DebugLoc, StringRef DebugName) { auto name = linkInfo.getName(); llvm::GlobalValue *existingValue = IGM.Module.getNamedGlobal(name); if (existingValue) { @@ -5472,11 +5471,10 @@ llvm::Constant *IRGenModule::getAddrOfProtocolConformanceDescriptor( } /// Fetch the declaration of the ivar initializer for the given class. -llvm::Optional IRGenModule::getAddrOfIVarInitDestroy( - ClassDecl *cd, - bool isDestroyer, - bool isForeign, - ForDefinition_t forDefinition) { +llvm::Optional +IRGenModule::getAddrOfIVarInitDestroy(ClassDecl *cd, bool isDestroyer, + bool isForeign, + ForDefinition_t forDefinition) { auto silRef = SILDeclRef(cd, isDestroyer ? SILDeclRef::Kind::IVarDestroyer diff --git a/lib/IRGen/GenDiffFunc.cpp b/lib/IRGen/GenDiffFunc.cpp index 96d9fadef50..2bcceb24456 100644 --- a/lib/IRGen/GenDiffFunc.cpp +++ b/lib/IRGen/GenDiffFunc.cpp @@ -143,7 +143,9 @@ public: fields, T, getBestKnownAlignment().getValue(), *this); } - llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { return llvm::None; } + llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { + return llvm::None; + } llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF, SILType T) const { return llvm::None; } @@ -318,7 +320,9 @@ public: fields, T, getBestKnownAlignment().getValue(), *this); } - llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { return llvm::None; } + llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { + return llvm::None; + } llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF, SILType T) const { return llvm::None; } diff --git a/lib/IRGen/GenFunc.cpp b/lib/IRGen/GenFunc.cpp index 668bd4d66b9..0d2cd436ca1 100644 --- a/lib/IRGen/GenFunc.cpp +++ b/lib/IRGen/GenFunc.cpp @@ -316,10 +316,12 @@ namespace { static bool isFirstElementTrivial() { return true; } - void emitRetainFirstElement(IRGenFunction &IGF, llvm::Value *fn, - llvm::Optional atomicity = llvm::None) const {} - void emitReleaseFirstElement(IRGenFunction &IGF, llvm::Value *fn, - llvm::Optional atomicity = llvm::None) const {} + void emitRetainFirstElement( + IRGenFunction &IGF, llvm::Value *fn, + llvm::Optional atomicity = llvm::None) const {} + void emitReleaseFirstElement( + IRGenFunction &IGF, llvm::Value *fn, + llvm::Optional atomicity = llvm::None) const {} void emitAssignFirstElement(IRGenFunction &IGF, llvm::Value *fn, Address fnAddr) const { IGF.Builder.CreateStore(fn, fnAddr); @@ -337,15 +339,17 @@ namespace { bool isSecondElementTrivial() const { return isTriviallyDestroyable(ResilienceExpansion::Maximal); } - void emitRetainSecondElement(IRGenFunction &IGF, llvm::Value *data, - llvm::Optional atomicity = llvm::None) const { + void emitRetainSecondElement( + IRGenFunction &IGF, llvm::Value *data, + llvm::Optional atomicity = llvm::None) const { if (!isTriviallyDestroyable(ResilienceExpansion::Maximal)) { if (!atomicity) atomicity = IGF.getDefaultAtomicity(); IGF.emitNativeStrongRetain(data, *atomicity); } } - void emitReleaseSecondElement(IRGenFunction &IGF, llvm::Value *data, - llvm::Optional atomicity = llvm::None) const { + void emitReleaseSecondElement( + IRGenFunction &IGF, llvm::Value *data, + llvm::Optional atomicity = llvm::None) const { if (!isTriviallyDestroyable(ResilienceExpansion::Maximal)) { if (!atomicity) atomicity = IGF.getDefaultAtomicity(); IGF.emitNativeStrongRelease(data, *atomicity); @@ -1199,8 +1203,7 @@ public: : PartialApplicationForwarderEmission( IGM, subIGF, fwd, staticFnPtr, calleeHasContext, origSig, origType, substType, outType, subs, layout, conventions), - layout(getAsyncContextLayout( - subIGF.IGM, origType, substType, subs)), + layout(getAsyncContextLayout(subIGF.IGM, origType, substType, subs)), currentArgumentIndex(outType->getNumParameters()) {} void begin() override { super::begin(); } @@ -1356,16 +1359,12 @@ getPartialApplicationForwarderEmission( /// If 'layout' is null, there is a single captured value of /// Swift-refcountable type that is being used directly as the /// context object. -static llvm::Value *emitPartialApplicationForwarder(IRGenModule &IGM, - const llvm::Optional &staticFnPtr, - bool calleeHasContext, - const Signature &origSig, - CanSILFunctionType origType, - CanSILFunctionType substType, - CanSILFunctionType outType, - SubstitutionMap subs, - HeapLayout const *layout, - ArrayRef conventions) { +static llvm::Value *emitPartialApplicationForwarder( + IRGenModule &IGM, const llvm::Optional &staticFnPtr, + bool calleeHasContext, const Signature &origSig, + CanSILFunctionType origType, CanSILFunctionType substType, + CanSILFunctionType outType, SubstitutionMap subs, HeapLayout const *layout, + ArrayRef conventions) { auto outSig = IGM.getSignature(outType); llvm::AttributeList outAttrs = outSig.getAttributes(); llvm::FunctionType *fwdTy = outSig.getType(); @@ -1472,7 +1471,8 @@ static llvm::Value *emitPartialApplicationForwarder(IRGenModule &IGM, auto bindingLayout = layout->getElement(nextCapturedField++); // The bindings should be fixed-layout inside the object, so we can // pass None here. If they weren't, we'd have a chicken-egg problem. - auto bindingsAddr = bindingLayout.project(subIGF, data, /*offsets*/ llvm::None); + auto bindingsAddr = + bindingLayout.project(subIGF, data, /*offsets*/ llvm::None); layout->getBindings().restore(subIGF, bindingsAddr, MetadataState::Complete); } @@ -2083,7 +2083,7 @@ llvm::Optional irgen::emitFunctionPartialApplication( out.add(ctx); return {}; } - + llvm::Optional staticFn; if (fn.isConstant()) staticFn = fn; diff --git a/lib/IRGen/GenHeap.cpp b/lib/IRGen/GenHeap.cpp index 4014f7868c5..099b3914ba0 100644 --- a/lib/IRGen/GenHeap.cpp +++ b/lib/IRGen/GenHeap.cpp @@ -1553,11 +1553,14 @@ public: // FIXME: This seems wrong. We used to just mangle opened archetypes as // their interface type. Let's make that explicit now. auto astType = boxedInterfaceType.getASTType(); - astType = astType.transformRec([](Type t) -> llvm::Optional { - if (auto *openedExistential = t->getAs()) - return openedExistential->getInterfaceType(); - return llvm::None; - })->getCanonicalType(); + astType = + astType + .transformRec([](Type t) -> llvm::Optional { + if (auto *openedExistential = t->getAs()) + return openedExistential->getInterfaceType(); + return llvm::None; + }) + ->getCanonicalType(); boxedInterfaceType = SILType::getPrimitiveType( astType, boxedInterfaceType.getCategory()); } diff --git a/lib/IRGen/GenKeyPath.cpp b/lib/IRGen/GenKeyPath.cpp index c569871a401..d23a53e822c 100644 --- a/lib/IRGen/GenKeyPath.cpp +++ b/lib/IRGen/GenKeyPath.cpp @@ -885,11 +885,14 @@ emitKeyPathComponent(IRGenModule &IGM, // FIXME: This seems wrong. We used to just mangle opened archetypes as // their interface type. Let's make that explicit now. - substType = substType.transformRec([](Type t) -> llvm::Optional { - if (auto *openedExistential = t->getAs()) - return openedExistential->getInterfaceType(); - return llvm::None; - })->getCanonicalType(); + substType = substType + .transformRec([](Type t) -> llvm::Optional { + if (auto *openedExistential = + t->getAs()) + return openedExistential->getInterfaceType(); + return llvm::None; + }) + ->getCanonicalType(); if (reqt.isAnyMetadata()) { // Type requirement. diff --git a/lib/IRGen/GenMeta.cpp b/lib/IRGen/GenMeta.cpp index 92d82a10066..eddad07b906 100644 --- a/lib/IRGen/GenMeta.cpp +++ b/lib/IRGen/GenMeta.cpp @@ -780,8 +780,7 @@ namespace { SILDefaultWitnessTable *DefaultWitnesses; llvm::Optional - NumRequirementsInSignature, - NumRequirements; + NumRequirementsInSignature, NumRequirements; bool Resilient; @@ -1183,7 +1182,7 @@ namespace { StringRef UserFacingName; llvm::Optional> ImportInfo; - + using super::IGM; using super::B; using super::asImpl; @@ -4248,7 +4247,8 @@ namespace { const ClassLayout &FieldLayout; llvm::Optional - ClassRODataOffset, MetaclassObjectOffset, MetaclassRODataOffset; + ClassRODataOffset, MetaclassObjectOffset, MetaclassRODataOffset; + public: GenericClassMetadataBuilder(IRGenModule &IGM, ClassDecl *theClass, ConstantStructBuilder &B, @@ -5431,9 +5431,8 @@ void irgen::emitSpecializedGenericStructMetadata(IRGenModule &IGM, CanType type, // Enums -static llvm::Optional getConstantPayloadSize(IRGenModule &IGM, - EnumDecl *enumDecl, - CanType enumTy) { +static llvm::Optional +getConstantPayloadSize(IRGenModule &IGM, EnumDecl *enumDecl, CanType enumTy) { auto &enumTI = IGM.getTypeInfoForUnlowered(enumTy); if (!enumTI.isFixedSize(ResilienceExpansion::Maximal)) { return llvm::None; @@ -5446,7 +5445,7 @@ static llvm::Optional getConstantPayloadSize(IRGenModule &IGM, } static llvm::Optional getConstantPayloadSize(IRGenModule &IGM, - EnumDecl *enumDecl) { + EnumDecl *enumDecl) { auto enumTy = enumDecl->getDeclaredTypeInContext()->getCanonicalType(); return getConstantPayloadSize(IGM, enumDecl, enumTy); } @@ -6602,8 +6601,8 @@ void IRGenModule::emitOpaqueTypeDecl(OpaqueTypeDecl *D) { bool irgen::methodRequiresReifiedVTableEntry(IRGenModule &IGM, const SILVTable *vtable, SILDeclRef method) { - llvm::Optional entry - = vtable->getEntry(IGM.getSILModule(), method); + llvm::Optional entry = + vtable->getEntry(IGM.getSILModule(), method); LLVM_DEBUG(llvm::dbgs() << "looking at vtable:\n"; vtable->print(llvm::dbgs())); if (!entry) { diff --git a/lib/IRGen/GenProto.cpp b/lib/IRGen/GenProto.cpp index 3cb6729b6dd..b387f78adb6 100644 --- a/lib/IRGen/GenProto.cpp +++ b/lib/IRGen/GenProto.cpp @@ -3577,14 +3577,13 @@ GenericTypeRequirements::GenericTypeRequirements(IRGenModule &IGM, // Construct a representative function type. auto generics = ncGenerics.getCanonicalSignature(); - auto fnType = SILFunctionType::get(generics, SILFunctionType::ExtInfo(), - SILCoroutineKind::None, - /*callee*/ ParameterConvention::Direct_Unowned, - /*params*/ {}, /*yields*/ {}, - /*results*/ {}, /*error*/ llvm::None, - /*pattern subs*/ SubstitutionMap(), - /*invocation subs*/ SubstitutionMap(), - IGM.Context); + auto fnType = SILFunctionType::get( + generics, SILFunctionType::ExtInfo(), SILCoroutineKind::None, + /*callee*/ ParameterConvention::Direct_Unowned, + /*params*/ {}, /*yields*/ {}, + /*results*/ {}, /*error*/ llvm::None, + /*pattern subs*/ SubstitutionMap(), + /*invocation subs*/ SubstitutionMap(), IGM.Context); // Figure out what we're actually still required to pass PolymorphicConvention convention(IGM, fnType); diff --git a/lib/IRGen/GenReflection.cpp b/lib/IRGen/GenReflection.cpp index 53531d98014..b240925e44d 100644 --- a/lib/IRGen/GenReflection.cpp +++ b/lib/IRGen/GenReflection.cpp @@ -662,9 +662,9 @@ protected: // method. using GetAddrOfEntityFn = llvm::Constant* (IRGenModule &, ConstantInit); - llvm::GlobalVariable *emit( - llvm::Optional> getAddr, - const char *section) { + llvm::GlobalVariable * + emit(llvm::Optional> getAddr, + const char *section) { layout(); llvm::GlobalVariable *var; @@ -704,8 +704,7 @@ protected: return emit(llvm::Optional>(getAddr), section); } - llvm::GlobalVariable *emit(llvm::NoneType none, - const char *section) { + llvm::GlobalVariable *emit(llvm::NoneType none, const char *section) { return emit(llvm::Optional>(), section); } diff --git a/lib/IRGen/GenStruct.cpp b/lib/IRGen/GenStruct.cpp index ed149c3ae31..e4d96c81aaa 100644 --- a/lib/IRGen/GenStruct.cpp +++ b/lib/IRGen/GenStruct.cpp @@ -235,7 +235,7 @@ namespace { } llvm::Optional getFieldIndexIfNotEmpty(IRGenModule &IGM, - VarDecl *field) const { + VarDecl *field) const { auto &fieldInfo = getFieldInfo(field); if (fieldInfo.isEmpty()) return llvm::None; @@ -534,7 +534,9 @@ namespace { destroy(IGF, src, T, isOutlined); } - llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { return llvm::None; } + llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { + return llvm::None; + } llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF, SILType T) const { return llvm::None; } @@ -851,7 +853,9 @@ namespace { isOutlined); } - llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { return llvm::None; } + llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { + return llvm::None; + } llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF, SILType T) const { return llvm::None; } @@ -1553,8 +1557,8 @@ irgen::getPhysicalStructMemberAccessStrategy(IRGenModule &IGM, } llvm::Optional irgen::getPhysicalStructFieldIndex(IRGenModule &IGM, - SILType baseType, - VarDecl *field) { + SILType baseType, + VarDecl *field) { FOR_STRUCT_IMPL(IGM, baseType, getFieldIndexIfNotEmpty, field); } diff --git a/lib/IRGen/GenTuple.cpp b/lib/IRGen/GenTuple.cpp index d669585546d..da8cbafbec3 100644 --- a/lib/IRGen/GenTuple.cpp +++ b/lib/IRGen/GenTuple.cpp @@ -189,7 +189,7 @@ namespace { /// Return the statically-known offset of the given element. llvm::Optional getFixedElementOffset(IRGenModule &IGM, - unsigned fieldNo) const { + unsigned fieldNo) const { const TupleFieldInfo &field = asImpl().getFields()[fieldNo]; switch (field.getKind()) { case ElementLayout::Kind::Empty: @@ -205,7 +205,7 @@ namespace { } llvm::Optional getElementStructIndex(IRGenModule &IGM, - unsigned fieldNo) const { + unsigned fieldNo) const { const TupleFieldInfo &field = asImpl().getFields()[fieldNo]; if (field.isEmpty()) return llvm::None; @@ -632,14 +632,14 @@ Address irgen::projectTupleElementAddressByDynamicIndex(IRGenFunction &IGF, } llvm::Optional irgen::getFixedTupleElementOffset(IRGenModule &IGM, - SILType tupleType, - unsigned fieldNo) { + SILType tupleType, + unsigned fieldNo) { // Macro happens to work with IGM, too. FOR_TUPLE_IMPL(IGM, tupleType, getFixedElementOffset, fieldNo); } -llvm::Optional irgen::getPhysicalTupleElementStructIndex(IRGenModule &IGM, - SILType tupleType, - unsigned fieldNo) { +llvm::Optional +irgen::getPhysicalTupleElementStructIndex(IRGenModule &IGM, SILType tupleType, + unsigned fieldNo) { FOR_TUPLE_IMPL(IGM, tupleType, getElementStructIndex, fieldNo); } diff --git a/lib/IRGen/GenTuple.h b/lib/IRGen/GenTuple.h index 1a16c195710..221b2959f9d 100644 --- a/lib/IRGen/GenTuple.h +++ b/lib/IRGen/GenTuple.h @@ -56,8 +56,8 @@ namespace irgen { /// /// This API is used by RemoteAST. llvm::Optional getFixedTupleElementOffset(IRGenModule &IGM, - SILType tupleType, - unsigned fieldNo); + SILType tupleType, + unsigned fieldNo); /// Returns the index of the element in the llvm struct type which represents /// \p fieldNo in \p tupleType. @@ -65,8 +65,8 @@ namespace irgen { /// Returns None if the tuple element is an empty type and therefore has no /// corresponding element in the llvm type. llvm::Optional getPhysicalTupleElementStructIndex(IRGenModule &IGM, - SILType tupleType, - unsigned fieldNo); + SILType tupleType, + unsigned fieldNo); } // end namespace irgen } // end namespace swift diff --git a/lib/IRGen/GenType.h b/lib/IRGen/GenType.h index 8df6a90aa3c..b2b848cc79e 100644 --- a/lib/IRGen/GenType.h +++ b/lib/IRGen/GenType.h @@ -247,7 +247,8 @@ private: /// error. bool readLegacyTypeInfo(llvm::vfs::FileSystem &fs, StringRef path); - llvm::Optional getLegacyTypeInfo(NominalTypeDecl *decl) const; + llvm::Optional + getLegacyTypeInfo(NominalTypeDecl *decl) const; // Debugging aids. #ifndef NDEBUG diff --git a/lib/IRGen/GenValueWitness.cpp b/lib/IRGen/GenValueWitness.cpp index ef0bf043368..9603e5b3f09 100644 --- a/lib/IRGen/GenValueWitness.cpp +++ b/lib/IRGen/GenValueWitness.cpp @@ -960,12 +960,12 @@ valueWitnessRequiresCopyability(ValueWitness index) { /// Find a witness to the fact that a type is a value type. /// Always adds an i8*. -static void addValueWitness(IRGenModule &IGM, ConstantStructBuilder &B, - ValueWitness index, FixedPacking packing, - CanType abstractType, SILType concreteType, - const TypeInfo &concreteTI, - const llvm::Optional - boundGenericCharacteristics = llvm::None) { +static void +addValueWitness(IRGenModule &IGM, ConstantStructBuilder &B, ValueWitness index, + FixedPacking packing, CanType abstractType, + SILType concreteType, const TypeInfo &concreteTI, + const llvm::Optional + boundGenericCharacteristics = llvm::None) { auto addFunction = [&](llvm::Constant *fn) { fn = llvm::ConstantExpr::getBitCast(fn, IGM.Int8PtrTy); B.addSignedPointer(fn, IGM.getOptions().PointerAuth.ValueWitnesses, index); @@ -1198,11 +1198,12 @@ static llvm::StructType *getValueWitnessTableType(IRGenModule &IGM, } /// Collect the value witnesses for a particular type. -static void addValueWitnesses(IRGenModule &IGM, ConstantStructBuilder &B, - FixedPacking packing, CanType abstractType, - SILType concreteType, const TypeInfo &concreteTI, - const llvm::Optional - boundGenericCharacteristics = llvm::None) { +static void +addValueWitnesses(IRGenModule &IGM, ConstantStructBuilder &B, + FixedPacking packing, CanType abstractType, + SILType concreteType, const TypeInfo &concreteTI, + const llvm::Optional + boundGenericCharacteristics = llvm::None) { for (unsigned i = 0; i != NumRequiredValueWitnesses; ++i) { addValueWitness(IGM, B, ValueWitness(i), packing, abstractType, concreteType, concreteTI, boundGenericCharacteristics); diff --git a/lib/IRGen/IRABIDetailsProvider.cpp b/lib/IRGen/IRABIDetailsProvider.cpp index e4ecc1b199d..a20ea6912c1 100644 --- a/lib/IRGen/IRABIDetailsProvider.cpp +++ b/lib/IRGen/IRABIDetailsProvider.cpp @@ -41,8 +41,8 @@ using namespace swift; using namespace irgen; -static llvm::Optional getPrimitiveTypeFromLLVMType(ASTContext &ctx, - const llvm::Type *type) { +static llvm::Optional +getPrimitiveTypeFromLLVMType(ASTContext &ctx, const llvm::Type *type) { if (const auto *intType = dyn_cast(type)) { switch (intType->getBitWidth()) { case 1: diff --git a/lib/IRGen/IRGen.cpp b/lib/IRGen/IRGen.cpp index 4388dcc2ae5..d37b8b531da 100644 --- a/lib/IRGen/IRGen.cpp +++ b/lib/IRGen/IRGen.cpp @@ -1544,9 +1544,9 @@ GeneratedModule swift::performIRGeneration( const auto *SILModPtr = SILMod.get(); const auto &SILOpts = SILModPtr->getOptions(); auto desc = IRGenDescriptor::forWholeModule( - M, Opts, TBDOpts, SILOpts, SILModPtr->Types, - std::move(SILMod), ModuleName, PSPs, /*symsToEmit*/ llvm::None, - parallelOutputFilenames, outModuleHash); + M, Opts, TBDOpts, SILOpts, SILModPtr->Types, std::move(SILMod), + ModuleName, PSPs, /*symsToEmit*/ llvm::None, parallelOutputFilenames, + outModuleHash); if (Opts.shouldPerformIRGenerationInParallel() && !parallelOutputFilenames.empty() && @@ -1570,8 +1570,8 @@ performIRGeneration(FileUnit *file, const IRGenOptions &Opts, const auto *SILModPtr = SILMod.get(); const auto &SILOpts = SILModPtr->getOptions(); auto desc = IRGenDescriptor::forFile( - file, Opts, TBDOpts, SILOpts, SILModPtr->Types, - std::move(SILMod), ModuleName, PSPs, PrivateDiscriminator, + file, Opts, TBDOpts, SILOpts, SILModPtr->Types, std::move(SILMod), + ModuleName, PSPs, PrivateDiscriminator, /*symsToEmit*/ llvm::None, outModuleHash); return llvm::cantFail(file->getASTContext().evaluator(IRGenRequest{desc})); } diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index b86ba4b88a4..82c4230e611 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -795,7 +795,8 @@ private: Desc.getASTFile()); }; - static llvm::Optional getClangModule(const ModuleDecl &M) { + static llvm::Optional + getClangModule(const ModuleDecl &M) { for (auto *FU : M.getFiles()) if (auto *CMU = dyn_cast_or_null(FU)) if (auto Desc = CMU->getASTSourceDescriptor()) @@ -1393,17 +1394,17 @@ private: case TypeKind::BuiltinNativeObject: { unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); - auto PTy = - DBuilder.createPointerType(nullptr, PtrSize, 0, - /* DWARFAddressSpace */ llvm::None, MangledName); + auto PTy = DBuilder.createPointerType(nullptr, PtrSize, 0, + /* DWARFAddressSpace */ llvm::None, + MangledName); return DBuilder.createObjectPointerType(PTy); } case TypeKind::BuiltinBridgeObject: { unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); - auto PTy = - DBuilder.createPointerType(nullptr, PtrSize, 0, - /* DWARFAddressSpace */ llvm::None, MangledName); + auto PTy = DBuilder.createPointerType(nullptr, PtrSize, 0, + /* DWARFAddressSpace */ llvm::None, + MangledName); return DBuilder.createObjectPointerType(PTy); } @@ -3189,7 +3190,8 @@ void IRGenDebugInfo::emitDbgIntrinsic(IRBuilder &Builder, llvm::Value *Storage, void IRGenDebugInfo::emitGlobalVariableDeclaration( llvm::GlobalVariable *Storage, StringRef Name, StringRef LinkageName, - DebugTypeInfo DebugType, bool IsLocalToUnit, llvm::Optional Loc) { + DebugTypeInfo DebugType, bool IsLocalToUnit, + llvm::Optional Loc) { static_cast(this)->emitGlobalVariableDeclaration( Storage, Name, LinkageName, DebugType, IsLocalToUnit, Loc); } diff --git a/lib/IRGen/IRGenModule.h b/lib/IRGen/IRGenModule.h index c8fbc9b0f10..9d4523bbfd6 100644 --- a/lib/IRGen/IRGenModule.h +++ b/lib/IRGen/IRGenModule.h @@ -1421,7 +1421,7 @@ private: llvm::Constant *ObjCEmptyCachePtr = nullptr; llvm::Constant *ObjCEmptyVTablePtr = nullptr; llvm::Constant *ObjCISAMaskPtr = nullptr; - llvm::Optional ObjCRetainAutoreleasedReturnValueMarker; + llvm::Optional ObjCRetainAutoreleasedReturnValueMarker; llvm::DenseMap SwiftRootClasses; llvm::AttributeList AllocAttrs; @@ -1440,8 +1440,8 @@ private: \ llvm::Constant *FixLifetimeFn = nullptr; mutable llvm::Optional HeapPointerSpareBits; - -//--- Generic --------------------------------------------------------------- + + //--- Generic --------------------------------------------------------------- public: llvm::Constant *getFixLifetimeFn(); @@ -1573,10 +1573,9 @@ public: llvm::Constant * getAddrOfEffectiveValueWitnessTable(CanType concreteType, ConstantInit init = ConstantInit()); - llvm::Optional getAddrOfIVarInitDestroy(ClassDecl *cd, - bool isDestroyer, - bool isForeign, - ForDefinition_t forDefinition); + llvm::Optional + getAddrOfIVarInitDestroy(ClassDecl *cd, bool isDestroyer, bool isForeign, + ForDefinition_t forDefinition); void setVCallVisibility(llvm::GlobalVariable *var, llvm::GlobalObject::VCallVisibility visibility, diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp index 2152d98a7f3..0879e12aceb 100644 --- a/lib/IRGen/IRGenSIL.cpp +++ b/lib/IRGen/IRGenSIL.cpp @@ -997,12 +997,11 @@ public: /// register allocator doesn't elide the dbg.value intrinsic when /// register pressure is high. There is a trade-off to this: With /// shadow copies, we lose the precise lifetime. - llvm::Value *emitShadowCopyIfNeeded(llvm::Value *Storage, - llvm::Type *StorageType, - const SILDebugScope *Scope, - SILDebugVariable VarInfo, - bool IsAnonymous, bool WasMoved, - llvm::Optional Align = llvm::None) { + llvm::Value * + emitShadowCopyIfNeeded(llvm::Value *Storage, llvm::Type *StorageType, + const SILDebugScope *Scope, SILDebugVariable VarInfo, + bool IsAnonymous, bool WasMoved, + llvm::Optional Align = llvm::None) { // Never emit shadow copies when optimizing, or if already on the stack. No // debug info is emitted for refcounts either @@ -4015,9 +4014,9 @@ static void emitReturnInst(IRGenSILFunction &IGF, auto errorType = cast(IGF.IGM.getStorageType(errorResultType)); nativeResultsStorage.push_back(llvm::ConstantPointerNull::get(errorType)); - return emitAsyncReturn( - IGF, asyncLayout, fnType, - llvm::Optional>(nativeResultsStorage)); + return emitAsyncReturn(IGF, asyncLayout, fnType, + llvm::Optional>( + nativeResultsStorage)); } return emitAsyncReturn(IGF, asyncLayout, fnType, llvm::None); diff --git a/lib/IRGen/ScalarPairTypeInfo.h b/lib/IRGen/ScalarPairTypeInfo.h index f34f8177574..e065665abc0 100644 --- a/lib/IRGen/ScalarPairTypeInfo.h +++ b/lib/IRGen/ScalarPairTypeInfo.h @@ -195,10 +195,12 @@ public: static bool isFirstElementTrivial() { return true; } - void emitRetainFirstElement(IRGenFunction &IGF, llvm::Value *value, - llvm::Optional atomicity = llvm::None) const {} - void emitReleaseFirstElement(IRGenFunction &IGF, llvm::Value *value, - llvm::Optional atomicity = llvm::None) const {} + void emitRetainFirstElement( + IRGenFunction &IGF, llvm::Value *value, + llvm::Optional atomicity = llvm::None) const {} + void emitReleaseFirstElement( + IRGenFunction &IGF, llvm::Value *value, + llvm::Optional atomicity = llvm::None) const {} void emitAssignFirstElement(IRGenFunction &IGF, llvm::Value *value, Address valueAddr) const { IGF.Builder.CreateStore(value, valueAddr); @@ -207,10 +209,12 @@ public: static bool isSecondElementTrivial() { return true; } - void emitRetainSecondElement(IRGenFunction &IGF, llvm::Value *value, - llvm::Optional atomicity = llvm::None) const {} - void emitReleaseSecondElement(IRGenFunction &IGF, llvm::Value *value, - llvm::Optional atomicity = llvm::None) const {} + void emitRetainSecondElement( + IRGenFunction &IGF, llvm::Value *value, + llvm::Optional atomicity = llvm::None) const {} + void emitReleaseSecondElement( + IRGenFunction &IGF, llvm::Value *value, + llvm::Optional atomicity = llvm::None) const {} void emitAssignSecondElement(IRGenFunction &IGF, llvm::Value *value, Address valueAddr) const { IGF.Builder.CreateStore(value, valueAddr); diff --git a/lib/IRGen/SwiftTargetInfo.h b/lib/IRGen/SwiftTargetInfo.h index 2a2818de7f9..b01a1cc54de 100644 --- a/lib/IRGen/SwiftTargetInfo.h +++ b/lib/IRGen/SwiftTargetInfo.h @@ -109,7 +109,7 @@ public: /// The value stored in a Builtin.once predicate to indicate that an /// initialization has already happened, if known. llvm::Optional OnceDonePredicateValue = llvm::None; - + /// True if `swift_retain` and `swift_release` are no-ops when passed /// "negative" pointer values. bool SwiftRetainIgnoresNegativeValues = false; diff --git a/lib/IRGen/TBDGen.cpp b/lib/IRGen/TBDGen.cpp index bb0f6e1b7bc..a4d8c722068 100644 --- a/lib/IRGen/TBDGen.cpp +++ b/lib/IRGen/TBDGen.cpp @@ -111,7 +111,7 @@ static llvm::Optional getLinkerPlatformId(StringRef Platform) { return llvm::StringSwitch>(Platform) #define LD_PLATFORM(Name, Id) .Case(#Name, Id) #include "ldPlatformKinds.def" - .Default(llvm::None); + .Default(llvm::None); } StringRef InstallNameStore::getInstallName(LinkerPlatformId Id) const { @@ -269,7 +269,7 @@ getLinkerPlatformName(OriginallyDefinedInAttr::ActiveVersion Ver) { /// Find the most relevant introducing version of the decl stack we have visited /// so far. static llvm::Optional -getInnermostIntroVersion(ArrayRef DeclStack, PlatformKind Platform) { +getInnermostIntroVersion(ArrayRef DeclStack, PlatformKind Platform) { for (auto It = DeclStack.rbegin(); It != DeclStack.rend(); ++ It) { if (auto Result = (*It)->getIntroducedOSVersion(Platform)) return Result; diff --git a/lib/IRGen/TypeLayout.cpp b/lib/IRGen/TypeLayout.cpp index 9c57c792ef8..406bd50f6e7 100644 --- a/lib/IRGen/TypeLayout.cpp +++ b/lib/IRGen/TypeLayout.cpp @@ -1650,8 +1650,7 @@ AlignedGroupEntry::fixedAlignment(IRGenModule &IGM) const { std::max((Alignment::int_type)1, minimumAlignment)); for (auto *entry : entries) { if (!entry->fixedAlignment(IGM)) { - return *(_fixedAlignment = - llvm::Optional(llvm::None)); + return *(_fixedAlignment = llvm::Optional(llvm::None)); } currentAlignment = std::max(currentAlignment, *entry->fixedAlignment(IGM)); } @@ -2587,8 +2586,7 @@ EnumTypeLayoutEntry::fixedAlignment(IRGenModule &IGM) const { for (auto payload : cases) { auto caseAlign = payload->fixedAlignment(IGM); if (!caseAlign) { - return *(_fixedAlignment = - llvm::Optional(llvm::None)); + return *(_fixedAlignment = llvm::Optional(llvm::None)); } maxAlign = std::max(*caseAlign, maxAlign); } diff --git a/lib/IRGen/TypeLayout.h b/lib/IRGen/TypeLayout.h index 33d027e36b2..7831846adeb 100644 --- a/lib/IRGen/TypeLayout.h +++ b/lib/IRGen/TypeLayout.h @@ -441,8 +441,7 @@ private: /// None -> Not yet computed /// Optional(None) -> Not fixed size /// Optional(Size) -> Fixed Size - mutable llvm::Optional> _fixedSize = - llvm::None; + mutable llvm::Optional> _fixedSize = llvm::None; /// Memoize the value of fixedAlignment() /// None -> Not yet computed /// Optional(None) -> Not fixed Alignment @@ -454,8 +453,7 @@ private: /// None -> Not yet computed /// Optional(None) -> Not fixed xi count /// Optional(Count) -> Fixed XICount - mutable llvm::Optional> _fixedXICount = - llvm::None; + mutable llvm::Optional> _fixedXICount = llvm::None; llvm::Value *withExtraInhabitantProvidingEntry( IRGenFunction &IGF, Address addr, llvm::Type *returnType, @@ -577,8 +575,7 @@ private: /// None -> Not yet computed /// Optional(None) -> Not fixed size /// Optional(Size) -> Fixed Size - mutable llvm::Optional> _fixedSize = - llvm::None; + mutable llvm::Optional> _fixedSize = llvm::None; /// Memoize the value of fixedAlignment() /// None -> Not yet computed /// Optional(None) -> Not fixed Alignment @@ -590,8 +587,7 @@ private: /// None -> Not yet computed /// Optional(None) -> Not fixed xi count /// Optional(Count) -> Fixed XICount - mutable llvm::Optional> _fixedXICount = - llvm::None; + mutable llvm::Optional> _fixedXICount = llvm::None; llvm::Value *maxPayloadSize(IRGenFunction &IGF) const; llvm::BasicBlock *testSinglePayloadEnumContainsPayload(IRGenFunction &IGF, diff --git a/lib/IRGen/TypeLayoutDumper.cpp b/lib/IRGen/TypeLayoutDumper.cpp index 659d0b33530..b536cf96f5d 100644 --- a/lib/IRGen/TypeLayoutDumper.cpp +++ b/lib/IRGen/TypeLayoutDumper.cpp @@ -115,8 +115,8 @@ static void addYAMLTypeInfoNode(NominalTypeDecl *NTD, Result.push_back(createYAMLTypeInfoNode(NTD, IGM, fixedTI)); } -static llvm::Optional -createYAMLModuleNode(ModuleDecl *Mod, IRGenModule &IGM) { +static llvm::Optional createYAMLModuleNode(ModuleDecl *Mod, + IRGenModule &IGM) { std::vector Decls; NominalTypeWalker Walker(Decls); diff --git a/lib/Index/Index.cpp b/lib/Index/Index.cpp index 6413c1a5394..b1a5b1cc6f2 100644 --- a/lib/Index/Index.cpp +++ b/lib/Index/Index.cpp @@ -1010,7 +1010,8 @@ private: bool initFuncDeclIndexSymbol(FuncDecl *D, IndexSymbol &Info); bool initFuncRefIndexSymbol(ValueDecl *D, SourceLoc Loc, IndexSymbol &Info); bool initVarRefIndexSymbols(Expr *CurrentE, ValueDecl *D, SourceLoc Loc, - IndexSymbol &Info, llvm::Optional AccKind); + IndexSymbol &Info, + llvm::Optional AccKind); bool indexComment(const Decl *D); @@ -1839,9 +1840,9 @@ bool IndexSwiftASTWalker::initFuncRefIndexSymbol(ValueDecl *D, SourceLoc Loc, return false; } -bool IndexSwiftASTWalker::initVarRefIndexSymbols(Expr *CurrentE, ValueDecl *D, - SourceLoc Loc, IndexSymbol &Info, - llvm::Optional AccKind) { +bool IndexSwiftASTWalker::initVarRefIndexSymbols( + Expr *CurrentE, ValueDecl *D, SourceLoc Loc, IndexSymbol &Info, + llvm::Optional AccKind) { if (initIndexSymbol(D, Loc, /*IsRef=*/true, Info)) return true; diff --git a/lib/Markup/AST.cpp b/lib/Markup/AST.cpp index 7651b85f557..bf12af86377 100644 --- a/lib/Markup/AST.cpp +++ b/lib/Markup/AST.cpp @@ -15,10 +15,10 @@ /// //===----------------------------------------------------------------------===// -#include "swift/Markup/Markup.h" #include "swift/Markup/AST.h" -#include "llvm/ADT/Optional.h" +#include "swift/Markup/Markup.h" #include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" using namespace swift; using namespace markup; @@ -216,8 +216,7 @@ Strong *Strong::create(MarkupContext &MC, ParamField::ParamField(StringRef Name, ArrayRef Children) : PrivateExtension(ASTNodeKind::ParamField), NumChildren(Children.size()), - Name(Name), - Parts(llvm::None) { + Name(Name), Parts(llvm::None) { std::uninitialized_copy(Children.begin(), Children.end(), getTrailingObjects()); } diff --git a/lib/Markup/Markup.cpp b/lib/Markup/Markup.cpp index ce19f5a30e0..39c624126ab 100644 --- a/lib/Markup/Markup.cpp +++ b/lib/Markup/Markup.cpp @@ -10,14 +10,14 @@ // //===----------------------------------------------------------------------===// -#include "llvm/ADT/SmallVector.h" -#include "llvm/Support/ErrorHandling.h" -#include "swift/AST/Comment.h" -#include "swift/Markup/LineList.h" #include "swift/Markup/Markup.h" #include "cmark-gfm.h" +#include "swift/AST/Comment.h" +#include "swift/Markup/LineList.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/ErrorHandling.h" using namespace swift; using namespace markup; @@ -176,7 +176,8 @@ ParseResult parseImage(MarkupContext &MC, ParseState State) { auto NodeTitle = cmark_node_get_title(State.Node); std::string TitleString = NodeTitle ? NodeTitle : ""; - auto Title = TitleString.empty() ? llvm::None : llvm::Optional(TitleString); + auto Title = + TitleString.empty() ? llvm::None : llvm::Optional(TitleString); SmallVector Children; auto ResultState = parseChildren(MC, State, Children); diff --git a/lib/Option/SanitizerOptions.cpp b/lib/Option/SanitizerOptions.cpp index 683d7542993..af7b52644aa 100644 --- a/lib/Option/SanitizerOptions.cpp +++ b/lib/Option/SanitizerOptions.cpp @@ -47,10 +47,10 @@ static StringRef toFileName(const SanitizerKind kind) { llvm_unreachable("Unknown sanitizer"); } -static llvm::Optional parse(const char* arg) { +static llvm::Optional parse(const char *arg) { return llvm::StringSwitch>(arg) - #define SANITIZER(_, kind, name, file) .Case(#name, SanitizerKind::kind) - #include "swift/Basic/Sanitizers.def" +#define SANITIZER(_, kind, name, file) .Case(#name, SanitizerKind::kind) +#include "swift/Basic/Sanitizers.def" .Default(llvm::None); } diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp index 1268abb29bf..18d8d0e0a6d 100644 --- a/lib/Parse/ParseDecl.cpp +++ b/lib/Parse/ParseDecl.cpp @@ -339,10 +339,10 @@ void *ExportedSourceFileRequest::evaluate(Evaluator &evaluator, #endif } -void -Parser::parseSourceFileViaASTGen(SmallVectorImpl &items, - llvm::Optional &transaction, - bool suppressDiagnostics) { +void Parser::parseSourceFileViaASTGen( + SmallVectorImpl &items, + llvm::Optional &transaction, + bool suppressDiagnostics) { #if SWIFT_SWIFT_PARSER const auto &langOpts = Context.LangOpts; @@ -791,10 +791,12 @@ ParserResult Parser::parseExtendedAvailabilitySpecList( } bool Parser::parseSpecializeAttributeArguments( - swift::tok ClosingBrace, bool &DiscardAttribute, llvm::Optional &Exported, + swift::tok ClosingBrace, bool &DiscardAttribute, + llvm::Optional &Exported, llvm::Optional &Kind, swift::TrailingWhereClause *&TrailingWhereClause, - DeclNameRef &targetFunction, AvailabilityContext *SILAvailability, SmallVectorImpl &spiGroups, + DeclNameRef &targetFunction, AvailabilityContext *SILAvailability, + SmallVectorImpl &spiGroups, SmallVectorImpl &availableAttrs, size_t &typeErasedParamsCount, llvm::function_ref parseSILTargetName, @@ -2087,8 +2089,9 @@ static bool isKnownDocumentationAttributeArgument(StringRef ArgumentName) { .Default(false); } -bool Parser::parseDocumentationAttributeArgument(llvm::Optional &Metadata, - llvm::Optional &Visibility) { +bool Parser::parseDocumentationAttributeArgument( + llvm::Optional &Metadata, + llvm::Optional &Visibility) { if (Tok.isNot(tok::identifier)) { diagnose(Tok.getLoc(), diag::documentation_attr_expected_argument); return false; @@ -2114,14 +2117,14 @@ bool Parser::parseDocumentationAttributeArgument(llvm::Optional &Meta } auto ArgumentValue = Tok.getText(); llvm::Optional ParsedVisibility = - llvm::StringSwitch>(ArgumentValue) - .Case("open", AccessLevel::Open) - .Case("public", AccessLevel::Public) - .Case("package", AccessLevel::Package) - .Case("internal", AccessLevel::Internal) - .Case("private", AccessLevel::Private) - .Case("fileprivate", AccessLevel::FilePrivate) - .Default(llvm::None); + llvm::StringSwitch>(ArgumentValue) + .Case("open", AccessLevel::Open) + .Case("public", AccessLevel::Public) + .Case("package", AccessLevel::Package) + .Case("internal", AccessLevel::Internal) + .Case("private", AccessLevel::Private) + .Case("fileprivate", AccessLevel::FilePrivate) + .Default(llvm::None); if (!ParsedVisibility) { diagnose(Tok.getLoc(), diag::documentation_attr_unknown_access_level, ArgumentValue); @@ -2200,13 +2203,14 @@ Parser::parseDocumentationAttribute(SourceLoc AtLoc, SourceLoc Loc) { static llvm::Optional getMacroIntroducedDeclNameKind(Identifier name) { - return llvm::StringSwitch>(name.str()) - .Case("named", MacroIntroducedDeclNameKind::Named) - .Case("overloaded", MacroIntroducedDeclNameKind::Overloaded) - .Case("prefixed", MacroIntroducedDeclNameKind::Prefixed) - .Case("suffixed", MacroIntroducedDeclNameKind::Suffixed) - .Case("arbitrary", MacroIntroducedDeclNameKind::Arbitrary) - .Default(llvm::None); + return llvm::StringSwitch>( + name.str()) + .Case("named", MacroIntroducedDeclNameKind::Named) + .Case("overloaded", MacroIntroducedDeclNameKind::Overloaded) + .Case("prefixed", MacroIntroducedDeclNameKind::Prefixed) + .Case("suffixed", MacroIntroducedDeclNameKind::Suffixed) + .Case("arbitrary", MacroIntroducedDeclNameKind::Arbitrary) + .Default(llvm::None); } /// Determine the macro role based on its name. @@ -2460,11 +2464,9 @@ Parser::parseMacroRoleAttribute( /// /// \returns \c None if an error was diagnosed; \c Identifier() if the argument list was permissibly /// omitted; the identifier written by the user otherwise. -static llvm::Optional -parseSingleAttrOptionImpl(Parser &P, SourceLoc Loc, SourceRange &AttrRange, - StringRef AttrName, DeclAttrKind DK, - bool allowOmitted, - Diagnostic nonIdentifierDiagnostic) { +static llvm::Optional parseSingleAttrOptionImpl( + Parser &P, SourceLoc Loc, SourceRange &AttrRange, StringRef AttrName, + DeclAttrKind DK, bool allowOmitted, Diagnostic nonIdentifierDiagnostic) { SWIFT_DEFER { AttrRange = SourceRange(Loc, P.PreviousLoc); }; @@ -2529,7 +2531,7 @@ parseSingleAttrOptionIdentifier(Parser &P, SourceLoc Loc, /// /// \returns \c None if an error was diagnosed; the value corresponding to the identifier written by the /// user otherwise. -template +template static llvm::Optional parseSingleAttrOption(Parser &P, SourceLoc Loc, SourceRange &AttrRange, StringRef AttrName, DeclAttrKind DK, @@ -3462,8 +3464,8 @@ ParserStatus Parser::parseNewDeclAttribute(DeclAttributes &Attributes, return makeParserSuccess(); } - llvm::Optional value = getStringLiteralIfNotInterpolated( - Tok.getLoc(), flag); + llvm::Optional value = + getStringLiteralIfNotInterpolated(Tok.getLoc(), flag); if (!value) return makeParserSuccess(); Token stringTok = Tok; @@ -3742,19 +3744,18 @@ ParserStatus Parser::parseDeclAttribute( if (DK == DAK_Rethrows) { DK = DAK_AtRethrows; } if (DK == DAK_Reasync) { DK = DAK_AtReasync; } - auto checkInvalidAttrName = [&](StringRef invalidName, - StringRef correctName, - DeclAttrKind kind, - llvm::Optional> diag = llvm::None) { - if (DK == DAK_Count && Tok.getText() == invalidName) { - DK = kind; + auto checkInvalidAttrName = + [&](StringRef invalidName, StringRef correctName, DeclAttrKind kind, + llvm::Optional> diag = llvm::None) { + if (DK == DAK_Count && Tok.getText() == invalidName) { + DK = kind; - if (diag) { - diagnose(Tok, *diag, invalidName, correctName) - .fixItReplace(Tok.getLoc(), correctName); - } - } - }; + if (diag) { + diagnose(Tok, *diag, invalidName, correctName) + .fixItReplace(Tok.getLoc(), correctName); + } + } + }; // Check if attr is availability, and suggest available instead checkInvalidAttrName("availability", "available", DAK_Available, diag::attr_renamed); @@ -4100,18 +4101,18 @@ ParserStatus Parser::parseTypeAttribute(TypeAttributes &Attributes, // Determine which attribute it is, and diagnose it if unknown. TypeAttrKind attr = TypeAttributes::getAttrKindFromString(Tok.getText()); - auto checkInvalidAttrName = [&]( - StringRef invalidName, StringRef correctName, TypeAttrKind kind, - llvm::Optional> diag = llvm::None) { - if (attr == TAK_Count && Tok.getText() == invalidName) { - attr = kind; + auto checkInvalidAttrName = + [&](StringRef invalidName, StringRef correctName, TypeAttrKind kind, + llvm::Optional> diag = llvm::None) { + if (attr == TAK_Count && Tok.getText() == invalidName) { + attr = kind; - if (diag) { - diagnose(Tok, *diag, invalidName, correctName) - .fixItReplace(Tok.getLoc(), correctName); - } - } - }; + if (diag) { + diagnose(Tok, *diag, invalidName, correctName) + .fixItReplace(Tok.getLoc(), correctName); + } + } + }; // Historical name for @Sendable. checkInvalidAttrName( @@ -6131,14 +6132,15 @@ bool Parser::parseMemberDeclList(SourceLoc &LBLoc, SourceLoc &RBLoc, LBLoc = RBLoc = PreviousLoc; // Cache the empty result to prevent delayed parsing. - Context.evaluator.cacheOutput( - ParseMembersRequest{IDC}, FingerprintAndMembers{llvm::None, {}}); + Context.evaluator.cacheOutput(ParseMembersRequest{IDC}, + FingerprintAndMembers{llvm::None, {}}); return true; } // Record '{' '}' to the current hash, nothing else. recordTokenHash("}"); - llvm::SaveAndRestore> T(CurrentTokenHash, llvm::None); + llvm::SaveAndRestore> T(CurrentTokenHash, + llvm::None); bool HasOperatorDeclarations; bool HasNestedClassDeclarations; @@ -8333,8 +8335,8 @@ Parser::parseAbstractFunctionBodyImpl(AbstractFunctionDecl *AFD) { } } - llvm::SaveAndRestore> T(CurrentTokenHash, - StableHasher::defaultHasher()); + llvm::SaveAndRestore> T( + CurrentTokenHash, StableHasher::defaultHasher()); ParserResult Body = parseBraceItemList(diag::invalid_diagnostic); // Since we know 'Tok.is(tok::l_brace)', the body can't be null. @@ -8404,7 +8406,8 @@ void Parser::parseAbstractFunctionBody(AbstractFunctionDecl *AFD) { recordTokenHash("{"); recordTokenHash("}"); - llvm::SaveAndRestore> T(CurrentTokenHash, llvm::None); + llvm::SaveAndRestore> T(CurrentTokenHash, + llvm::None); // If we can delay parsing this body, or this is the first pass of code // completion, skip until the end. If we encounter a code completion token @@ -9811,12 +9814,12 @@ Parser::parseDeclPrecedenceGroup(ParseDeclOptions flags, return abortBody(); } - auto parsedAssociativity - = llvm::StringSwitch>(Tok.getText()) - .Case("none", Associativity::None) - .Case("left", Associativity::Left) - .Case("right", Associativity::Right) - .Default(llvm::None); + auto parsedAssociativity = + llvm::StringSwitch>(Tok.getText()) + .Case("none", Associativity::None) + .Case("left", Associativity::Left) + .Case("right", Associativity::Right) + .Default(llvm::None); if (!parsedAssociativity) { diagnose(Tok, diag::expected_precedencegroup_associativity); diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp index ef45c607ecc..5ecb4a96ef6 100644 --- a/lib/Parse/ParseExpr.cpp +++ b/lib/Parse/ParseExpr.cpp @@ -1414,7 +1414,8 @@ Parser::parseExprPostfixSuffix(ParserResult Result, bool isExprBasic, // it as a "postfix ifconfig expression". bool isPostfixIfConfigExpr = false; { - llvm::SaveAndRestore> H(CurrentTokenHash, llvm::None); + llvm::SaveAndRestore> H(CurrentTokenHash, + llvm::None); Parser::BacktrackingScope Backtrack(*this); // Skip to the first body. We may need to skip multiple '#if' directives // since we support nested '#if's. e.g. @@ -1882,7 +1883,7 @@ ParserResult Parser::parseExprPrimary(Diag<> ID, bool isExprBasic) { } if (peekToken().is(tok::code_complete) && Tok.getLoc().getAdvancedLoc(1) == peekToken().getLoc()) { - return parseExprPoundCodeCompletion(/*ParentKind*/llvm::None); + return parseExprPoundCodeCompletion(/*ParentKind*/ llvm::None); } return parseExprMacroExpansion(isExprBasic); @@ -2414,7 +2415,7 @@ Expr *Parser::parseExprEditorPlaceholder(Token PlaceholderTok, auto parseTypeForPlaceholder = [&]() -> std::pair { llvm::Optional DataOpt = - swift::parseEditorPlaceholder(PlaceholderTok.getText()); + swift::parseEditorPlaceholder(PlaceholderTok.getText()); if (!DataOpt) return {nullptr, nullptr}; StringRef TypeStr = DataOpt->Type; @@ -3598,8 +3599,8 @@ ParserResult Parser::parseExprCollection() { /// parseExprCollectionElement - Parse an element for collection expr. /// -/// If \p isDictionary is \c llvm::None, it's set to \c true if the element is for -/// dictionary literal, or \c false otherwise. +/// If \p isDictionary is \c llvm::None, it's set to \c true if the element is +/// for dictionary literal, or \c false otherwise. ParserResult Parser::parseExprCollectionElement(llvm::Optional &isDictionary) { auto Element = parseExpr(isDictionary.has_value() && *isDictionary diff --git a/lib/Parse/ParseIfConfig.cpp b/lib/Parse/ParseIfConfig.cpp index b52f0f120f0..ef10f8fdde5 100644 --- a/lib/Parse/ParseIfConfig.cpp +++ b/lib/Parse/ParseIfConfig.cpp @@ -32,13 +32,13 @@ using namespace swift; namespace { /// Get PlatformConditionKind from platform condition name. -static -llvm::Optional getPlatformConditionKind(StringRef Name) { +static llvm::Optional +getPlatformConditionKind(StringRef Name) { return llvm::StringSwitch>(Name) #define PLATFORM_CONDITION(LABEL, IDENTIFIER) \ .Case(IDENTIFIER, PlatformConditionKind::LABEL) #include "swift/AST/PlatformConditionKinds.def" - .Default(llvm::None); + .Default(llvm::None); } /// Get platform condition name from PlatformConditionKind. @@ -58,7 +58,8 @@ static StringRef extractExprSource(SourceManager &SM, Expr *E) { return SM.extractText(Range); } -static bool isValidPrefixUnaryOperator(llvm::Optional UnaryOperator) { +static bool +isValidPrefixUnaryOperator(llvm::Optional UnaryOperator) { return UnaryOperator != llvm::None && (UnaryOperator.value() == ">=" || UnaryOperator.value() == "<"); } @@ -327,7 +328,8 @@ public: *KindName == "_compiler_version") { auto PUE = dyn_cast(Arg); llvm::Optional PrefixName = - PUE ? getDeclRefStr(PUE->getFn(), DeclRefKind::PrefixOperator) : llvm::None; + PUE ? getDeclRefStr(PUE->getFn(), DeclRefKind::PrefixOperator) + : llvm::None; if (!isValidPrefixUnaryOperator(PrefixName)) { D.diagnose( Arg->getLoc(), diag::unsupported_platform_condition_argument, @@ -792,7 +794,8 @@ Result Parser::parseIfConfigRaw( SourceMgr.getIDEInspectionTargetBufferID() == L->getBufferID() && SourceMgr.isBeforeInBuffer(Tok.getLoc(), SourceMgr.getIDEInspectionTargetLoc())) { - llvm::SaveAndRestore> H(CurrentTokenHash, llvm::None); + llvm::SaveAndRestore> H(CurrentTokenHash, + llvm::None); BacktrackingScope backtrack(*this); do { auto startLoc = Tok.getLoc(); diff --git a/lib/Parse/ParseStmt.cpp b/lib/Parse/ParseStmt.cpp index 44b5bbbb910..3d759dd2a08 100644 --- a/lib/Parse/ParseStmt.cpp +++ b/lib/Parse/ParseStmt.cpp @@ -845,7 +845,7 @@ ParserResult Parser::parseStmtYield(SourceLoc tryLoc) { auto result = makeParserResult( YieldStmt::create(Context, yieldLoc, SourceLoc(), cce, SourceLoc())); if (CodeCompletionCallbacks) { - CodeCompletionCallbacks->completeYieldStmt(cce, /*index=*/ llvm::None); + CodeCompletionCallbacks->completeYieldStmt(cce, /*index=*/llvm::None); } result.setHasCodeCompletionAndIsError(); consumeToken(); @@ -2232,11 +2232,11 @@ ParserResult Parser::parseStmtCatch() { } return makeParserResult( - status, CaseStmt::create(Context, CaseParentKind::DoCatch, catchLoc, - caseLabelItems, - /*UnknownAttrLoc*/ SourceLoc(), - bodyResult.get()->getStartLoc(), - bodyResult.get(), caseBodyDecls, llvm::None, nullptr)); + status, + CaseStmt::create( + Context, CaseParentKind::DoCatch, catchLoc, caseLabelItems, + /*UnknownAttrLoc*/ SourceLoc(), bodyResult.get()->getStartLoc(), + bodyResult.get(), caseBodyDecls, llvm::None, nullptr)); } static bool isStmtForCStyle(Parser &P) { @@ -2743,8 +2743,8 @@ ParserResult Parser::parseStmtCase(bool IsActive) { return makeParserResult( Status, CaseStmt::create(Context, CaseParentKind::Switch, CaseLoc, CaseLabelItems, - UnknownAttrLoc, ColonLoc, Body, CaseBodyDecls, llvm::None, - FallthroughFinder::findFallthrough(Body))); + UnknownAttrLoc, ColonLoc, Body, CaseBodyDecls, + llvm::None, FallthroughFinder::findFallthrough(Body))); } /// stmt-pound-assert: diff --git a/lib/Parse/ParseType.cpp b/lib/Parse/ParseType.cpp index a38a86e8e77..97c88da9bbd 100644 --- a/lib/Parse/ParseType.cpp +++ b/lib/Parse/ParseType.cpp @@ -491,8 +491,9 @@ ParserResult Parser::parseTypeScalar( MutableArrayRef patternSubsTypes; if (isInSILMode()) { auto parseSubstitutions = - [&](MutableArrayRef &subs) -> llvm::Optional { - if (!consumeIf(tok::kw_for)) return llvm::None; + [&](MutableArrayRef &subs) -> llvm::Optional { + if (!consumeIf(tok::kw_for)) + return llvm::None; if (!startsWithLess(Tok)) { diagnose(Tok, diag::sil_function_subst_expected_l_angle); diff --git a/lib/Parse/ParseVersion.cpp b/lib/Parse/ParseVersion.cpp index a0c3b4de1c4..6daf483401e 100644 --- a/lib/Parse/ParseVersion.cpp +++ b/lib/Parse/ParseVersion.cpp @@ -176,9 +176,9 @@ llvm::Optional VersionParser::parseCompilerVersionString( return isValidVersion ? llvm::Optional(CV) : llvm::None; } -llvm::Optional VersionParser::parseVersionString(StringRef VersionString, - SourceLoc Loc, - DiagnosticEngine *Diags) { +llvm::Optional +VersionParser::parseVersionString(StringRef VersionString, SourceLoc Loc, + DiagnosticEngine *Diags) { Version TheVersion; SmallString<16> digits; llvm::raw_svector_ostream OS(digits); diff --git a/lib/Parse/Parser.cpp b/lib/Parse/Parser.cpp index 89f38d7798c..2156a51be1d 100644 --- a/lib/Parse/Parser.cpp +++ b/lib/Parse/Parser.cpp @@ -1077,8 +1077,7 @@ Parser::parseList(tok RightK, SourceLoc LeftLoc, SourceLoc &RightLoc, } llvm::Optional -Parser::getStringLiteralIfNotInterpolated(SourceLoc Loc, - StringRef DiagText) { +Parser::getStringLiteralIfNotInterpolated(SourceLoc Loc, StringRef DiagText) { assert(Tok.is(tok::string_literal)); // FIXME: Support extended escaping string literal. diff --git a/lib/PrintAsClang/ClangSyntaxPrinter.cpp b/lib/PrintAsClang/ClangSyntaxPrinter.cpp index a69b61a4495..bb0b4ce3d17 100644 --- a/lib/PrintAsClang/ClangSyntaxPrinter.cpp +++ b/lib/PrintAsClang/ClangSyntaxPrinter.cpp @@ -202,7 +202,8 @@ void ClangSyntaxPrinter::printInlineForHelperFunction() const { } void ClangSyntaxPrinter::printNullability( - llvm::Optional kind, NullabilityPrintKind printKind) const { + llvm::Optional kind, + NullabilityPrintKind printKind) const { if (!kind) return; diff --git a/lib/PrintAsClang/DeclAndTypePrinter.cpp b/lib/PrintAsClang/DeclAndTypePrinter.cpp index b95e07f43a1..4661cd62938 100644 --- a/lib/PrintAsClang/DeclAndTypePrinter.cpp +++ b/lib/PrintAsClang/DeclAndTypePrinter.cpp @@ -975,10 +975,10 @@ private: return true; } - Type getForeignResultType(AbstractFunctionDecl *AFD, - AnyFunctionType *methodTy, - llvm::Optional asyncConvention, - llvm::Optional errorConvention) { + Type + getForeignResultType(AbstractFunctionDecl *AFD, AnyFunctionType *methodTy, + llvm::Optional asyncConvention, + llvm::Optional errorConvention) { // A foreign error convention can affect the result type as seen in // Objective-C. if (errorConvention) { @@ -1402,10 +1402,10 @@ private: // Print out the function signature for a @_cdecl function. void printAbstractFunctionAsCFunction(FuncDecl *FD) { printDocumentationComment(FD); - llvm::Optional asyncConvention - = FD->getForeignAsyncConvention(); - llvm::Optional errorConvention - = FD->getForeignErrorConvention(); + llvm::Optional asyncConvention = + FD->getForeignAsyncConvention(); + llvm::Optional errorConvention = + FD->getForeignErrorConvention(); assert(!FD->getGenericSignature() && "top-level generic functions not supported here"); auto funcTy = FD->getInterfaceType()->castTo(); @@ -1492,7 +1492,8 @@ private: // Print out the extern C Swift ABI function signature. llvm::Optional printSwiftABIFunctionSignatureAsCxxFunction( - AbstractFunctionDecl *FD, llvm::Optional givenFuncType = llvm::None, + AbstractFunctionDecl *FD, + llvm::Optional givenFuncType = llvm::None, llvm::Optional selfTypeDeclContext = llvm::None) { assert(outputLang == OutputLanguageMode::Cxx); llvm::Optional asyncConvention = @@ -2254,7 +2255,8 @@ private: os << " */"; } - void visitErrorType(ErrorType *Ty, llvm::Optional optionalKind) { + void visitErrorType(ErrorType *Ty, + llvm::Optional optionalKind) { os << "/* error */id"; } @@ -2303,7 +2305,7 @@ private: } void visitTypeAliasType(TypeAliasType *aliasTy, - llvm::Optional optionalKind) { + llvm::Optional optionalKind) { const TypeAliasDecl *alias = aliasTy->getDecl(); auto genericArgs = aliasTy->getDirectGenericArgs(); @@ -2389,8 +2391,9 @@ private: /// If \p BGT represents a generic struct used to import Clang types, print /// it out. - bool printIfKnownGenericStruct(const BoundGenericStructType *BGT, - llvm::Optional optionalKind) { + bool + printIfKnownGenericStruct(const BoundGenericStructType *BGT, + llvm::Optional optionalKind) { auto bgsTy = Type(const_cast(BGT)); if (bgsTy->isUnmanaged()) { @@ -2423,8 +2426,9 @@ private: return true; } - void visitBoundGenericStructType(BoundGenericStructType *BGT, - llvm::Optional optionalKind) { + void + visitBoundGenericStructType(BoundGenericStructType *BGT, + llvm::Optional optionalKind) { // Handle bridged types. if (printIfObjCBridgeable(BGT->getDecl(), BGT->getGenericArgs(), optionalKind)) @@ -2442,14 +2446,15 @@ private: void printGenericArgs(ArrayRef genericArgs) { os << '<'; - interleave(genericArgs, - [this](Type t) { print(t, llvm::None); }, - [this] { os << ", "; }); + interleave( + genericArgs, [this](Type t) { print(t, llvm::None); }, + [this] { os << ", "; }); os << '>'; } - void visitBoundGenericClassType(BoundGenericClassType *BGT, - llvm::Optional optionalKind) { + void + visitBoundGenericClassType(BoundGenericClassType *BGT, + llvm::Optional optionalKind) { // Only handle imported ObjC generics. auto CD = BGT->getClassOrBoundGenericClass(); if (!CD->isObjC()) @@ -2484,7 +2489,8 @@ private: visitType(BGT, optionalKind); } - void visitEnumType(EnumType *ET, llvm::Optional optionalKind) { + void visitEnumType(EnumType *ET, + llvm::Optional optionalKind) { const EnumDecl *ED = ET->getDecl(); // Handle bridged types. @@ -2495,7 +2501,8 @@ private: os << getNameForObjC(ED); } - void visitClassType(ClassType *CT, llvm::Optional optionalKind) { + void visitClassType(ClassType *CT, + llvm::Optional optionalKind) { const ClassDecl *CD = CT->getClassOrBoundGenericClass(); assert(CD->isObjC()); auto clangDecl = dyn_cast_or_null(CD->getClangDecl()); @@ -2555,8 +2562,9 @@ private: visitExistentialType(PT, optionalKind, /*isMetatype=*/false); } - void visitProtocolCompositionType(ProtocolCompositionType *PCT, - llvm::Optional optionalKind) { + void + visitProtocolCompositionType(ProtocolCompositionType *PCT, + llvm::Optional optionalKind) { visitExistentialType(PCT, optionalKind, /*isMetatype=*/false); } @@ -2565,8 +2573,9 @@ private: visitPart(ET->getConstraintType(), optionalKind); } - void visitExistentialMetatypeType(ExistentialMetatypeType *MT, - llvm::Optional optionalKind) { + void + visitExistentialMetatypeType(ExistentialMetatypeType *MT, + llvm::Optional optionalKind) { Type instanceTy = MT->getInstanceType(); visitExistentialType(instanceTy, optionalKind, /*isMetatype=*/true); } @@ -2584,8 +2593,9 @@ private: } } - void visitGenericTypeParamType(GenericTypeParamType *type, - llvm::Optional optionalKind) { + void + visitGenericTypeParamType(GenericTypeParamType *type, + llvm::Optional optionalKind) { const GenericTypeParamDecl *decl = type->getDecl(); assert(decl && "can't print canonicalized GenericTypeParamType"); @@ -2670,25 +2680,30 @@ private: os << ")"; } - void visitTupleType(TupleType *TT, llvm::Optional optionalKind) { + void visitTupleType(TupleType *TT, + llvm::Optional optionalKind) { assert(TT->getNumElements() == 0); os << "void"; } - void visitPackType(PackType *PT, llvm::Optional optionalKind) { + void visitPackType(PackType *PT, + llvm::Optional optionalKind) { assert(PT->getNumElements() == 0); os << "void"; } - void visitPackExpansionType(PackExpansionType *PET, llvm::Optional optionalKind) { + void visitPackExpansionType(PackExpansionType *PET, + llvm::Optional optionalKind) { os << "void"; } - void visitPackElementType(PackElementType *PET, llvm::Optional optionalKind) { + void visitPackElementType(PackElementType *PET, + llvm::Optional optionalKind) { llvm_unreachable("Not implemented"); } - void visitParenType(ParenType *PT, llvm::Optional optionalKind) { + void visitParenType(ParenType *PT, + llvm::Optional optionalKind) { visitPart(PT->getSinglyDesugaredType(), optionalKind); } @@ -2703,8 +2718,9 @@ private: os << "instancetype"; } - void visitReferenceStorageType(ReferenceStorageType *RST, - llvm::Optional optionalKind) { + void + visitReferenceStorageType(ReferenceStorageType *RST, + llvm::Optional optionalKind) { visitPart(RST->getReferentType(), optionalKind); } diff --git a/lib/PrintAsClang/PrimitiveTypeMapping.cpp b/lib/PrintAsClang/PrimitiveTypeMapping.cpp index 1cdd8146ad2..be6ac9443d6 100644 --- a/lib/PrintAsClang/PrimitiveTypeMapping.cpp +++ b/lib/PrintAsClang/PrimitiveTypeMapping.cpp @@ -22,22 +22,16 @@ void PrimitiveTypeMapping::initialize(ASTContext &ctx) { assert(mappedTypeNames.empty() && "expected empty type map"); #define MAP(SWIFT_NAME, CLANG_REPR, NEEDS_NULLABILITY) \ mappedTypeNames[{ctx.StdlibModuleName, ctx.getIdentifier(#SWIFT_NAME)}] = { \ - CLANG_REPR, \ - llvm::Optional(CLANG_REPR), \ - llvm::Optional(CLANG_REPR), \ - NEEDS_NULLABILITY \ - } + CLANG_REPR, llvm::Optional(CLANG_REPR), \ + llvm::Optional(CLANG_REPR), NEEDS_NULLABILITY} #define MAP_C(SWIFT_NAME, OBJC_REPR, C_REPR, NEEDS_NULLABILITY) \ mappedTypeNames[{ctx.StdlibModuleName, ctx.getIdentifier(#SWIFT_NAME)}] = { \ - OBJC_REPR, \ - llvm::Optional(C_REPR), \ - llvm::Optional(C_REPR), \ - NEEDS_NULLABILITY \ - } + OBJC_REPR, llvm::Optional(C_REPR), \ + llvm::Optional(C_REPR), NEEDS_NULLABILITY} #define MAP_CXX(SWIFT_NAME, OBJC_REPR, C_REPR, CXX_REPR, NEEDS_NULLABILITY) \ mappedTypeNames[{ctx.StdlibModuleName, ctx.getIdentifier(#SWIFT_NAME)}] = { \ - OBJC_REPR, llvm::Optional(C_REPR), llvm::Optional(CXX_REPR), \ - NEEDS_NULLABILITY} + OBJC_REPR, llvm::Optional(C_REPR), \ + llvm::Optional(CXX_REPR), NEEDS_NULLABILITY} MAP(CBool, "bool", false); @@ -95,11 +89,11 @@ void PrimitiveTypeMapping::initialize(ASTContext &ctx) { mappedTypeNames[{ctx.Id_Darwin, ctx.getIdentifier("DarwinBoolean")}] = { "Boolean", llvm::None, llvm::None, false}; - mappedTypeNames[{ctx.Id_CoreGraphics, ctx.Id_CGFloat}] = {"CGFloat", llvm::None, - llvm::None, false}; + mappedTypeNames[{ctx.Id_CoreGraphics, ctx.Id_CGFloat}] = { + "CGFloat", llvm::None, llvm::None, false}; - mappedTypeNames[{ctx.Id_CoreFoundation, ctx.Id_CGFloat}] = {"CGFloat", llvm::None, - llvm::None, false}; + mappedTypeNames[{ctx.Id_CoreFoundation, ctx.Id_CGFloat}] = { + "CGFloat", llvm::None, llvm::None, false}; // Use typedefs we set up for SIMD vector types. #define MAP_SIMD_TYPE(BASENAME, _, __) \ diff --git a/lib/PrintAsClang/PrintClangFunction.cpp b/lib/PrintAsClang/PrintClangFunction.cpp index ec15e617147..d7b0b1078b5 100644 --- a/lib/PrintAsClang/PrintClangFunction.cpp +++ b/lib/PrintAsClang/PrintClangFunction.cpp @@ -235,9 +235,9 @@ public: return ClangRepresentation::unsupported; } - ClangRepresentation visitTupleType(TupleType *TT, - llvm::Optional optionalKind, - bool isInOutParam) { + ClangRepresentation + visitTupleType(TupleType *TT, llvm::Optional optionalKind, + bool isInOutParam) { if (TT->getNumElements() > 0) // FIXME: Handle non-void type. return ClangRepresentation::unsupported; @@ -259,16 +259,17 @@ public: return visitSugarType(aliasTy, optionalKind, isInOutParam); } - ClangRepresentation visitSugarType(SugarType *sugarTy, - llvm::Optional optionalKind, - bool isInOutParam) { + ClangRepresentation + visitSugarType(SugarType *sugarTy, + llvm::Optional optionalKind, + bool isInOutParam) { return visitPart(sugarTy->getSinglyDesugaredType(), optionalKind, isInOutParam); } - ClangRepresentation visitClassType(ClassType *CT, - llvm::Optional optionalKind, - bool isInOutParam) { + ClangRepresentation + visitClassType(ClassType *CT, llvm::Optional optionalKind, + bool isInOutParam) { auto *cd = CT->getDecl(); if (cd->hasClangNode()) { ClangSyntaxPrinter(os).printClangTypeReference(cd->getClangDecl()); @@ -302,16 +303,16 @@ public: return ClangRepresentation::representable; } - ClangRepresentation visitEnumType(EnumType *ET, - llvm::Optional optionalKind, - bool isInOutParam) { + ClangRepresentation + visitEnumType(EnumType *ET, llvm::Optional optionalKind, + bool isInOutParam) { return visitValueType(ET, ET->getNominalOrBoundGenericNominal(), optionalKind, isInOutParam); } - ClangRepresentation visitStructType(StructType *ST, - llvm::Optional optionalKind, - bool isInOutParam) { + ClangRepresentation + visitStructType(StructType *ST, llvm::Optional optionalKind, + bool isInOutParam) { return visitValueType(ST, ST->getNominalOrBoundGenericNominal(), optionalKind, isInOutParam); } @@ -333,11 +334,10 @@ public: return result; } - ClangRepresentation visitValueType(TypeBase *type, - const NominalTypeDecl *decl, - llvm::Optional optionalKind, - bool isInOutParam, - ArrayRef genericArgs = {}) { + ClangRepresentation + visitValueType(TypeBase *type, const NominalTypeDecl *decl, + llvm::Optional optionalKind, + bool isInOutParam, ArrayRef genericArgs = {}) { assert(isa(decl) || isa(decl)); // Handle known type names. @@ -475,9 +475,10 @@ public: return visitPart(ds->getSelfType(), optionalKind, isInOutParam); } - ClangRepresentation visitMetatypeType(MetatypeType *mt, - llvm::Optional optionalKind, - bool isInOutParam) { + ClangRepresentation + visitMetatypeType(MetatypeType *mt, + llvm::Optional optionalKind, + bool isInOutParam) { if (typeUseKind == FunctionSignatureTypeUse::TypeReference) return visitPart(mt->getInstanceType(), optionalKind, isInOutParam); return ClangRepresentation::unsupported; @@ -1234,8 +1235,9 @@ void DeclAndTypeClangFunctionPrinter::printCxxThunkBody( os, cPrologueOS, typeMapping, OutputLanguageMode::Cxx, interopContext, delegate, moduleContext, declPrinter, FunctionSignatureTypeUse::TypeReference); - auto result = typePrinter.visit(metadataSrcParam.getType(), llvm::None, - /*isInOut=*/false); + auto result = + typePrinter.visit(metadataSrcParam.getType(), llvm::None, + /*isInOut=*/false); assert(!result.isUnsupported()); os << ">::getTypeMetadata()"; }, @@ -1262,13 +1264,13 @@ void DeclAndTypeClangFunctionPrinter::printCxxThunkBody( if (classDecl->hasClangNode()) { assert(!isa(classDecl->getClangDecl())); os << "return "; - printCallToCFunc(/*additionalParam=*/ llvm::None); + printCallToCFunc(/*additionalParam=*/llvm::None); os << ";\n"; return; } ClangClassTypePrinter::printClassTypeReturnScaffold( os, classDecl, moduleContext, - [&]() { printCallToCFunc(/*additionalParam=*/ llvm::None); }); + [&]() { printCallToCFunc(/*additionalParam=*/llvm::None); }); return; } if (auto *decl = resultTy->getNominalOrBoundGenericNominal()) { @@ -1311,7 +1313,7 @@ void DeclAndTypeClangFunctionPrinter::printCxxThunkBody( ClangSyntaxPrinter(os).printIdentifier( cast(classDecl->getClangDecl())->getName()); os << " *)(__bridge void *)"; - printCallToCFunc(/*additionalParam=*/ llvm::None); + printCallToCFunc(/*additionalParam=*/llvm::None); os << ";\n"; return; } @@ -1325,7 +1327,7 @@ void DeclAndTypeClangFunctionPrinter::printCxxThunkBody( // If the function can't throw just return its value result. else if (!hasThrows) os << " return "; - printCallToCFunc(/*additionalParam=*/ llvm::None); + printCallToCFunc(/*additionalParam=*/llvm::None); os << ";\n"; // Create the condition and the statement to throw an exception. diff --git a/lib/PrintAsClang/PrintClangFunction.h b/lib/PrintAsClang/PrintClangFunction.h index 0a871bcd49e..039a4691af3 100644 --- a/lib/PrintAsClang/PrintClangFunction.h +++ b/lib/PrintAsClang/PrintClangFunction.h @@ -114,7 +114,8 @@ public: const ModuleDecl *moduleContext, Type resultTy, const ParameterList *params, bool hasThrows = false, const AnyFunctionType *funcType = nullptr, bool isStaticMethod = false, - llvm::Optional dispatchInfo = llvm::None); + llvm::Optional dispatchInfo = + llvm::None); /// Print the Swift method as C++ method declaration/definition, including /// constructors. diff --git a/lib/Refactoring/Refactoring.cpp b/lib/Refactoring/Refactoring.cpp index e0d2a4a509f..c7af2a25e77 100644 --- a/lib/Refactoring/Refactoring.cpp +++ b/lib/Refactoring/Refactoring.cpp @@ -639,7 +639,8 @@ struct RenameInfo { }; static llvm::Optional -renameAvailabilityInfo(const ValueDecl *VD, llvm::Optional RefInfo) { +renameAvailabilityInfo(const ValueDecl *VD, + llvm::Optional RefInfo) { RefactorAvailableKind AvailKind = RefactorAvailableKind::Available; if (getRelatedSystemDecl(VD)) { AvailKind = RefactorAvailableKind::Unavailable_system_symbol; @@ -721,7 +722,8 @@ renameAvailabilityInfo(const ValueDecl *VD, llvm::Optional RefInf /// Given a cursor, return the decl and its rename availability. \c None if /// the cursor did not resolve to a decl or it resolved to a decl that we do /// not allow renaming on. -static llvm::Optional getRenameInfo(ResolvedCursorInfoPtr cursorInfo) { +static llvm::Optional +getRenameInfo(ResolvedCursorInfoPtr cursorInfo) { auto valueCursor = dyn_cast(cursorInfo); if (!valueCursor) return llvm::None; @@ -739,7 +741,8 @@ static llvm::Optional getRenameInfo(ResolvedCursorInfoPtr cursorInfo valueCursor->isKeywordArgument()}; } - llvm::Optional info = renameAvailabilityInfo(VD, refInfo); + llvm::Optional info = + renameAvailabilityInfo(VD, refInfo); if (!info) return llvm::None; @@ -798,8 +801,8 @@ private: return true; } - llvm::Optional indexSymbolToRenameLoc(const index::IndexSymbol &symbol, - StringRef NewName); + llvm::Optional + indexSymbolToRenameLoc(const index::IndexSymbol &symbol, StringRef NewName); private: StringRef USR; @@ -990,10 +993,9 @@ static void analyzeRenameScope(ValueDecl *VD, Scopes.push_back(Scope); } -static llvm::Optional localRenames(SourceFile *SF, - SourceLoc startLoc, - StringRef preferredName, - DiagnosticEngine &diags) { +static llvm::Optional +localRenames(SourceFile *SF, SourceLoc startLoc, StringRef preferredName, + DiagnosticEngine &diags) { auto cursorInfo = evaluateOrDefault(SF->getASTContext().evaluator, CursorInfoRequest{CursorInfoOwner(SF, startLoc)}, @@ -1356,7 +1358,8 @@ getNotableRegions(StringRef SourceText, unsigned NameOffset, StringRef Name, UnresolvedLoc UnresoledName{NameLoc, true}; NameMatcher Matcher(*Instance->getPrimarySourceFile()); - auto Resolved = Matcher.resolve(llvm::makeArrayRef(UnresoledName), llvm::None); + auto Resolved = + Matcher.resolve(llvm::makeArrayRef(UnresoledName), llvm::None); assert(!Resolved.empty() && "Failed to resolve generated func name loc"); RenameLoc RenameConfig = { @@ -1728,27 +1731,25 @@ bool RefactoringActionExtractExprBase::performChange() { EndOffset = DeclBuffer.size(); OS << TyBuffer.str() << " = " << RangeInfo.ContentRange.str() << "\n"; - NoteRegion DeclNameRegion{ - RefactoringRangeKind::BaseName, - /*StartLine=*/1, /*StartColumn=*/StartOffset + 1, - /*EndLine=*/1, /*EndColumn=*/EndOffset + 1, - /*ArgIndex*/llvm::None - }; + NoteRegion DeclNameRegion{RefactoringRangeKind::BaseName, + /*StartLine=*/1, + /*StartColumn=*/StartOffset + 1, + /*EndLine=*/1, + /*EndColumn=*/EndOffset + 1, + /*ArgIndex*/ llvm::None}; // Perform code change. EditConsumer.accept(SM, InsertLoc, DeclBuffer.str(), {DeclNameRegion}); // Replace all occurrences of the extracted expression. for (auto *E : AllExpressions) { - EditConsumer.accept(SM, - Lexer::getCharSourceRangeFromSourceRange(SM, E->getSourceRange()), - PreferredName, - {{ - RefactoringRangeKind::BaseName, - /*StartLine=*/1, /*StartColumn-*/1, /*EndLine=*/1, - /*EndColumn=*/static_cast(PreferredName.size() + 1), - /*ArgIndex*/llvm::None - }}); + EditConsumer.accept( + SM, Lexer::getCharSourceRangeFromSourceRange(SM, E->getSourceRange()), + PreferredName, + {{RefactoringRangeKind::BaseName, + /*StartLine=*/1, /*StartColumn-*/ 1, /*EndLine=*/1, + /*EndColumn=*/static_cast(PreferredName.size() + 1), + /*ArgIndex*/ llvm::None}}); } return false; } @@ -8616,8 +8617,9 @@ bool RefactoringActionAddAsyncWrapper::performChange() { /// Retrieve the macro expansion buffer for the given macro expansion /// expression. -static llvm::Optional getMacroExpansionBuffer( - SourceManager &sourceMgr, MacroExpansionExpr *expansion) { +static llvm::Optional +getMacroExpansionBuffer(SourceManager &sourceMgr, + MacroExpansionExpr *expansion) { return evaluateOrDefault( expansion->getDeclContext()->getASTContext().evaluator, ExpandMacroExpansionExprRequest{expansion}, {}); diff --git a/lib/SIL/IR/AbstractionPattern.cpp b/lib/SIL/IR/AbstractionPattern.cpp index 2cbf53b185e..b4bbdbafc64 100644 --- a/lib/SIL/IR/AbstractionPattern.cpp +++ b/lib/SIL/IR/AbstractionPattern.cpp @@ -125,8 +125,8 @@ AbstractionPattern TypeConverter::getAbstractionPattern(EnumElementDecl *decl) { AbstractionPattern::EncodedForeignInfo AbstractionPattern::EncodedForeignInfo::encode( - const llvm::Optional &foreignError, - const llvm::Optional &foreignAsync) { + const llvm::Optional &foreignError, + const llvm::Optional &foreignAsync) { // Foreign async convention takes precedence. if (foreignAsync.has_value()) { return EncodedForeignInfo(EncodedForeignInfo::Async, @@ -144,20 +144,18 @@ AbstractionPattern::EncodedForeignInfo::encode( } } -AbstractionPattern -AbstractionPattern::getObjCMethod(CanType origType, - const clang::ObjCMethodDecl *method, - const llvm::Optional &foreignError, - const llvm::Optional &foreignAsync) { +AbstractionPattern AbstractionPattern::getObjCMethod( + CanType origType, const clang::ObjCMethodDecl *method, + const llvm::Optional &foreignError, + const llvm::Optional &foreignAsync) { auto errorInfo = EncodedForeignInfo::encode(foreignError, foreignAsync); return getObjCMethod(origType, method, errorInfo); } -AbstractionPattern -AbstractionPattern::getCurriedObjCMethod(CanType origType, - const clang::ObjCMethodDecl *method, - const llvm::Optional &foreignError, - const llvm::Optional &foreignAsync) { +AbstractionPattern AbstractionPattern::getCurriedObjCMethod( + CanType origType, const clang::ObjCMethodDecl *method, + const llvm::Optional &foreignError, + const llvm::Optional &foreignAsync) { auto errorInfo = EncodedForeignInfo::encode(foreignError, foreignAsync); return getCurriedObjCMethod(origType, method, errorInfo); } @@ -482,8 +480,10 @@ bool AbstractionPattern::doesTupleContainPackExpansionType() const { llvm::Optional AbstractionPattern::getVanishingTupleElementPatternType() const { - if (!isTuple()) return llvm::None; - if (!GenericSubs) return llvm::None; + if (!isTuple()) + return llvm::None; + if (!GenericSubs) + return llvm::None; // Substitution causes tuples to vanish when substituting the elements // produces a singleton tuple and it didn't start that way. @@ -500,7 +500,8 @@ AbstractionPattern::getVanishingTupleElementPatternType() const { // singleton. If this is the second such candidate, of course, it's // not a singleton. if (!eltType.isPackExpansion()) { - if (singletonEltType) return llvm::None; + if (singletonEltType) + return llvm::None; singletonEltType = eltType; // Otherwise, check what the expansion shape expands to. @@ -2374,7 +2375,7 @@ public: auto newResultTy = visit(func.getResult(), pattern.getFunctionResultType()); - + llvm::Optional extInfo; if (func->hasExtInfo()) extInfo = func->getExtInfo(); diff --git a/lib/SIL/IR/SILDeclRef.cpp b/lib/SIL/IR/SILDeclRef.cpp index c62f32fcff9..cdb8c2bca05 100644 --- a/lib/SIL/IR/SILDeclRef.cpp +++ b/lib/SIL/IR/SILDeclRef.cpp @@ -219,7 +219,8 @@ ASTContext &SILDeclRef::getASTContext() const { return DC->getASTContext(); } -llvm::Optional SILDeclRef::getAvailabilityForLinkage() const { +llvm::Optional +SILDeclRef::getAvailabilityForLinkage() const { // Back deployment thunks and fallbacks don't have availability since they // are non-ABI. // FIXME: Generalize this check to all kinds of non-ABI functions. diff --git a/lib/SIL/IR/SILFunction.cpp b/lib/SIL/IR/SILFunction.cpp index e61c86adb47..5c97ac25581 100644 --- a/lib/SIL/IR/SILFunction.cpp +++ b/lib/SIL/IR/SILFunction.cpp @@ -92,20 +92,16 @@ void SILFunction::removeSpecializeAttr(SILSpecializeAttr *attr) { SpecializeAttrSet.end()); } -SILFunction * -SILFunction::create(SILModule &M, SILLinkage linkage, StringRef name, - CanSILFunctionType loweredType, - GenericEnvironment *genericEnv, llvm::Optional loc, - IsBare_t isBareSILFunction, IsTransparent_t isTrans, - IsSerialized_t isSerialized, ProfileCounter entryCount, - IsDynamicallyReplaceable_t isDynamic, - IsDistributed_t isDistributed, - IsRuntimeAccessible_t isRuntimeAccessible, - IsExactSelfClass_t isExactSelfClass, - IsThunk_t isThunk, - SubclassScope classSubclassScope, Inline_t inlineStrategy, - EffectsKind E, SILFunction *insertBefore, - const SILDebugScope *debugScope) { +SILFunction *SILFunction::create( + SILModule &M, SILLinkage linkage, StringRef name, + CanSILFunctionType loweredType, GenericEnvironment *genericEnv, + llvm::Optional loc, IsBare_t isBareSILFunction, + IsTransparent_t isTrans, IsSerialized_t isSerialized, + ProfileCounter entryCount, IsDynamicallyReplaceable_t isDynamic, + IsDistributed_t isDistributed, IsRuntimeAccessible_t isRuntimeAccessible, + IsExactSelfClass_t isExactSelfClass, IsThunk_t isThunk, + SubclassScope classSubclassScope, Inline_t inlineStrategy, EffectsKind E, + SILFunction *insertBefore, const SILDebugScope *debugScope) { // Get a StringMapEntry for the function. As a sop to error cases, // allow the name to have an empty string. llvm::StringMapEntry *entry = nullptr; diff --git a/lib/SIL/IR/SILFunctionBuilder.cpp b/lib/SIL/IR/SILFunctionBuilder.cpp index 9bd43084ddb..f03194ba9de 100644 --- a/lib/SIL/IR/SILFunctionBuilder.cpp +++ b/lib/SIL/IR/SILFunctionBuilder.cpp @@ -314,11 +314,11 @@ SILFunction *SILFunctionBuilder::getOrCreateFunction( if (constant.isRuntimeAccessibleFunction()) isRuntimeAccessible = IsRuntimeAccessible; - auto *F = SILFunction::create(mod, linkage, name, constantType, nullptr, llvm::None, - IsNotBare, IsTrans, IsSer, entryCount, IsDyn, - IsDistributed, isRuntimeAccessible, - IsNotExactSelfClass, IsNotThunk, - constant.getSubclassScope(), inlineStrategy); + auto *F = SILFunction::create( + mod, linkage, name, constantType, nullptr, llvm::None, IsNotBare, IsTrans, + IsSer, entryCount, IsDyn, IsDistributed, isRuntimeAccessible, + IsNotExactSelfClass, IsNotThunk, constant.getSubclassScope(), + inlineStrategy); F->setDebugScope(new (mod) SILDebugScope(loc, F)); if (constant.isGlobal()) diff --git a/lib/SIL/IR/SILFunctionType.cpp b/lib/SIL/IR/SILFunctionType.cpp index 33053138319..8de12b13e7e 100644 --- a/lib/SIL/IR/SILFunctionType.cpp +++ b/lib/SIL/IR/SILFunctionType.cpp @@ -2010,7 +2010,8 @@ lowerCaptureContextParameters(TypeConverter &TC, SILDeclRef function, } } -static AccessorDecl *getAsCoroutineAccessor(llvm::Optional constant) { +static AccessorDecl * +getAsCoroutineAccessor(llvm::Optional constant) { if (!constant || !constant->hasDecl()) return nullptr;; @@ -2121,7 +2122,8 @@ static CanSILFunctionType getSILFunctionType( AbstractionPattern origType, CanAnyFunctionType substFnInterfaceType, SILExtInfoBuilder extInfoBuilder, const Conventions &conventions, const ForeignInfo &foreignInfo, llvm::Optional origConstant, - llvm::Optional constant, llvm::Optional reqtSubs, + llvm::Optional constant, + llvm::Optional reqtSubs, ProtocolConformanceRef witnessMethodConformance) { // Find the generic parameters. CanGenericSignature genericSig = @@ -2654,7 +2656,8 @@ static CanSILFunctionType getNativeSILFunctionType( TypeConverter &TC, TypeExpansionContext context, AbstractionPattern origType, CanAnyFunctionType substInterfaceType, SILExtInfoBuilder extInfoBuilder, llvm::Optional origConstant, - llvm::Optional constant, llvm::Optional reqtSubs, + llvm::Optional constant, + llvm::Optional reqtSubs, ProtocolConformanceRef witnessMethodConformance) { assert(bool(origConstant) == bool(constant)); auto getSILFunctionTypeForConventions = @@ -2730,7 +2733,8 @@ CanSILFunctionType swift::getNativeSILFunctionType( TypeConverter &TC, TypeExpansionContext context, AbstractionPattern origType, CanAnyFunctionType substType, SILExtInfo silExtInfo, llvm::Optional origConstant, - llvm::Optional substConstant, llvm::Optional reqtSubs, + llvm::Optional substConstant, + llvm::Optional reqtSubs, ProtocolConformanceRef witnessMethodConformance) { return ::getNativeSILFunctionType( @@ -2978,14 +2982,10 @@ buildThunkSignature(SILFunction *fn, /// Build the type of a function transformation thunk. CanSILFunctionType swift::buildSILFunctionThunkType( - SILFunction *fn, - CanSILFunctionType &sourceType, - CanSILFunctionType &expectedType, - CanType &inputSubstType, - CanType &outputSubstType, - GenericEnvironment *&genericEnv, - SubstitutionMap &interfaceSubs, - CanType &dynamicSelfType, + SILFunction *fn, CanSILFunctionType &sourceType, + CanSILFunctionType &expectedType, CanType &inputSubstType, + CanType &outputSubstType, GenericEnvironment *&genericEnv, + SubstitutionMap &interfaceSubs, CanType &dynamicSelfType, bool withoutActuallyEscaping, llvm::Optional differentiationThunkKind) { // We shouldn't be thunking generic types here, and substituted function types @@ -3173,7 +3173,6 @@ CanSILFunctionType swift::buildSILFunctionThunkType( interfaceResults, interfaceErrorResult, expectedType->getPatternSubstitutions(), SubstitutionMap(), fn->getASTContext()); - } //===----------------------------------------------------------------------===// @@ -3624,10 +3623,10 @@ static CanSILFunctionType getSILFunctionTypeForClangDecl( bool isMutating = TC.Context.getClangModuleLoader()->isCXXMethodMutating(method); auto conventions = CXXMethodConventions(method, isMutating); - return getSILFunctionType(TC, TypeExpansionContext::minimal(), origPattern, - substInterfaceType, extInfoBuilder, conventions, - foreignInfo, constant, constant, llvm::None, - ProtocolConformanceRef()); + return getSILFunctionType(TC, TypeExpansionContext::minimal(), + origPattern, substInterfaceType, extInfoBuilder, + conventions, foreignInfo, constant, constant, + llvm::None, ProtocolConformanceRef()); } } diff --git a/lib/SIL/IR/SILGlobalVariable.cpp b/lib/SIL/IR/SILGlobalVariable.cpp index fb4c1b878e9..b709e8298e1 100644 --- a/lib/SIL/IR/SILGlobalVariable.cpp +++ b/lib/SIL/IR/SILGlobalVariable.cpp @@ -20,7 +20,7 @@ using namespace swift; SwiftMetatype SILGlobalVariable::registeredMetatype; - + SILGlobalVariable *SILGlobalVariable::create(SILModule &M, SILLinkage linkage, IsSerialized_t isSerialized, StringRef name, @@ -42,19 +42,14 @@ SILGlobalVariable *SILGlobalVariable::create(SILModule &M, SILLinkage linkage, return var; } - SILGlobalVariable::SILGlobalVariable(SILModule &Module, SILLinkage Linkage, IsSerialized_t isSerialized, StringRef Name, SILType LoweredType, - llvm::Optional Loc, VarDecl *Decl) - : SwiftObjectHeader(registeredMetatype), - Module(Module), - Name(Name), - LoweredType(LoweredType), - Location(Loc.value_or(SILLocation::invalid())), - Linkage(unsigned(Linkage)), - HasLocation(Loc.has_value()), - VDecl(Decl) { + llvm::Optional Loc, + VarDecl *Decl) + : SwiftObjectHeader(registeredMetatype), Module(Module), Name(Name), + LoweredType(LoweredType), Location(Loc.value_or(SILLocation::invalid())), + Linkage(unsigned(Linkage)), HasLocation(Loc.has_value()), VDecl(Decl) { setSerialized(isSerialized); IsDeclaration = isAvailableExternally(Linkage); setLet(Decl ? Decl->isLet() : false); diff --git a/lib/SIL/IR/SILInstructions.cpp b/lib/SIL/IR/SILInstructions.cpp index abe57b228a8..5fb844ddc34 100644 --- a/lib/SIL/IR/SILInstructions.cpp +++ b/lib/SIL/IR/SILInstructions.cpp @@ -227,7 +227,8 @@ SILDebugVariable::createFromAllocation(const AllocationInst *AI) { AllocStackInst::AllocStackInst(SILDebugLocation Loc, SILType elementType, ArrayRef TypeDependentOperands, - SILFunction &F, llvm::Optional Var, + SILFunction &F, + llvm::Optional Var, bool hasDynamicLifetime, bool isLexical, bool usesMoveableValueDebugInfo) : InstructionBase(Loc, elementType.getAddressType()), @@ -611,13 +612,11 @@ BeginApplyInst::BeginApplyInst(SILDebugLocation loc, SILValue callee, assert(substCalleeTy.castTo()->isCoroutine()); } -BeginApplyInst * -BeginApplyInst::create(SILDebugLocation loc, SILValue callee, - SubstitutionMap subs, ArrayRef args, - ApplyOptions options, - llvm::Optional moduleConventions, - SILFunction &F, - const GenericSpecializationInformation *specializationInfo) { +BeginApplyInst *BeginApplyInst::create( + SILDebugLocation loc, SILValue callee, SubstitutionMap subs, + ArrayRef args, ApplyOptions options, + llvm::Optional moduleConventions, SILFunction &F, + const GenericSpecializationInformation *specializationInfo) { SILType substCalleeSILType = callee->getType().substGenericArgs( F.getModule(), subs, F.getTypeExpansionContext()); auto substCalleeType = substCalleeSILType.castTo(); @@ -884,14 +883,15 @@ SILType DifferentiableFunctionExtractInst::getExtracteeType( DifferentiableFunctionExtractInst::DifferentiableFunctionExtractInst( SILModule &module, SILDebugLocation debugLoc, NormalDifferentiableFunctionTypeComponent extractee, SILValue function, - ValueOwnershipKind forwardingOwnershipKind, llvm::Optional extracteeType) + ValueOwnershipKind forwardingOwnershipKind, + llvm::Optional extracteeType) : UnaryInstructionBase(debugLoc, function, extracteeType ? *extracteeType : getExtracteeType(function, extractee, module), forwardingOwnershipKind), - Extractee(extractee), HasExplicitExtracteeType(extracteeType.has_value()) { -} + Extractee(extractee), + HasExplicitExtracteeType(extracteeType.has_value()) {} SILType LinearFunctionExtractInst:: getExtracteeType( @@ -2007,8 +2007,8 @@ SELECT_ENUM_INST *SelectEnumInstBase::createSelectEnum( SelectEnumInst *SelectEnumInst::create( SILDebugLocation Loc, SILValue Operand, SILType Type, SILValue DefaultValue, ArrayRef> CaseValues, SILModule &M, - llvm::Optional> CaseCounts, ProfileCounter DefaultCount, - ValueOwnershipKind forwardingOwnership) { + llvm::Optional> CaseCounts, + ProfileCounter DefaultCount, ValueOwnershipKind forwardingOwnership) { return createSelectEnum(Loc, Operand, Type, DefaultValue, CaseValues, M, CaseCounts, DefaultCount, forwardingOwnership); @@ -2070,7 +2070,7 @@ NullablePtr SelectEnumInstBase::getSingleTrueElement() const { return nullptr; // Try to find a single literal "true" case. - llvm::Optional TrueElement; + llvm::Optional TrueElement; for (unsigned i = 0, e = getNumCases(); i < e; ++i) { auto casePair = getCase(i); if (auto intLit = dyn_cast(casePair.second)) { @@ -2079,7 +2079,7 @@ NullablePtr SelectEnumInstBase::getSingleTrueElement() const { TrueElement = casePair.first; else // Use Optional(nullptr) to represent more than one. - TrueElement = llvm::Optional(nullptr); + TrueElement = llvm::Optional(nullptr); } } } @@ -2095,7 +2095,7 @@ SWITCH_ENUM_INST *SwitchEnumInstBase::createSwitchEnum( SILDebugLocation Loc, SILValue Operand, SILBasicBlock *DefaultBB, ArrayRef> CaseBBs, SILFunction &F, llvm::Optional> CaseCounts, - ProfileCounter DefaultCount, RestTys &&... restArgs) { + ProfileCounter DefaultCount, RestTys &&...restArgs) { // Allocate enough room for the instruction with tail-allocated // EnumElementDecl and SILSuccessor arrays. There are `CaseBBs.size()` decls // and `CaseBBs.size() + (DefaultBB ? 1 : 0)` successors. diff --git a/lib/SIL/IR/SILModule.cpp b/lib/SIL/IR/SILModule.cpp index 222abc3a0a8..ad33e1c2081 100644 --- a/lib/SIL/IR/SILModule.cpp +++ b/lib/SIL/IR/SILModule.cpp @@ -412,8 +412,7 @@ bool SILModule::loadFunction(SILFunction *F, LinkingMode LinkMode) { return true; } -SILFunction *SILModule::loadFunction(StringRef name, - LinkingMode LinkMode, +SILFunction *SILModule::loadFunction(StringRef name, LinkingMode LinkMode, llvm::Optional linkage) { SILFunction *func = lookUpFunction(name); if (!func) @@ -905,10 +904,9 @@ void SILModule::performOnceForPrespecializedImportedExtensions( prespecializedFunctionDeclsImported = true; } -SILProperty *SILProperty::create(SILModule &M, - bool Serialized, - AbstractStorageDecl *Decl, - llvm::Optional Component) { +SILProperty * +SILProperty::create(SILModule &M, bool Serialized, AbstractStorageDecl *Decl, + llvm::Optional Component) { auto prop = new (M) SILProperty(Serialized, Decl, Component); M.properties.push_back(prop); return prop; diff --git a/lib/SIL/IR/SILProfiler.cpp b/lib/SIL/IR/SILProfiler.cpp index 4f97fff63b0..d97d2863ffc 100644 --- a/lib/SIL/IR/SILProfiler.cpp +++ b/lib/SIL/IR/SILProfiler.cpp @@ -520,7 +520,8 @@ class SourceMappingRegion { public: SourceMappingRegion(ASTNode Node, llvm::Optional Counter, - llvm::Optional StartLoc, llvm::Optional EndLoc) + llvm::Optional StartLoc, + llvm::Optional EndLoc) : Node(Node), Counter(std::move(Counter)), StartLoc(StartLoc), EndLoc(EndLoc) { assert((!StartLoc || StartLoc->isValid()) && @@ -918,7 +919,8 @@ private: } /// Adjust the count for control flow when exiting a scope. - void adjustForNonLocalExits(ASTNode Scope, llvm::Optional ControlFlowAdjust) { + void adjustForNonLocalExits(ASTNode Scope, + llvm::Optional ControlFlowAdjust) { if (Parent.getAsDecl()) return; diff --git a/lib/SIL/IR/SILTypeSubstitution.cpp b/lib/SIL/IR/SILTypeSubstitution.cpp index e7b4ea4d368..d1708cde993 100644 --- a/lib/SIL/IR/SILTypeSubstitution.cpp +++ b/lib/SIL/IR/SILTypeSubstitution.cpp @@ -281,9 +281,8 @@ public: // Substitute the underlying conformance of opaque type archetypes if we // should look through opaque archetypes. if (typeExpansionContext.shouldLookThroughOpaqueTypeArchetypes()) { - auto substType = IFS.withNewOptions(llvm::None, [&] { - return selfType.subst(IFS)->getCanonicalType(); - }); + auto substType = IFS.withNewOptions( + llvm::None, [&] { return selfType.subst(IFS)->getCanonicalType(); }); if (substType->hasOpaqueArchetype()) { substConformance = substOpaqueTypesWithUnderlyingTypes( substConformance, substType, typeExpansionContext); diff --git a/lib/SIL/IR/SILVTable.cpp b/lib/SIL/IR/SILVTable.cpp index a705ee09822..d6d3dcaa072 100644 --- a/lib/SIL/IR/SILVTable.cpp +++ b/lib/SIL/IR/SILVTable.cpp @@ -38,8 +38,8 @@ SILVTable *SILVTable::create(SILModule &M, ClassDecl *Class, return vt; } -llvm::Optional -SILVTable::getEntry(SILModule &M, SILDeclRef method) const { +llvm::Optional SILVTable::getEntry(SILModule &M, + SILDeclRef method) const { SILDeclRef m = method; do { auto entryIter = M.VTableEntryCache.find({this, m}); diff --git a/lib/SIL/IR/TypeLowering.cpp b/lib/SIL/IR/TypeLowering.cpp index 0928327ef64..240d423dfca 100644 --- a/lib/SIL/IR/TypeLowering.cpp +++ b/lib/SIL/IR/TypeLowering.cpp @@ -2752,19 +2752,19 @@ bool TypeConverter::visitAggregateLeaves( llvm::SmallVector< std::tuple, 16> worklist; - auto insertIntoWorklist = [&visited, - &worklist](CanType substTy, - AbstractionPattern origTy, - ValueDecl *field, - llvm::Optional maybeIndex) -> bool { + auto insertIntoWorklist = + [&visited, &worklist](CanType substTy, AbstractionPattern origTy, + ValueDecl *field, + llvm::Optional maybeIndex) -> bool { unsigned index = maybeIndex.value_or(UINT_MAX); if (!visited.insert({substTy, field, index}).second) return false; worklist.push_back({substTy, origTy, field, index}); return true; }; - auto popFromWorklist = [&worklist]() - -> std::tuple> { + auto popFromWorklist = + [&worklist]() -> std::tuple> { CanType ty; AbstractionPattern origTy = AbstractionPattern::getOpaque(); ValueDecl *field; @@ -3004,7 +3004,8 @@ TypeConverter::computeLoweredRValueType(TypeExpansionContext forExpansion, .build(); return ::getNativeSILFunctionType(TC, forExpansion, origType, substFnType, - silExtInfo, llvm::None, llvm::None, llvm::None, {}); + silExtInfo, llvm::None, llvm::None, + llvm::None, {}); } // Ignore dynamic self types. diff --git a/lib/SIL/Parser/ParseSIL.cpp b/lib/SIL/Parser/ParseSIL.cpp index cf3a0f4b215..f85c456822b 100644 --- a/lib/SIL/Parser/ParseSIL.cpp +++ b/lib/SIL/Parser/ParseSIL.cpp @@ -295,9 +295,9 @@ namespace swift { } template - bool - parseSILQualifier(llvm::Optional &result, - llvm::function_ref(StringRef)> parseName); + bool parseSILQualifier( + llvm::Optional &result, + llvm::function_ref(StringRef)> parseName); bool parseVerbatim(StringRef identifier); @@ -356,7 +356,8 @@ namespace swift { return false; } - llvm::Optional parseOptionalAttribute(ArrayRef expected) { + llvm::Optional + parseOptionalAttribute(ArrayRef expected) { // We parse here @ . if (P.Tok.getKind() != tok::at_sign) return llvm::None; @@ -850,12 +851,12 @@ static bool parseSILLinkage(llvm::Optional &Result, Parser &P) { // Then use a string switch to try and parse the identifier. Result = llvm::StringSwitch>(P.Tok.getText()) - .Case("non_abi", SILLinkage::PublicNonABI) - .Case("hidden", SILLinkage::Hidden) - .Case("shared", SILLinkage::Shared) - .Case("public_external", SILLinkage::PublicExternal) - .Case("hidden_external", SILLinkage::HiddenExternal) - .Default(llvm::None); + .Case("non_abi", SILLinkage::PublicNonABI) + .Case("hidden", SILLinkage::Hidden) + .Case("shared", SILLinkage::Shared) + .Case("public_external", SILLinkage::PublicExternal) + .Case("hidden_external", SILLinkage::HiddenExternal) + .Default(llvm::None); // If we succeed, consume the token. if (Result) { @@ -945,7 +946,8 @@ static bool parseSILOptional(bool &Result, SILParser &SP, StringRef Expected) { // return true; template bool SILParser::parseSILQualifier( - llvm::Optional &result, llvm::function_ref(StringRef)> parseName) { + llvm::Optional &result, + llvm::function_ref(StringRef)> parseName) { auto loc = P.Tok.getLoc(); StringRef Str; // If we do not parse '[' ... ']', @@ -1594,13 +1596,13 @@ bool SILParser::parseSILDottedPathWithoutPound(ValueDecl *&Decl, static llvm::Optional getAccessorKind(StringRef ident) { return llvm::StringSwitch>(ident) - .Case("getter", AccessorKind::Get) - .Case("setter", AccessorKind::Set) - .Case("addressor", AccessorKind::Address) - .Case("mutableAddressor", AccessorKind::MutableAddress) - .Case("read", AccessorKind::Read) - .Case("modify", AccessorKind::Modify) - .Default(llvm::None); + .Case("getter", AccessorKind::Get) + .Case("setter", AccessorKind::Set) + .Case("addressor", AccessorKind::Address) + .Case("mutableAddressor", AccessorKind::MutableAddress) + .Case("read", AccessorKind::Read) + .Case("modify", AccessorKind::Modify) + .Default(llvm::None); } /// sil-decl-ref ::= '#' sil-identifier ('.' sil-identifier)* sil-decl-subref? @@ -1821,12 +1823,13 @@ bool SILParser::parseTypedValueRef(SILValue &Result, SourceLoc &Loc, } /// Look up whether the given string corresponds to a SIL opcode. -static llvm::Optional getOpcodeByName(StringRef OpcodeName) { +static llvm::Optional +getOpcodeByName(StringRef OpcodeName) { return llvm::StringSwitch>(OpcodeName) - #define FULL_INST(Id, TextualName, Parent, MemBehavior, MayRelease) \ - .Case(#TextualName, SILInstructionKind::Id) - #include "swift/SIL/SILNodes.def" - .Default(llvm::None); +#define FULL_INST(Id, TextualName, Parent, MemBehavior, MayRelease) \ + .Case(#TextualName, SILInstructionKind::Id) +#include "swift/SIL/SILNodes.def" + .Default(llvm::None); } /// getInstructionKind - This method maps the string form of a SIL instruction @@ -6008,8 +6011,9 @@ bool SILParser::parseSpecificSILInstruction(SILBuilder &B, } if (Opcode == SILInstructionKind::SwitchEnumInst) { - ResultVal = B.createSwitchEnum(InstLoc, Val, DefaultBB, CaseBBs, llvm::None, - ProfileCounter(), forwardingOwnership); + ResultVal = + B.createSwitchEnum(InstLoc, Val, DefaultBB, CaseBBs, llvm::None, + ProfileCounter(), forwardingOwnership); } else ResultVal = B.createSwitchEnumAddr(InstLoc, Val, DefaultBB, CaseBBs); break; @@ -6342,7 +6346,8 @@ bool SILParser::parseSpecificSILInstruction(SILBuilder &B, diag::sil_inst_autodiff_expected_function_type_operand); return true; } - llvm::Optional> derivativeFunctions = llvm::None; + llvm::Optional> derivativeFunctions = + llvm::None; // Parse an optional operand list // `with_derivative { , }`. if (P.Tok.is(tok::identifier) && P.Tok.getText() == "with_derivative") { @@ -7328,8 +7333,9 @@ bool SILParserState::parseDeclSILStage(Parser &P) { /// will still incorrectly diagnose this as an "invalid redeclaration" and give /// all but the first declaration an error type. static llvm::Optional lookupGlobalDecl(Identifier GlobalName, - SILLinkage GlobalLinkage, - SILType GlobalType, Parser &P) { + SILLinkage GlobalLinkage, + SILType GlobalType, + Parser &P) { // Create a set of DemangleOptions to produce the global variable's // identifier, which is used as a search key in the declaration context. Demangle::DemangleOptions demangleOpts; diff --git a/lib/SIL/Utils/Projection.cpp b/lib/SIL/Utils/Projection.cpp index 22cc6fd6d3a..346ff5afc62 100644 --- a/lib/SIL/Utils/Projection.cpp +++ b/lib/SIL/Utils/Projection.cpp @@ -364,7 +364,7 @@ void Projection::getFirstLevelProjections( //===----------------------------------------------------------------------===// llvm::Optional ProjectionPath::getProjectionPath(SILValue Start, - SILValue End) { + SILValue End) { ProjectionPath P(Start->getType(), End->getType()); // If Start == End, there is a "trivial" projection path in between the diff --git a/lib/SIL/Verifier/LinearLifetimeChecker.cpp b/lib/SIL/Verifier/LinearLifetimeChecker.cpp index 1958f83d3e0..3d336f1251c 100644 --- a/lib/SIL/Verifier/LinearLifetimeChecker.cpp +++ b/lib/SIL/Verifier/LinearLifetimeChecker.cpp @@ -105,12 +105,12 @@ struct State { /// terminates. SmallSetVector successorBlocksThatMustBeVisited; - State(SILValue value, - LinearLifetimeChecker::ErrorBuilder &errorBuilder, - llvm::Optional> leakingBlockCallback, - llvm::Optional> - nonConsumingUseOutsideLifetimeCallback, - ArrayRef consumingUses, ArrayRef nonConsumingUses) + State( + SILValue value, LinearLifetimeChecker::ErrorBuilder &errorBuilder, + llvm::Optional> leakingBlockCallback, + llvm::Optional> + nonConsumingUseOutsideLifetimeCallback, + ArrayRef consumingUses, ArrayRef nonConsumingUses) : value(value), beginInst(value->getDefiningInsertionPoint()), errorBuilder(errorBuilder), visitedBlocks(value->getFunction()), leakingBlockCallback(leakingBlockCallback), @@ -119,12 +119,13 @@ struct State { consumingUses(consumingUses), nonConsumingUses(nonConsumingUses), blocksWithConsumingUses(value->getFunction()) {} - State(SILBasicBlock *beginBlock, - LinearLifetimeChecker::ErrorBuilder &errorBuilder, - llvm::Optional> leakingBlockCallback, - llvm::Optional> - nonConsumingUseOutsideLifetimeCallback, - ArrayRef consumingUses, ArrayRef nonConsumingUses) + State( + SILBasicBlock *beginBlock, + LinearLifetimeChecker::ErrorBuilder &errorBuilder, + llvm::Optional> leakingBlockCallback, + llvm::Optional> + nonConsumingUseOutsideLifetimeCallback, + ArrayRef consumingUses, ArrayRef nonConsumingUses) : value(), beginInst(&*beginBlock->begin()), errorBuilder(errorBuilder), visitedBlocks(beginBlock->getParent()), leakingBlockCallback(leakingBlockCallback), diff --git a/lib/SILGen/Callee.h b/lib/SILGen/Callee.h index 87f4003d625..495f0100b6f 100644 --- a/lib/SILGen/Callee.h +++ b/lib/SILGen/Callee.h @@ -36,21 +36,23 @@ private: public: CalleeTypeInfo() = default; - CalleeTypeInfo(CanSILFunctionType substFnType, - AbstractionPattern origResultType, CanType substResultType, - const llvm::Optional &foreignError, - const llvm::Optional &foreignAsync, - ImportAsMemberStatus foreignSelf, - llvm::Optional overrideRep = llvm::None) + CalleeTypeInfo( + CanSILFunctionType substFnType, AbstractionPattern origResultType, + CanType substResultType, + const llvm::Optional &foreignError, + const llvm::Optional &foreignAsync, + ImportAsMemberStatus foreignSelf, + llvm::Optional overrideRep = llvm::None) : origFormalType(llvm::None), substFnType(substFnType), origResultType(origResultType), substResultType(substResultType), foreign{foreignSelf, foreignError, foreignAsync}, overrideRep(overrideRep) {} - CalleeTypeInfo(CanSILFunctionType substFnType, - AbstractionPattern origResultType, CanType substResultType, - llvm::Optional overrideRep = llvm::None) + CalleeTypeInfo( + CanSILFunctionType substFnType, AbstractionPattern origResultType, + CanType substResultType, + llvm::Optional overrideRep = llvm::None) : origFormalType(llvm::None), substFnType(substFnType), origResultType(origResultType), substResultType(substResultType), foreign(), overrideRep(overrideRep) {} diff --git a/lib/SILGen/Condition.h b/lib/SILGen/Condition.h index 9742190f419..d85f0e54f3a 100644 --- a/lib/SILGen/Condition.h +++ b/lib/SILGen/Condition.h @@ -106,7 +106,7 @@ class ConditionalValue { /// The Scope for the current branch. llvm::Optional scope; - + /// A place to hold conditional Initializations of our result. std::unique_ptr currentInitialization; diff --git a/lib/SILGen/Conversion.h b/lib/SILGen/Conversion.h index b4c9b2f2b99..3b91ef56931 100644 --- a/lib/SILGen/Conversion.h +++ b/lib/SILGen/Conversion.h @@ -227,8 +227,7 @@ public: }; llvm::Optional -canPeepholeConversions(SILGenFunction &SGF, - const Conversion &outerConversion, +canPeepholeConversions(SILGenFunction &SGF, const Conversion &outerConversion, const Conversion &innerConversion); /// An initialization where we ultimately want to apply a conversion to diff --git a/lib/SILGen/LValue.h b/lib/SILGen/LValue.h index 576f37a32f6..21f42671b1d 100644 --- a/lib/SILGen/LValue.h +++ b/lib/SILGen/LValue.h @@ -215,7 +215,7 @@ class PhysicalPathComponent : public PathComponent { protected: PhysicalPathComponent(LValueTypeData typeData, KindTy Kind, llvm::Optional actorIso = llvm::None) - : PathComponent(typeData, Kind), ActorIso(actorIso) { + : PathComponent(typeData, Kind), ActorIso(actorIso) { assert(isPhysical() && "PhysicalPathComponent Kind isn't physical"); } @@ -447,13 +447,11 @@ public: // given actor's isolation domain. If the indicator is not present, that // only means that a switch does not need to be emitted during the access. - void addNonMemberVarComponent(SILGenFunction &SGF, SILLocation loc, - VarDecl *var, SubstitutionMap subs, - LValueOptions options, - SGFAccessKind accessKind, - AccessStrategy strategy, - CanType formalRValueType, - llvm::Optional actorIso = llvm::None); + void addNonMemberVarComponent( + SILGenFunction &SGF, SILLocation loc, VarDecl *var, SubstitutionMap subs, + LValueOptions options, SGFAccessKind accessKind, AccessStrategy strategy, + CanType formalRValueType, + llvm::Optional actorIso = llvm::None); /// Add a member component to the access path of this lvalue. void addMemberComponent(SILGenFunction &SGF, SILLocation loc, @@ -467,29 +465,21 @@ public: PreparedArguments &&indices, ArgumentList *argListForDiagnostics); - void addMemberVarComponent(SILGenFunction &SGF, SILLocation loc, - VarDecl *var, - SubstitutionMap subs, - LValueOptions options, - bool isSuper, - SGFAccessKind accessKind, - AccessStrategy accessStrategy, - CanType formalRValueType, - bool isOnSelf = false, - llvm::Optional actorIso = llvm::None); + void + addMemberVarComponent(SILGenFunction &SGF, SILLocation loc, VarDecl *var, + SubstitutionMap subs, LValueOptions options, + bool isSuper, SGFAccessKind accessKind, + AccessStrategy accessStrategy, CanType formalRValueType, + bool isOnSelf = false, + llvm::Optional actorIso = llvm::None); - void addMemberSubscriptComponent(SILGenFunction &SGF, SILLocation loc, - SubscriptDecl *subscript, - SubstitutionMap subs, - LValueOptions options, - bool isSuper, - SGFAccessKind accessKind, - AccessStrategy accessStrategy, - CanType formalRValueType, - PreparedArguments &&indices, - ArgumentList *argListForDiagnostics, - bool isOnSelfParameter = false, - llvm::Optional actorIso = llvm::None); + void addMemberSubscriptComponent( + SILGenFunction &SGF, SILLocation loc, SubscriptDecl *subscript, + SubstitutionMap subs, LValueOptions options, bool isSuper, + SGFAccessKind accessKind, AccessStrategy accessStrategy, + CanType formalRValueType, PreparedArguments &&indices, + ArgumentList *argListForDiagnostics, bool isOnSelfParameter = false, + llvm::Optional actorIso = llvm::None); /// Add a subst-to-orig reabstraction component. That is, given /// that this l-value trafficks in values following the substituted diff --git a/lib/SILGen/ResultPlan.cpp b/lib/SILGen/ResultPlan.cpp index 76de7e87f4d..06d9001ff63 100644 --- a/lib/SILGen/ResultPlan.cpp +++ b/lib/SILGen/ResultPlan.cpp @@ -428,9 +428,8 @@ class PackExpansionResultPlan : public ResultPlan { SmallVector ComponentPlans; public: - PackExpansionResultPlan(ResultPlanBuilder &builder, - SILValue packAddr, - llvm::Optional> inits, + PackExpansionResultPlan(ResultPlanBuilder &builder, SILValue packAddr, + llvm::Optional> inits, AbstractionPattern origExpansionType, CanTupleEltTypeArrayRef substEltTypes) : PackAddr(packAddr) { @@ -601,8 +600,8 @@ public: origEltPlans.push_back( builder.build(nullptr, origEltType, substEltTypes[0])); } else { - origEltPlans.push_back( - builder.buildForPackExpansion(llvm::None, origEltType, substEltTypes)); + origEltPlans.push_back(builder.buildForPackExpansion( + llvm::None, origEltType, substEltTypes)); } }); } @@ -1199,10 +1198,9 @@ ResultPlanPtr ResultPlanBuilder::buildForScalar(Initialization *init, calleeTypeInfo.getOverrideRep())); } -ResultPlanPtr ResultPlanBuilder:: - buildForPackExpansion(llvm::Optional> inits, - AbstractionPattern origExpansionType, - CanTupleEltTypeArrayRef substTypes) { +ResultPlanPtr ResultPlanBuilder::buildForPackExpansion( + llvm::Optional> inits, + AbstractionPattern origExpansionType, CanTupleEltTypeArrayRef substTypes) { assert(!inits || inits->size() == substTypes.size()); // Pack expansions in the original result type always turn into diff --git a/lib/SILGen/ResultPlan.h b/lib/SILGen/ResultPlan.h index c5db77626a4..23a205cba05 100644 --- a/lib/SILGen/ResultPlan.h +++ b/lib/SILGen/ResultPlan.h @@ -98,9 +98,10 @@ struct ResultPlanBuilder { ResultPlanPtr buildForTuple(Initialization *emitInto, AbstractionPattern origType, CanType substType); - ResultPlanPtr buildForPackExpansion(llvm::Optional> inits, - AbstractionPattern origExpansionType, - CanTupleEltTypeArrayRef substTypes); + ResultPlanPtr + buildForPackExpansion(llvm::Optional> inits, + AbstractionPattern origExpansionType, + CanTupleEltTypeArrayRef substTypes); ResultPlanPtr buildPackExpansionIntoPack(SILValue packAddr, CanPackType formalPackType, unsigned componentIndex, diff --git a/lib/SILGen/SILGen.cpp b/lib/SILGen/SILGen.cpp index 804f074211f..f2ab0994f04 100644 --- a/lib/SILGen/SILGen.cpp +++ b/lib/SILGen/SILGen.cpp @@ -94,13 +94,11 @@ SILGenModule::~SILGenModule() { M.verifyIncompleteOSSA(); } -static SILDeclRef -getBridgingFn(llvm::Optional &cacheSlot, - SILGenModule &SGM, - Identifier moduleName, - StringRef functionName, - std::initializer_list inputTypes, - Type outputType) { +static SILDeclRef getBridgingFn(llvm::Optional &cacheSlot, + SILGenModule &SGM, Identifier moduleName, + StringRef functionName, + std::initializer_list inputTypes, + Type outputType) { if (!cacheSlot) { ASTContext &ctx = SGM.M.getASTContext(); ModuleDecl *mod = ctx.getLoadedModule(moduleName); @@ -366,7 +364,8 @@ SILGenModule::getConformanceToBridgedStoredNSError(SILLocation loc, Type type) { } static FuncDecl *lookupIntrinsic(ModuleDecl &module, - llvm::Optional &cache, Identifier name) { + llvm::Optional &cache, + Identifier name) { if (cache) return *cache; @@ -602,17 +601,10 @@ SILGenModule::getKeyPathProjectionCoroutine(bool isReadAccess, auto env = sig.getGenericEnvironment(); SILGenFunctionBuilder builder(*this); - fn = builder.createFunction(SILLinkage::PublicExternal, - functionName, - functionTy, - env, - /*location*/ llvm::None, - IsNotBare, - IsNotTransparent, - IsNotSerialized, - IsNotDynamic, - IsNotDistributed, - IsNotRuntimeAccessible); + fn = builder.createFunction( + SILLinkage::PublicExternal, functionName, functionTy, env, + /*location*/ llvm::None, IsNotBare, IsNotTransparent, IsNotSerialized, + IsNotDynamic, IsNotDistributed, IsNotRuntimeAccessible); return fn; } @@ -2367,6 +2359,7 @@ std::unique_ptr swift::performASTLowering(FileUnit &sf, Lowering::TypeConverter &tc, const SILOptions &options, const IRGenOptions *irgenOptions) { - auto desc = ASTLoweringDescriptor::forFile(sf, tc, options, llvm::None, irgenOptions); + auto desc = + ASTLoweringDescriptor::forFile(sf, tc, options, llvm::None, irgenOptions); return llvm::cantFail(sf.getASTContext().evaluator(ASTLoweringRequest{desc})); } diff --git a/lib/SILGen/SILGen.h b/lib/SILGen/SILGen.h index ded42b63011..5a6e4133db9 100644 --- a/lib/SILGen/SILGen.h +++ b/lib/SILGen/SILGen.h @@ -108,31 +108,31 @@ public: llvm::Optional BoolToWindowsBoolFn; llvm::Optional WindowsBoolToBoolFn; - llvm::Optional PointerProtocol; + llvm::Optional PointerProtocol; - llvm::Optional ObjectiveCBridgeable; - llvm::Optional BridgeToObjectiveCRequirement; - llvm::Optional UnconditionallyBridgeFromObjectiveCRequirement; - llvm::Optional BridgedObjectiveCType; + llvm::Optional ObjectiveCBridgeable; + llvm::Optional BridgeToObjectiveCRequirement; + llvm::Optional UnconditionallyBridgeFromObjectiveCRequirement; + llvm::Optional BridgedObjectiveCType; - llvm::Optional BridgedStoredNSError; - llvm::Optional NSErrorRequirement; + llvm::Optional BridgedStoredNSError; + llvm::Optional NSErrorRequirement; llvm::Optional NSErrorConformanceToError; - llvm::Optional AsyncLetStart; - llvm::Optional AsyncLetGet; - llvm::Optional AsyncLetGetThrowing; - llvm::Optional EndAsyncLet; + llvm::Optional AsyncLetStart; + llvm::Optional AsyncLetGet; + llvm::Optional AsyncLetGetThrowing; + llvm::Optional EndAsyncLet; - llvm::Optional TaskFutureGet; - llvm::Optional TaskFutureGetThrowing; + llvm::Optional TaskFutureGet; + llvm::Optional TaskFutureGetThrowing; - llvm::Optional RunTaskForBridgedAsyncMethod; - llvm::Optional ResumeUnsafeContinuation; - llvm::Optional ResumeUnsafeThrowingContinuation; - llvm::Optional ResumeUnsafeThrowingContinuationWithError; - llvm::Optional CheckExpectedExecutor; + llvm::Optional RunTaskForBridgedAsyncMethod; + llvm::Optional ResumeUnsafeContinuation; + llvm::Optional ResumeUnsafeThrowingContinuation; + llvm::Optional ResumeUnsafeThrowingContinuationWithError; + llvm::Optional CheckExpectedExecutor; llvm::Optional AsyncMainDrainQueue; llvm::Optional GetMainExecutor; @@ -170,9 +170,8 @@ public: /// Emit a vtable thunk for a derived method if its natural abstraction level /// diverges from the overridden base method. If no thunking is needed, /// returns a static reference to the derived method. - llvm::Optional emitVTableMethod(ClassDecl *theClass, - SILDeclRef derived, - SILDeclRef base); + llvm::Optional + emitVTableMethod(ClassDecl *theClass, SILDeclRef derived, SILDeclRef base); /// True if a function has been emitted for a given SILDeclRef. bool hasFunction(SILDeclRef constant); diff --git a/lib/SILGen/SILGenApply.cpp b/lib/SILGen/SILGenApply.cpp index 4c88c6671cd..90c6683e76f 100644 --- a/lib/SILGen/SILGenApply.cpp +++ b/lib/SILGen/SILGenApply.cpp @@ -275,8 +275,8 @@ static void convertOwnershipConventionsGivenParamInfos( llvm::transform(indices(params), std::back_inserter(outVar), [&](unsigned i) -> ManagedValue { return convertOwnershipConventionGivenParamInfo( - SGF, params[i], llvm::None /*orig param*/, values[i], loc, - isForCoroutine); + SGF, params[i], llvm::None /*orig param*/, values[i], + loc, isForCoroutine); }); } @@ -3239,8 +3239,9 @@ public: DelayedArguments(delayedArgs) {} // origParamType is a parameter type. - void emitSingleArg(ArgumentSource &&arg, AbstractionPattern origParamType, - llvm::Optional param = llvm::None) { + void + emitSingleArg(ArgumentSource &&arg, AbstractionPattern origParamType, + llvm::Optional param = llvm::None) { // If this is delayed default argument, prepare to emit the default argument // generator later. if (arg.isDelayedDefaultArg()) { @@ -3712,9 +3713,10 @@ private: origParamType, claimedParams); } - void emitDirect(ArgumentSource &&arg, SILType loweredSubstArgType, - AbstractionPattern origParamType, SILParameterInfo param, - llvm::Optional origParam = llvm::None) { + void + emitDirect(ArgumentSource &&arg, SILType loweredSubstArgType, + AbstractionPattern origParamType, SILParameterInfo param, + llvm::Optional origParam = llvm::None) { ManagedValue value; auto loc = arg.getLocation(); @@ -4696,8 +4698,7 @@ public: FormalEvaluationScope &&writebackScope) : SGF(SGF), callee(std::move(callee)), initialWritebackScope(std::move(writebackScope)), - implicitActorHopTarget(llvm::None), - implicitlyThrows(false) {} + implicitActorHopTarget(llvm::None), implicitlyThrows(false) {} /// A factory method for decomposing the apply expr \p e into a call /// emission. @@ -4737,8 +4738,8 @@ public: /// Sets a flag that indicates whether this call be treated as being /// implicitly async, i.e., it requires a hop_to_executor prior to /// invoking the sync callee, etc. - void setImplicitlyAsync( - llvm::Optional implicitActorHopTarget) { + void + setImplicitlyAsync(llvm::Optional implicitActorHopTarget) { this->implicitActorHopTarget = implicitActorHopTarget; } @@ -5388,12 +5389,10 @@ public: /// result does need to be turned back into something matching a /// formal type. RValue SILGenFunction::emitApply( - ResultPlanPtr &&resultPlan, - ArgumentScope &&argScope, SILLocation loc, - ManagedValue fn, SubstitutionMap subs, - ArrayRef args, - const CalleeTypeInfo &calleeTypeInfo, - ApplyOptions options, SGFContext evalContext, + ResultPlanPtr &&resultPlan, ArgumentScope &&argScope, SILLocation loc, + ManagedValue fn, SubstitutionMap subs, ArrayRef args, + const CalleeTypeInfo &calleeTypeInfo, ApplyOptions options, + SGFContext evalContext, llvm::Optional implicitActorHopTarget) { auto substFnType = calleeTypeInfo.substFnType; @@ -6492,9 +6491,9 @@ ArgumentSource AccessorBaseArgPreparer::prepareAccessorAddressBaseArg() { // FIXME: this assumes that there's never meaningful reabstraction of self // arguments. return ArgumentSource( - loc, LValue::forAddress(SGFAccessKind::ReadWrite, base, llvm::None, - AbstractionPattern(baseFormalType), - baseFormalType)); + loc, + LValue::forAddress(SGFAccessKind::ReadWrite, base, llvm::None, + AbstractionPattern(baseFormalType), baseFormalType)); } // Otherwise, we have a value that we can forward without any additional @@ -6695,13 +6694,9 @@ SILDeclRef SILGenModule::getAccessorDeclRef(AccessorDecl *accessor, /// Emit a call to a getter. RValue SILGenFunction::emitGetAccessor( - SILLocation loc, SILDeclRef get, - SubstitutionMap substitutions, - ArgumentSource &&selfValue, bool isSuper, - bool isDirectUse, - PreparedArguments &&subscriptIndices, - SGFContext c, - bool isOnSelfParameter, + SILLocation loc, SILDeclRef get, SubstitutionMap substitutions, + ArgumentSource &&selfValue, bool isSuper, bool isDirectUse, + PreparedArguments &&subscriptIndices, SGFContext c, bool isOnSelfParameter, llvm::Optional implicitActorHopTarget) { // Scope any further writeback just within this operation. FormalEvaluationScope writebackScope(*this); @@ -7261,9 +7256,9 @@ SILGenFunction::emitDynamicSubscriptGetterApply(SILLocation loc, indexValues.push_back(std::move(rVal).getScalarValue()); } - auto resultRV = emitMonomorphicApply(loc, result, indexValues, - foreignMethodTy.getResult(), valueTy, - ApplyOptions(), llvm::None, llvm::None); + auto resultRV = emitMonomorphicApply( + loc, result, indexValues, foreignMethodTy.getResult(), valueTy, + ApplyOptions(), llvm::None, llvm::None); // Package up the result in an optional. emitInjectOptionalValueInto(loc, {loc, std::move(resultRV)}, optTemp, diff --git a/lib/SILGen/SILGenBridging.cpp b/lib/SILGen/SILGenBridging.cpp index fcb40a4db9f..26685ac79c8 100644 --- a/lib/SILGen/SILGenBridging.cpp +++ b/lib/SILGen/SILGenBridging.cpp @@ -90,15 +90,14 @@ static bool shouldBridgeThroughError(SILGenModule &SGM, CanType type, /// object, using the appropriate witness for the /// _ObjectiveCBridgeable._bridgeToObjectiveC requirement. static llvm::Optional -emitBridgeNativeToObjectiveC(SILGenFunction &SGF, - SILLocation loc, - ManagedValue swiftValue, - CanType swiftValueType, +emitBridgeNativeToObjectiveC(SILGenFunction &SGF, SILLocation loc, + ManagedValue swiftValue, CanType swiftValueType, CanType bridgedType, ProtocolConformance *conformance) { // Find the _bridgeToObjectiveC requirement. auto requirement = SGF.SGM.getBridgeToObjectiveCRequirement(loc); - if (!requirement) return llvm::None; + if (!requirement) + return llvm::None; // Retrieve the _bridgeToObjectiveC witness. auto witness = conformance->getWitnessDecl(requirement); @@ -106,7 +105,8 @@ emitBridgeNativeToObjectiveC(SILGenFunction &SGF, // Determine the type we're bridging to. auto objcTypeReq = SGF.SGM.getBridgedObjectiveCTypeRequirement(loc); - if (!objcTypeReq) return llvm::None; + if (!objcTypeReq) + return llvm::None; Type objcType = conformance->getTypeWitness(objcTypeReq); @@ -178,19 +178,19 @@ emitBridgeNativeToObjectiveC(SILGenFunction &SGF, /// value, using the appropriate witness for the /// _ObjectiveCBridgeable._unconditionallyBridgeFromObjectiveC requirement. static llvm::Optional -emitBridgeObjectiveCToNative(SILGenFunction &SGF, - SILLocation loc, - ManagedValue objcValue, - CanType bridgedType, +emitBridgeObjectiveCToNative(SILGenFunction &SGF, SILLocation loc, + ManagedValue objcValue, CanType bridgedType, ProtocolConformance *conformance) { // Find the _unconditionallyBridgeFromObjectiveC requirement. auto requirement = SGF.SGM.getUnconditionallyBridgeFromObjectiveCRequirement(loc); - if (!requirement) return llvm::None; + if (!requirement) + return llvm::None; // Find the _ObjectiveCType requirement. auto objcTypeRequirement = SGF.SGM.getBridgedObjectiveCTypeRequirement(loc); - if (!objcTypeRequirement) return llvm::None; + if (!objcTypeRequirement) + return llvm::None; // Retrieve the _unconditionallyBridgeFromObjectiveC witness. auto witness = conformance->getWitnessDeclRef(requirement); @@ -474,12 +474,11 @@ static void buildFuncToBlockInvokeBody(SILGenFunction &SGF, // Call the native function. SGFContext C(canEmitIntoInit ? init.get() : nullptr); - ManagedValue result = SGF.emitMonomorphicApply(loc, fn, args, - formalNativeResultType, - formalNativeResultType, - ApplyOptions(), - llvm::None, llvm::None, C) - .getAsSingleValue(SGF, loc); + ManagedValue result = + SGF.emitMonomorphicApply(loc, fn, args, formalNativeResultType, + formalNativeResultType, ApplyOptions(), + llvm::None, llvm::None, C) + .getAsSingleValue(SGF, loc); // Bridge the result back to ObjC. if (!canEmitIntoInit) { @@ -915,14 +914,13 @@ static void buildBlockToFuncThunkBody(SILGenFunction &SGF, : nullptr; // Call the block. - ManagedValue result = SGF.emitMonomorphicApply(loc, block, args, - formalBlockTy.getResult(), - formalResultType, - ApplyOptions(), - /*override CC*/ SILFunctionTypeRepresentation::Block, - /*foreign error*/ llvm::None, - SGFContext(init.get())) - .getAsSingleValue(SGF, loc); + ManagedValue result = + SGF.emitMonomorphicApply( + loc, block, args, formalBlockTy.getResult(), formalResultType, + ApplyOptions(), + /*override CC*/ SILFunctionTypeRepresentation::Block, + /*foreign error*/ llvm::None, SGFContext(init.get())) + .getAsSingleValue(SGF, loc); SILValue r; @@ -1319,16 +1317,14 @@ static CanAnyFunctionType substGenericArgs(CanAnyFunctionType fnType, } /// Bridge argument types and adjust retain count conventions for an ObjC thunk. -static SILFunctionType *emitObjCThunkArguments(SILGenFunction &SGF, - SILLocation loc, - SILDeclRef thunk, - SmallVectorImpl &args, - SILValue &foreignErrorSlot, - SILValue &foreignAsyncSlot, - llvm::Optional &foreignError, - llvm::Optional &foreignAsync, - CanType &nativeFormalResultTy, - CanType &bridgedFormalResultTy) { +static SILFunctionType * +emitObjCThunkArguments(SILGenFunction &SGF, SILLocation loc, SILDeclRef thunk, + SmallVectorImpl &args, + SILValue &foreignErrorSlot, SILValue &foreignAsyncSlot, + llvm::Optional &foreignError, + llvm::Optional &foreignAsync, + CanType &nativeFormalResultTy, + CanType &bridgedFormalResultTy) { SILDeclRef native = thunk.asForeign(false); auto subs = SGF.F.getForwardingSubstitutionMap(); @@ -2299,8 +2295,8 @@ void SILGenFunction::emitForeignToNativeThunk(SILDeclRef thunk) { ArgumentScope argScope(*this, fd); ManagedValue resultMV = emitApply(std::move(resultPlan), std::move(argScope), fd, - ManagedValue::forUnmanaged(fn), subs, args, - calleeTypeInfo, ApplyOptions(), context, llvm::None) + ManagedValue::forUnmanaged(fn), subs, args, calleeTypeInfo, + ApplyOptions(), context, llvm::None) .getAsSingleValue(*this, fd); if (indirectResult) { diff --git a/lib/SILGen/SILGenBuilder.cpp b/lib/SILGen/SILGenBuilder.cpp index 96a04a49904..4f960f9a9bf 100644 --- a/lib/SILGen/SILGenBuilder.cpp +++ b/lib/SILGen/SILGenBuilder.cpp @@ -558,9 +558,8 @@ ManagedValue SILGenBuilder::createInputFunctionArgument( isFormalParameterPack); } -ManagedValue -SILGenBuilder::createInputFunctionArgument(SILType type, - llvm::Optional inputLoc) { +ManagedValue SILGenBuilder::createInputFunctionArgument( + SILType type, llvm::Optional inputLoc) { assert(inputLoc.has_value() && "This optional is only for overload resolution " "purposes! Do not pass in None here!"); return ::createInputFunctionArgument(*this, type, *inputLoc); diff --git a/lib/SILGen/SILGenBuiltin.cpp b/lib/SILGen/SILGenBuiltin.cpp index f8d7fde618b..7d19030bf13 100644 --- a/lib/SILGen/SILGenBuiltin.cpp +++ b/lib/SILGen/SILGenBuiltin.cpp @@ -37,11 +37,9 @@ using namespace Lowering; /// /// Because these are builtin operations, we can make some structural /// assumptions about the expression used to call them. -static llvm::Optional> -decomposeArguments(SILGenFunction &SGF, - SILLocation loc, - PreparedArguments &&args, - unsigned expectedCount) { +static llvm::Optional> +decomposeArguments(SILGenFunction &SGF, SILLocation loc, + PreparedArguments &&args, unsigned expectedCount) { SmallVector result; auto sources = std::move(args).getSources(); @@ -1795,7 +1793,7 @@ SpecializedEmitter::forDecl(SILGenModule &SGM, SILDeclRef function) { if (function.kind != SILDeclRef::Kind::Func) return llvm::None; if (!function.hasDecl()) - return llvm::None; + return llvm::None; ValueDecl *decl = function.getDecl(); if (!isa(decl->getDeclContext())) return llvm::None; diff --git a/lib/SILGen/SILGenConstructor.cpp b/lib/SILGen/SILGenConstructor.cpp index e4ae8c95713..e48f4defbcf 100644 --- a/lib/SILGen/SILGenConstructor.cpp +++ b/lib/SILGen/SILGenConstructor.cpp @@ -463,7 +463,7 @@ static void emitImplicitValueConstructor(SILGenFunction &SGF, ->lookThroughAllOptionalTypes()->is()) { auto resultTy = cast(arg.getType()).getResult(); arg = SGF.emitMonomorphicApply( - Loc, std::move(arg).getAsSingleValue(SGF, Loc), { }, resultTy, + Loc, std::move(arg).getAsSingleValue(SGF, Loc), {}, resultTy, resultTy, ApplyOptions(), llvm::None, llvm::None); } } @@ -1006,8 +1006,7 @@ static void emitNonDefaultDistributedActorInitialization( } void SILGenFunction::emitConstructorPrologActorHop( - SILLocation loc, - llvm::Optional maybeIso) { + SILLocation loc, llvm::Optional maybeIso) { loc = loc.asAutoGenerated(); if (maybeIso) { if (auto executor = emitExecutor(loc, *maybeIso, llvm::None)) { @@ -1160,8 +1159,7 @@ void SILGenFunction::emitClassConstructorInitializer(ConstructorDecl *ctor) { // Create a basic block to jump to for the implicit 'self' return. // We won't emit the block until after we've emitted the body. - prepareEpilog(llvm::None, ctor->hasThrows(), - CleanupLocation(endOfInitLoc)); + prepareEpilog(llvm::None, ctor->hasThrows(), CleanupLocation(endOfInitLoc)); auto resultType = ctor->mapTypeIntoContext(ctor->getResultInterfaceType()); diff --git a/lib/SILGen/SILGenConvert.cpp b/lib/SILGen/SILGenConvert.cpp index 5eec401b36f..696edf60498 100644 --- a/lib/SILGen/SILGenConvert.cpp +++ b/lib/SILGen/SILGenConvert.cpp @@ -1529,7 +1529,8 @@ Lowering::canPeepholeConversions(SILGenFunction &SGF, outerConversion.getKind() == Conversion::ForceAndBridgeToObjC; if (forced) { sourceType = sourceType.getOptionalObjectType(); - if (!sourceType) return llvm::None; + if (!sourceType) + return llvm::None; intermediateType = intermediateType.getOptionalObjectType(); assert(intermediateType); } @@ -1603,4 +1604,3 @@ Lowering::canPeepholeConversions(SILGenFunction &SGF, } llvm_unreachable("bad kind"); } - diff --git a/lib/SILGen/SILGenDecl.cpp b/lib/SILGen/SILGenDecl.cpp index eec845012ec..cb99687a311 100644 --- a/lib/SILGen/SILGenDecl.cpp +++ b/lib/SILGen/SILGenDecl.cpp @@ -534,7 +534,7 @@ public: // The variable may have its lifetime extended by a closure, heap-allocate // it using a box. - + llvm::Optional DbgVar; if (generateDebugInfo) DbgVar = SILDebugVariable(decl->isLet(), ArgNo); @@ -1975,8 +1975,8 @@ CleanupHandle SILGenFunction::enterAsyncLetCleanup(SILValue alet, /// Create a LocalVariableInitialization for the uninitialized var. InitializationPtr SILGenFunction::emitLocalVariableWithCleanup( - VarDecl *vd, llvm::Optional kind, unsigned ArgNo, - bool generateDebugInfo) { + VarDecl *vd, llvm::Optional kind, + unsigned ArgNo, bool generateDebugInfo) { return InitializationPtr(new LocalVariableInitialization( vd, kind, ArgNo, generateDebugInfo, *this)); } diff --git a/lib/SILGen/SILGenDynamicCast.cpp b/lib/SILGen/SILGenDynamicCast.cpp index 205739c7003..5b78475ae55 100644 --- a/lib/SILGen/SILGenDynamicCast.cpp +++ b/lib/SILGen/SILGenDynamicCast.cpp @@ -490,9 +490,9 @@ RValue Lowering::emitConditionalCheckedCast( }, // The failure path. [&](llvm::Optional Value) { - // We always are performing a take here, so Value should be llvm::None since - // the - // object should have been destroyed immediately in the fail block. + // We always are performing a take here, so Value should be llvm::None + // since the object should have been destroyed immediately in the fail + // block. assert(!Value.has_value() && "Expected a take_always consumption kind"); auto noneDecl = SGF.getASTContext().getOptionalNoneDecl(); diff --git a/lib/SILGen/SILGenEpilog.cpp b/lib/SILGen/SILGenEpilog.cpp index 59a31cd8d6e..1d57122f2c3 100644 --- a/lib/SILGen/SILGenEpilog.cpp +++ b/lib/SILGen/SILGenEpilog.cpp @@ -21,8 +21,7 @@ using namespace swift; using namespace Lowering; void SILGenFunction::prepareEpilog(llvm::Optional directResultType, - bool isThrowing, - CleanupLocation CleanupL) { + bool isThrowing, CleanupLocation CleanupL) { auto *epilogBB = createBasicBlock(); // If we have any direct results, receive them via BB arguments. diff --git a/lib/SILGen/SILGenExpr.cpp b/lib/SILGen/SILGenExpr.cpp index 4f291a4b004..1db2a8da1a3 100644 --- a/lib/SILGen/SILGenExpr.cpp +++ b/lib/SILGen/SILGenExpr.cpp @@ -566,7 +566,7 @@ namespace { BridgingConversion() : SubExpr(nullptr) {} BridgingConversion(Expr *sub, llvm::Optional kind, unsigned depth) - : SubExpr(sub), Kind(kind), MaxOptionalDepth(depth) { + : SubExpr(sub), Kind(kind), MaxOptionalDepth(depth) { assert(!kind || Conversion::isBridgingKind(*kind)); } @@ -643,9 +643,10 @@ static BridgingConversion getBridgingConversion(Expr *E) { // If we peeked through an opening, and we didn't recognize a specific // pattern above involving the opaque value, make sure we use the opening // as the final expression instead of accidentally look through it. - if (open) return { open, llvm::None, 0 }; + if (open) + return {open, llvm::None, 0}; - return { E, llvm::None, 0 }; + return {E, llvm::None, 0}; } /// If the given expression represents a bridging conversion, emit it with @@ -2537,8 +2538,8 @@ SILGenFunction::emitApplyOfDefaultArgGenerator(SILLocation loc, emitCaptures(loc, generator, CaptureEmission::ImmediateApplication, captures); - return emitApply(std::move(resultPtr), std::move(argScope), loc, fnRef, - subs, captures, calleeTypeInfo, ApplyOptions(), C, llvm::None); + return emitApply(std::move(resultPtr), std::move(argScope), loc, fnRef, subs, + captures, calleeTypeInfo, ApplyOptions(), C, llvm::None); } RValue SILGenFunction::emitApplyOfStoredPropertyInitializer( @@ -2560,8 +2561,8 @@ RValue SILGenFunction::emitApplyOfStoredPropertyInitializer( ResultPlanPtr resultPlan = ResultPlanBuilder::computeResultPlan(*this, calleeTypeInfo, loc, C); ArgumentScope argScope(*this, loc); - return emitApply(std::move(resultPlan), std::move(argScope), loc, fnRef, - subs, {}, calleeTypeInfo, ApplyOptions(), C, llvm::None); + return emitApply(std::move(resultPlan), std::move(argScope), loc, fnRef, subs, + {}, calleeTypeInfo, ApplyOptions(), C, llvm::None); } RValue RValueEmitter::visitDestructureTupleExpr(DestructureTupleExpr *E, @@ -3022,14 +3023,11 @@ static SILFunction *getOrCreateKeyPathGetter(SILGenModule &SGM, ParameterConvention::Direct_Unowned}); SILResultInfo result(loweredPropTy, ResultConvention::Indirect); - - return SILFunctionType::get(genericSig, - SILFunctionType::ExtInfo::getThin(), - SILCoroutineKind::None, - ParameterConvention::Direct_Unowned, - params, {}, result, llvm::None, - SubstitutionMap(), SubstitutionMap(), - SGM.getASTContext()); + + return SILFunctionType::get( + genericSig, SILFunctionType::ExtInfo::getThin(), SILCoroutineKind::None, + ParameterConvention::Direct_Unowned, params, {}, result, llvm::None, + SubstitutionMap(), SubstitutionMap(), SGM.getASTContext()); }(); // Find the function and see if we already created it. @@ -3205,14 +3203,11 @@ static SILFunction *getOrCreateKeyPathSetter(SILGenModule &SGM, if (!indexes.empty()) params.push_back({C.getUnsafeRawPointerType()->getCanonicalType(), ParameterConvention::Direct_Unowned}); - - return SILFunctionType::get(genericSig, - SILFunctionType::ExtInfo::getThin(), - SILCoroutineKind::None, - ParameterConvention::Direct_Unowned, - params, {}, {}, llvm::None, - SubstitutionMap(), SubstitutionMap(), - SGM.getASTContext()); + + return SILFunctionType::get( + genericSig, SILFunctionType::ExtInfo::getThin(), SILCoroutineKind::None, + ParameterConvention::Direct_Unowned, params, {}, {}, llvm::None, + SubstitutionMap(), SubstitutionMap(), SGM.getASTContext()); }(); // Mangle the name of the thunk to see if we already created it. @@ -3289,9 +3284,8 @@ static SILFunction *getOrCreateKeyPathSetter(SILGenModule &SGM, } else { auto baseOrig = ManagedValue::forLValue(baseArg); lv = LValue::forAddress(SGFAccessKind::ReadWrite, baseOrig, llvm::None, - AbstractionPattern::getOpaque(), - baseType); - + AbstractionPattern::getOpaque(), baseType); + // Open an existential lvalue, if necessary. if (baseType->isAnyExistentialType()) { auto opened = subs.getReplacementTypes()[0]->castTo(); @@ -3404,15 +3398,12 @@ getOrCreateKeyPathEqualsAndHash(SILGenModule &SGM, SmallVector results; results.push_back({boolTy, ResultConvention::Unowned}); - - auto signature = SILFunctionType::get(genericSig, - SILFunctionType::ExtInfo::getThin(), - SILCoroutineKind::None, - ParameterConvention::Direct_Unowned, - params, /*yields*/ {}, results, llvm::None, - SubstitutionMap(), SubstitutionMap(), - C); - + + auto signature = SILFunctionType::get( + genericSig, SILFunctionType::ExtInfo::getThin(), SILCoroutineKind::None, + ParameterConvention::Direct_Unowned, params, /*yields*/ {}, results, + llvm::None, SubstitutionMap(), SubstitutionMap(), C); + // Mangle the name of the thunk to see if we already created it. auto name = Mangle::ASTMangler() .mangleKeyPathEqualsHelper(indexTypes, genericSig, expansion); @@ -3489,12 +3480,10 @@ getOrCreateKeyPathEqualsAndHash(SILGenModule &SGM, equatable); auto equalsSubstTy = equalsTy.castTo()->substGenericArgs( SGM.M, equatableSub, TypeExpansionContext(subSGF.F)); - auto equalsInfo = CalleeTypeInfo(equalsSubstTy, - AbstractionPattern(boolTy), boolTy, - llvm::None, - llvm::None, - ImportAsMemberStatus()); - + auto equalsInfo = + CalleeTypeInfo(equalsSubstTy, AbstractionPattern(boolTy), boolTy, + llvm::None, llvm::None, ImportAsMemberStatus()); + Scope branchScope(subSGF, loc); SILValue lhsEltAddr = lhsAddr; @@ -3529,13 +3518,13 @@ getOrCreateKeyPathEqualsAndHash(SILGenModule &SGM, auto equalsResultPlan = ResultPlanBuilder::computeResultPlan(subSGF, equalsInfo, loc, SGFContext()); ArgumentScope argScope(subSGF, loc); - isEqual = subSGF - .emitApply(std::move(equalsResultPlan), std::move(argScope), - loc, ManagedValue::forUnmanaged(equalsWitness), - equatableSub, - {lhsArg, rhsArg, metatyValue}, - equalsInfo, ApplyOptions(), SGFContext(), llvm::None) - .getUnmanagedSingleValue(subSGF, loc); + isEqual = + subSGF + .emitApply(std::move(equalsResultPlan), std::move(argScope), + loc, ManagedValue::forUnmanaged(equalsWitness), + equatableSub, {lhsArg, rhsArg, metatyValue}, + equalsInfo, ApplyOptions(), SGFContext(), llvm::None) + .getUnmanagedSingleValue(subSGF, loc); } branchScope.pop(); @@ -3581,14 +3570,12 @@ getOrCreateKeyPathEqualsAndHash(SILGenModule &SGM, SmallVector results; results.push_back({intTy, ResultConvention::Unowned}); - - auto signature = SILFunctionType::get(genericSig, - SILFunctionType::ExtInfo::getThin(), - SILCoroutineKind::None, - ParameterConvention::Direct_Unowned, - params, /*yields*/ {}, results, llvm::None, - SubstitutionMap(), SubstitutionMap(), C); - + + auto signature = SILFunctionType::get( + genericSig, SILFunctionType::ExtInfo::getThin(), SILCoroutineKind::None, + ParameterConvention::Direct_Unowned, params, /*yields*/ {}, results, + llvm::None, SubstitutionMap(), SubstitutionMap(), C); + // Mangle the name of the thunk to see if we already created it. SmallString<64> nameBuf; @@ -4796,10 +4783,11 @@ namespace { /// A flattened list of l-values. SmallVectorImpl> &Results; + public: TupleLValueEmitter(SILGenFunction &SGF, SGFAccessKind accessKind, SmallVectorImpl> &results) - : SGF(SGF), TheAccessKind(accessKind), Results(results) {} + : SGF(SGF), TheAccessKind(accessKind), Results(results) {} // If the destination is a tuple, recursively destructure. void visitTupleExpr(TupleExpr *E) { @@ -4837,7 +4825,7 @@ namespace { public: TupleLValueAssigner(SILGenFunction &SGF, SILLocation assignLoc, SmallVectorImpl> &destLVs) - : SGF(SGF), AssignLoc(assignLoc), DestLVQueue(destLVs) {} + : SGF(SGF), AssignLoc(assignLoc), DestLVQueue(destLVs) {} /// Top-level entrypoint. void emit(CanType destType, RValue &&src) { @@ -4979,7 +4967,7 @@ namespace { public: PatternLValueEmitter(SILGenFunction &SGF, SGFAccessKind accessKind, SmallVectorImpl> &results) - : SGF(SGF), TheAccessKind(accessKind), Results(results) {} + : SGF(SGF), TheAccessKind(accessKind), Results(results) {} #define USE_SUBPATTERN(Kind) \ Type visit##Kind##Pattern(Kind##Pattern *pattern) { \ diff --git a/lib/SILGen/SILGenForeignError.cpp b/lib/SILGen/SILGenForeignError.cpp index cbd42c996b0..9f8ba4864f9 100644 --- a/lib/SILGen/SILGenForeignError.cpp +++ b/lib/SILGen/SILGenForeignError.cpp @@ -248,8 +248,8 @@ emitBridgeReturnValueForForeignError(SILLocation loc, llvm_unreachable("bad foreign error convention kind"); } -static FunctionSection -functionSectionForConvention(llvm::Optional foreignAsync) { +static FunctionSection functionSectionForConvention( + llvm::Optional foreignAsync) { // If there is a foreign async convention too, the error block branches to // the block awaiting the continuation. return foreignAsync ? FunctionSection::Ordinary : FunctionSection::Postmatter; @@ -258,7 +258,8 @@ functionSectionForConvention(llvm::Optional foreignAsync /// Step out of the current control flow to emit a foreign error block, /// which loads from the error slot and jumps to the error slot. SILValue SILGenFunction::emitForeignErrorBlock( - SILLocation loc, SILBasicBlock *errorBB, llvm::Optional errorSlot, + SILLocation loc, SILBasicBlock *errorBB, + llvm::Optional errorSlot, llvm::Optional foreignAsync) { SILGenSavedInsertionPoint savedIP(*this, errorBB, functionSectionForConvention(foreignAsync)); @@ -304,11 +305,10 @@ SILValue SILGenFunction::emitForeignErrorBlock( /// Perform a foreign error check by testing whether the call result is zero. /// The call result is otherwise ignored. -static SILValue -emitResultIsZeroErrorCheck(SILGenFunction &SGF, SILLocation loc, - ManagedValue result, ManagedValue errorSlot, - bool suppressErrorCheck, bool zeroIsError, - llvm::Optional foreignAsync) { +static SILValue emitResultIsZeroErrorCheck( + SILGenFunction &SGF, SILLocation loc, ManagedValue result, + ManagedValue errorSlot, bool suppressErrorCheck, bool zeroIsError, + llvm::Optional foreignAsync) { // Just ignore the call result if we're suppressing the error check. if (suppressErrorCheck) { return SILValue(); @@ -389,10 +389,10 @@ emitResultIsNilErrorCheck(SILGenFunction &SGF, SILLocation loc, } /// Perform a foreign error check by testing whether the error was nil. -static SILValue -emitErrorIsNonNilErrorCheck(SILGenFunction &SGF, SILLocation loc, - ManagedValue errorSlot, bool suppressErrorCheck, - llvm::Optional foreignAsync) { +static SILValue emitErrorIsNonNilErrorCheck( + SILGenFunction &SGF, SILLocation loc, ManagedValue errorSlot, + bool suppressErrorCheck, + llvm::Optional foreignAsync) { // If we're suppressing the check, just don't check. if (suppressErrorCheck) return SILValue(); @@ -416,7 +416,8 @@ emitErrorIsNonNilErrorCheck(SILGenFunction &SGF, SILLocation loc, // in the errorSlot as our BB argument so we can pass ownership correctly. In // emitForeignErrorBlock, we will create the appropriate cleanup for the // argument. - SILValue error = SGF.emitForeignErrorBlock(loc, errorBB, llvm::None, foreignAsync); + SILValue error = + SGF.emitForeignErrorBlock(loc, errorBB, llvm::None, foreignAsync); // Return the result. SGF.B.emitBlock(contBB); diff --git a/lib/SILGen/SILGenFunction.cpp b/lib/SILGen/SILGenFunction.cpp index b4d811d5078..5116fce2d30 100644 --- a/lib/SILGen/SILGenFunction.cpp +++ b/lib/SILGen/SILGenFunction.cpp @@ -212,10 +212,9 @@ DeclName SILGenModule::getMagicFunctionName(SILDeclRef ref) { llvm_unreachable("Unhandled SILDeclRefKind in switch."); } -SILDebugLocation -SILGenFunction::getSILDebugLocation(SILBuilder &B, SILLocation Loc, - llvm::Optional CurDebugLocOverride, - bool ForMetaInstruction) { +SILDebugLocation SILGenFunction::getSILDebugLocation( + SILBuilder &B, SILLocation Loc, + llvm::Optional CurDebugLocOverride, bool ForMetaInstruction) { const SILDebugScope *Scope = B.getCurrentDebugScope(); if (!Scope) Scope = F.getDebugScope(); @@ -376,12 +375,13 @@ const SILDebugScope *SILGenFunction::getMacroScope(SourceLoc SLoc) { SILGenFunctionBuilder B(SGM); auto &ASTContext = SGM.M.getASTContext(); auto ExtInfo = SILFunctionType::ExtInfo::getThin(); - auto FunctionType = SILFunctionType::get( - nullptr, ExtInfo, SILCoroutineKind::None, - ParameterConvention::Direct_Unowned, /*Params*/ {}, - /*yields*/ - {}, - /*Results*/ {}, llvm::None, SubstitutionMap(), SubstitutionMap(), ASTContext); + auto FunctionType = + SILFunctionType::get(nullptr, ExtInfo, SILCoroutineKind::None, + ParameterConvention::Direct_Unowned, /*Params*/ {}, + /*yields*/ + {}, + /*Results*/ {}, llvm::None, SubstitutionMap(), + SubstitutionMap(), ASTContext); StringRef MacroName = ASTContext.getIdentifier(Macro.Name).str(); RegularLocation MacroLoc(Macro.SLoc); // Use the ExpansionLoc as the location so IRGenDebugInfo can extract the @@ -1150,8 +1150,8 @@ void SILGenFunction::emitArtificialTopLevel(Decl *mainDecl) { auto NSStringFromClassType = SILFunctionType::get( nullptr, extInfo, SILCoroutineKind::None, paramConvention, params, - /*yields*/ {}, resultInfos, /*error result*/ llvm::None, SubstitutionMap(), - SubstitutionMap(), ctx); + /*yields*/ {}, resultInfos, /*error result*/ llvm::None, + SubstitutionMap(), SubstitutionMap(), ctx); auto NSStringFromClassFn = builder.getOrCreateFunction( mainClass, "NSStringFromClass", SILLinkage::PublicExternal, diff --git a/lib/SILGen/SILGenFunction.h b/lib/SILGen/SILGenFunction.h index 1465f0e5c6d..44e27b785ee 100644 --- a/lib/SILGen/SILGenFunction.h +++ b/lib/SILGen/SILGenFunction.h @@ -692,9 +692,12 @@ public: return SGM.Types.getConstantInfo(context, constant); } - llvm::Optional getStaticEnforcement(VarDecl *var = nullptr); - llvm::Optional getDynamicEnforcement(VarDecl *var = nullptr); - llvm::Optional getUnknownEnforcement(VarDecl *var = nullptr); + llvm::Optional + getStaticEnforcement(VarDecl *var = nullptr); + llvm::Optional + getDynamicEnforcement(VarDecl *var = nullptr); + llvm::Optional + getUnknownEnforcement(VarDecl *var = nullptr); SourceManager &getSourceManager() { return SGM.M.getASTContext().SourceMgr; } std::string getMagicFileIDString(SourceLoc loc); @@ -870,9 +873,9 @@ public: /// Generate a nullary function that has the given result interface type and /// body. - void emitGeneratorFunction(SILDeclRef function, Type resultInterfaceType, - BraceStmt *body, - llvm::Optional pattern = llvm::None); + void emitGeneratorFunction( + SILDeclRef function, Type resultInterfaceType, BraceStmt *body, + llvm::Optional pattern = llvm::None); /// Generate an ObjC-compatible destructor (-dealloc). void emitObjCDestructor(SILDeclRef dtor); @@ -898,10 +901,8 @@ public: /// thunks. void emitProtocolWitness(AbstractionPattern reqtOrigTy, CanAnyFunctionType reqtSubstTy, - SILDeclRef requirement, - SubstitutionMap reqtSubs, - SILDeclRef witness, - SubstitutionMap witnessSubs, + SILDeclRef requirement, SubstitutionMap reqtSubs, + SILDeclRef witness, SubstitutionMap witnessSubs, IsFreeFunctionWitness_t isFree, bool isSelfConformance, llvm::Optional enterIsolation); @@ -1027,9 +1028,9 @@ public: /// back to what was previously the current executor after the actor-isolated /// region ends. Invoke \c emit on the breadcrumb to /// restore the previously-active executor. - ExecutorBreadcrumb emitHopToTargetActor(SILLocation loc, - llvm::Optional actorIso, - llvm::Optional actorSelf); + ExecutorBreadcrumb + emitHopToTargetActor(SILLocation loc, llvm::Optional actorIso, + llvm::Optional actorSelf); /// Emit a hop to the target executor, returning a breadcrumb with enough /// enough information to hop back. @@ -1061,8 +1062,8 @@ public: /// Emit the executor for the given actor isolation. llvm::Optional emitExecutor(SILLocation loc, - ActorIsolation isolation, - llvm::Optional maybeSelf); + ActorIsolation isolation, + llvm::Optional maybeSelf); /// Emit the executor value that corresponds to the generic (concurrent) /// executor. @@ -1099,18 +1100,18 @@ public: /// emitProlog - Generates prolog code to allocate and clean up mutable /// storage for closure captures and local arguments. - void emitProlog(CaptureInfo captureInfo, - ParameterList *paramList, ParamDecl *selfParam, - DeclContext *DC, Type resultType, - bool throws, SourceLoc throwsLoc, - llvm::Optional origClosureType = llvm::None); + void + emitProlog(CaptureInfo captureInfo, ParameterList *paramList, + ParamDecl *selfParam, DeclContext *DC, Type resultType, + bool throws, SourceLoc throwsLoc, + llvm::Optional origClosureType = llvm::None); /// A simpler version of emitProlog /// \returns the number of variables in paramPatterns. - uint16_t emitBasicProlog(ParameterList *paramList, ParamDecl *selfParam, - Type resultType, DeclContext *DC, - bool throws, SourceLoc throwsLoc, - unsigned numIgnoredTrailingParameters, - llvm::Optional origClosureType = llvm::None); + uint16_t emitBasicProlog( + ParameterList *paramList, ParamDecl *selfParam, Type resultType, + DeclContext *DC, bool throws, SourceLoc throwsLoc, + unsigned numIgnoredTrailingParameters, + llvm::Optional origClosureType = llvm::None); /// Create SILArguments in the entry block that bind a single value /// of the given parameter suitably for being forwarded. @@ -1131,8 +1132,8 @@ public: /// \param isThrowing If true, create an error epilog block. /// \param L The SILLocation which should be associated with /// cleanup instructions. - void prepareEpilog(llvm::Optional directResultType, - bool isThrowing, CleanupLocation L); + void prepareEpilog(llvm::Optional directResultType, bool isThrowing, + CleanupLocation L); void prepareRethrowEpilog(CleanupLocation l); void prepareCoroutineUnwindEpilog(CleanupLocation l); @@ -1150,8 +1151,8 @@ public: /// the ReturnLocation (This happens in case the predecessor block is /// merged with the epilog block.) std::pair, SILLocation> - emitEpilogBB(SILLocation TopLevelLoc); - + emitEpilogBB(SILLocation TopLevelLoc); + /// Emits a standard epilog which runs top-level cleanups then returns /// the function return value, if any. This can be customized by clients, who /// set UsesCustomEpilog to true, and optionally inject their own code into @@ -1437,7 +1438,8 @@ public: /// specified Initialization buffer(s). This avoids an allocation and copy if /// the result would be allocated into temporary memory normally. /// The location defaults to \c E. - void emitExprInto(Expr *E, Initialization *I, llvm::Optional L = llvm::None); + void emitExprInto(Expr *E, Initialization *I, + llvm::Optional L = llvm::None); /// Emit the given expression as an r-value. RValue emitRValue(Expr *E, SGFContext C = SGFContext()); @@ -1600,12 +1602,10 @@ public: SILDeclRef accessor); RValue emitGetAccessor( - SILLocation loc, SILDeclRef getter, - SubstitutionMap substitutions, + SILLocation loc, SILDeclRef getter, SubstitutionMap substitutions, ArgumentSource &&optionalSelfValue, bool isSuper, - bool isDirectAccessorUse, - PreparedArguments &&optionalSubscripts, SGFContext C, - bool isOnSelfParameter, + bool isDirectAccessorUse, PreparedArguments &&optionalSubscripts, + SGFContext C, bool isOnSelfParameter, llvm::Optional implicitActorHopTarget = llvm::None); void emitSetAccessor(SILLocation loc, SILDeclRef setter, @@ -1851,7 +1851,7 @@ public: SILLocation loc, ManagedValue fn, SubstitutionMap subs, ArrayRef args, const CalleeTypeInfo &calleeTypeInfo, ApplyOptions options, - SGFContext evalContext, + SGFContext evalContext, llvm::Optional implicitActorHopTarget); RValue emitApplyOfDefaultArgGenerator(SILLocation loc, @@ -1878,15 +1878,12 @@ public: /// A convenience method for emitApply that just handles monomorphic /// applications. - RValue emitMonomorphicApply(SILLocation loc, - ManagedValue fn, - ArrayRef args, - CanType foreignResultType, - CanType nativeResultType, - ApplyOptions options, - llvm::Optional overrideRep, - const llvm::Optional &foreignError, - SGFContext ctx = SGFContext()); + RValue emitMonomorphicApply( + SILLocation loc, ManagedValue fn, ArrayRef args, + CanType foreignResultType, CanType nativeResultType, ApplyOptions options, + llvm::Optional overrideRep, + const llvm::Optional &foreignError, + SGFContext ctx = SGFContext()); RValue emitApplyOfLibraryIntrinsic(SILLocation loc, FuncDecl *fn, @@ -2129,16 +2126,17 @@ public: SILValue foreignErrorSlot, const ForeignErrorConvention &foreignError); - SILValue emitForeignErrorBlock(SILLocation loc, SILBasicBlock *errorBB, - llvm::Optional errorSlot, - llvm::Optional foreignAsync); + SILValue + emitForeignErrorBlock(SILLocation loc, SILBasicBlock *errorBB, + llvm::Optional errorSlot, + llvm::Optional foreignAsync); - SILValue emitForeignErrorCheck(SILLocation loc, - SmallVectorImpl &directResults, - ManagedValue errorSlot, - bool suppressErrorCheck, - const ForeignErrorConvention &foreignError, - llvm::Optional foreignAsync); + SILValue + emitForeignErrorCheck(SILLocation loc, + SmallVectorImpl &directResults, + ManagedValue errorSlot, bool suppressErrorCheck, + const ForeignErrorConvention &foreignError, + llvm::Optional foreignAsync); //===--------------------------------------------------------------------===// // Re-abstraction thunks @@ -2779,8 +2777,9 @@ class SILGenSavedInsertionPoint { SILBasicBlock *SavedIP; FunctionSection SavedSection; public: - SILGenSavedInsertionPoint(SILGenFunction &SGF, SILBasicBlock *newIP, - llvm::Optional optSection = llvm::None) + SILGenSavedInsertionPoint( + SILGenFunction &SGF, SILBasicBlock *newIP, + llvm::Optional optSection = llvm::None) : SGF(SGF), SavedIP(SGF.B.getInsertionBB()), SavedSection(SGF.CurFunctionSection) { FunctionSection section = (optSection ? *optSection : SavedSection); diff --git a/lib/SILGen/SILGenGlobalVariable.cpp b/lib/SILGen/SILGenGlobalVariable.cpp index dca14e8ef76..44766de83c6 100644 --- a/lib/SILGen/SILGenGlobalVariable.cpp +++ b/lib/SILGen/SILGenGlobalVariable.cpp @@ -58,9 +58,8 @@ SILGlobalVariable *SILGenModule::getSILGlobalVariable(VarDecl *gDecl, SILType silTy = SILType::getPrimitiveObjectType( M.Types.getLoweredTypeOfGlobal(gDecl)); - auto *silGlobal = SILGlobalVariable::create(M, silLinkage, IsNotSerialized, - mangledName, silTy, - llvm::None, gDecl); + auto *silGlobal = SILGlobalVariable::create( + M, silLinkage, IsNotSerialized, mangledName, silTy, llvm::None, gDecl); silGlobal->setDeclaration(!forDef); return silGlobal; @@ -81,7 +80,7 @@ SILGenFunction::emitGlobalVariableRef(SILLocation loc, VarDecl *var, // variable first. So, we must call this accessor with the same // isolation that the variable itself requires during access. ExecutorBreadcrumb prevExecutor = emitHopToTargetActor(loc, actorIso, - /*base=*/llvm::None); + /*base=*/llvm::None); SILValue addr = B.createApply(loc, accessor, SubstitutionMap(), {}); diff --git a/lib/SILGen/SILGenLValue.cpp b/lib/SILGen/SILGenLValue.cpp index 53133a2fcbc..24bf3c8fd50 100644 --- a/lib/SILGen/SILGenLValue.cpp +++ b/lib/SILGen/SILGenLValue.cpp @@ -610,31 +610,31 @@ static SILValue enterAccessScope(SILGenFunction &SGF, SILLocation loc, SGFAccessKind accessKind, SILAccessEnforcement enforcement, llvm::Optional actorIso) { - auto silAccessKind = SILAccessKind::Modify; - if (isReadAccess(accessKind)) - silAccessKind = SILAccessKind::Read; - else if (isConsumeAccess(accessKind)) - silAccessKind = SILAccessKind::Deinit; + auto silAccessKind = SILAccessKind::Modify; + if (isReadAccess(accessKind)) + silAccessKind = SILAccessKind::Read; + else if (isConsumeAccess(accessKind)) + silAccessKind = SILAccessKind::Deinit; - assert(SGF.isInFormalEvaluationScope() && - "tried to enter access scope without a writeback scope!"); + assert(SGF.isInFormalEvaluationScope() && + "tried to enter access scope without a writeback scope!"); - ExecutorBreadcrumb prevExecutor = - SGF.emitHopToTargetActor(loc, actorIso, base); + ExecutorBreadcrumb prevExecutor = + SGF.emitHopToTargetActor(loc, actorIso, base); - // Enter the access. - addr = SGF.B.createBeginAccess(loc, addr, silAccessKind, enforcement, - /*hasNoNestedConflict=*/false, - /*fromBuiltin=*/false); + // Enter the access. + addr = SGF.B.createBeginAccess(loc, addr, silAccessKind, enforcement, + /*hasNoNestedConflict=*/false, + /*fromBuiltin=*/false); - // Push a writeback to end it. - auto accessedMV = ManagedValue::forLValue(addr); - std::unique_ptr component( - new EndAccessPseudoComponent(typeData, std::move(prevExecutor))); - pushWriteback(SGF, loc, std::move(component), accessedMV, - MaterializedLValue()); + // Push a writeback to end it. + auto accessedMV = ManagedValue::forLValue(addr); + std::unique_ptr component( + new EndAccessPseudoComponent(typeData, std::move(prevExecutor))); + pushWriteback(SGF, loc, std::move(component), accessedMV, + MaterializedLValue()); - return addr; + return addr; } static ManagedValue enterAccessScope(SILGenFunction &SGF, SILLocation loc, @@ -775,9 +775,9 @@ namespace { RefElementComponent(VarDecl *field, LValueOptions options, SILType substFieldType, LValueTypeData typeData, llvm::Optional actorIso) - : PhysicalPathComponent(typeData, RefElementKind, actorIso), - Field(field), SubstFieldType(substFieldType), - IsNonAccessing(options.IsNonAccessing) {} + : PhysicalPathComponent(typeData, RefElementKind, actorIso), + Field(field), SubstFieldType(substFieldType), + IsNonAccessing(options.IsNonAccessing) {} virtual bool isLoadingPure() const override { return true; } @@ -835,9 +835,9 @@ namespace { unsigned ElementIndex; public: TupleElementComponent(unsigned elementIndex, LValueTypeData typeData) - : PhysicalPathComponent(typeData, TupleElementKind, - /*actorIsolation=*/llvm::None), - ElementIndex(elementIndex) {} + : PhysicalPathComponent(typeData, TupleElementKind, + /*actorIsolation=*/llvm::None), + ElementIndex(elementIndex) {} virtual bool isLoadingPure() const override { return true; } @@ -867,8 +867,8 @@ namespace { StructElementComponent(VarDecl *field, SILType substFieldType, LValueTypeData typeData, llvm::Optional actorIso) - : PhysicalPathComponent(typeData, StructElementKind, actorIso), - Field(field), SubstFieldType(substFieldType) {} + : PhysicalPathComponent(typeData, StructElementKind, actorIso), + Field(field), SubstFieldType(substFieldType) {} virtual bool isLoadingPure() const override { return true; } @@ -911,10 +911,10 @@ namespace { bool isImplicitUnwrap; public: ForceOptionalObjectComponent(LValueTypeData typeData, bool isImplicitUnwrap) - : PhysicalPathComponent(typeData, OptionalObjectKind, - /*actorIsolation=*/llvm::None), - isImplicitUnwrap(isImplicitUnwrap) {} - + : PhysicalPathComponent(typeData, OptionalObjectKind, + /*actorIsolation=*/llvm::None), + isImplicitUnwrap(isImplicitUnwrap) {} + ManagedValue project(SILGenFunction &SGF, SILLocation loc, ManagedValue base) && override { // Assert that the optional value is present and return the projected out @@ -933,8 +933,8 @@ namespace { public: OpenOpaqueExistentialComponent(CanArchetypeType openedArchetype, LValueTypeData typeData) - : PhysicalPathComponent(typeData, OpenOpaqueExistentialKind, - /*actorIsolation=*/llvm::None) { + : PhysicalPathComponent(typeData, OpenOpaqueExistentialKind, + /*actorIsolation=*/llvm::None) { assert(getSubstFormalType() == openedArchetype); } @@ -1088,13 +1088,10 @@ namespace { public: ValueComponent(ManagedValue value, llvm::Optional enforcement, - LValueTypeData typeData, - bool isRValue = false, - llvm::Optional actorIso = llvm::None) : - PhysicalPathComponent(typeData, ValueKind, actorIso), - Value(value), - Enforcement(enforcement), - IsRValue(isRValue) { + LValueTypeData typeData, bool isRValue = false, + llvm::Optional actorIso = llvm::None) + : PhysicalPathComponent(typeData, ValueKind, actorIso), Value(value), + Enforcement(enforcement), IsRValue(isRValue) { assert(IsRValue || value.getType().isAddress() || value.getType().isBoxedNonCopyableType(value.getFunction())); } @@ -1162,7 +1159,7 @@ namespace { class BorrowValueComponent : public PhysicalPathComponent { public: BorrowValueComponent(LValueTypeData typeData) - : PhysicalPathComponent(typeData, BorrowValueKind, llvm::None) {} + : PhysicalPathComponent(typeData, BorrowValueKind, llvm::None) {} virtual bool isLoadingPure() const override { return true; } @@ -1412,8 +1409,7 @@ namespace { public: AccessorBasedComponent(PathComponent::KindTy kind, AbstractStorageDecl *decl, SILDeclRef accessor, - bool isSuper, - bool isDirectAccessorUse, + bool isSuper, bool isDirectAccessorUse, SubstitutionMap substitutions, CanType baseFormalType, LValueTypeData typeData, ArgumentList *argListForDiagnostics, @@ -1424,8 +1420,7 @@ namespace { std::move(indices)), Accessor(accessor), IsSuper(isSuper), IsDirectAccessorUse(isDirectAccessorUse), - IsOnSelfParameter(isOnSelfParameter), - Substitutions(substitutions), + IsOnSelfParameter(isOnSelfParameter), Substitutions(substitutions), ActorIso(actorIso) {} AccessorBasedComponent(const AccessorBasedComponent &copied, @@ -1447,27 +1442,20 @@ namespace { class GetterSetterComponent : public AccessorBasedComponent { public: - - GetterSetterComponent(AbstractStorageDecl *decl, - SILDeclRef accessor, - bool isSuper, - bool isDirectAccessorUse, - SubstitutionMap substitutions, - CanType baseFormalType, - LValueTypeData typeData, - ArgumentList *subscriptArgList, - PreparedArguments &&indices, - bool isOnSelfParameter, - llvm::Optional actorIso) - : AccessorBasedComponent(GetterSetterKind, decl, accessor, isSuper, - isDirectAccessorUse, substitutions, - baseFormalType, typeData, subscriptArgList, - std::move(indices), isOnSelfParameter, - actorIso) - { + GetterSetterComponent(AbstractStorageDecl *decl, SILDeclRef accessor, + bool isSuper, bool isDirectAccessorUse, + SubstitutionMap substitutions, CanType baseFormalType, + LValueTypeData typeData, + ArgumentList *subscriptArgList, + PreparedArguments &&indices, bool isOnSelfParameter, + llvm::Optional actorIso) + : AccessorBasedComponent( + GetterSetterKind, decl, accessor, isSuper, isDirectAccessorUse, + substitutions, baseFormalType, typeData, subscriptArgList, + std::move(indices), isOnSelfParameter, actorIso) { assert(getAccessorDecl()->isGetterOrSetter()); } - + GetterSetterComponent(const GetterSetterComponent &copied, SILGenFunction &SGF, SILLocation loc) @@ -2333,9 +2321,9 @@ namespace { PhysicalKeyPathApplicationComponent(LValueTypeData typeData, KeyPathTypeKind typeKind, ManagedValue keyPath) - : PhysicalPathComponent(typeData, PhysicalKeyPathApplicationKind, - /*actorIsolation=*/llvm::None), - TypeKind(typeKind), KeyPath(keyPath) { + : PhysicalPathComponent(typeData, PhysicalKeyPathApplicationKind, + /*actorIsolation=*/llvm::None), + TypeKind(typeKind), KeyPath(keyPath) { assert(typeKind == KPTK_KeyPath || typeKind == KPTK_WritableKeyPath || typeKind == KPTK_ReferenceWritableKeyPath); @@ -3015,14 +3003,10 @@ namespace { }; } -static LValue emitLValueForNonMemberVarDecl(SILGenFunction &SGF, - SILLocation loc, - ConcreteDeclRef declRef, - CanType formalRValueType, - SGFAccessKind accessKind, - LValueOptions options, - AccessSemantics semantics, - llvm::Optional actorIso) { +static LValue emitLValueForNonMemberVarDecl( + SILGenFunction &SGF, SILLocation loc, ConcreteDeclRef declRef, + CanType formalRValueType, SGFAccessKind accessKind, LValueOptions options, + AccessSemantics semantics, llvm::Optional actorIso) { LValue lv; auto *var = cast(declRef.getDecl()); @@ -3063,14 +3047,10 @@ static AccessKind mapAccessKind(SGFAccessKind accessKind) { llvm_unreachable("covered switch"); } -void LValue::addNonMemberVarComponent(SILGenFunction &SGF, SILLocation loc, - VarDecl *var, - SubstitutionMap subs, - LValueOptions options, - SGFAccessKind accessKind, - AccessStrategy strategy, - CanType formalRValueType, - llvm::Optional actorIso) { +void LValue::addNonMemberVarComponent( + SILGenFunction &SGF, SILLocation loc, VarDecl *var, SubstitutionMap subs, + LValueOptions options, SGFAccessKind accessKind, AccessStrategy strategy, + CanType formalRValueType, llvm::Optional actorIso) { struct NonMemberVarAccessEmitter : AccessEmitter { LValue &LV; @@ -3081,12 +3061,11 @@ void LValue::addNonMemberVarComponent(SILGenFunction &SGF, SILLocation loc, NonMemberVarAccessEmitter(SILGenFunction &SGF, SILLocation loc, VarDecl *var, SubstitutionMap subs, SGFAccessKind accessKind, - CanType formalRValueType, - LValueOptions options, + CanType formalRValueType, LValueOptions options, llvm::Optional actorIso, LValue &lv) - : AccessEmitter(SGF, var, subs, accessKind, formalRValueType), - LV(lv), Loc(loc), Options(options), ActorIso(actorIso) {} + : AccessEmitter(SGF, var, subs, accessKind, formalRValueType), LV(lv), + Loc(loc), Options(options), ActorIso(actorIso) {} void emitUsingAddressor(SILDeclRef addressor, bool isDirect, LValueTypeData typeData) { @@ -3346,11 +3325,10 @@ RValue SILGenFunction::emitRValueForNonMemberVarDecl(SILLocation loc, ? Result : Result.copyUnmanaged(*this, loc)); } - LValue lv = emitLValueForNonMemberVarDecl(*this, loc, declRef, - formalRValueType, - SGFAccessKind::OwnedObjectRead, - LValueOptions(), semantics, - /*actorIsolation=*/llvm::None); + LValue lv = emitLValueForNonMemberVarDecl( + *this, loc, declRef, formalRValueType, SGFAccessKind::OwnedObjectRead, + LValueOptions(), semantics, + /*actorIsolation=*/llvm::None); return emitLoadOfLValue(loc, std::move(lv), C); } @@ -3365,8 +3343,8 @@ LValue SILGenLValue::visitDiscardAssignmentExpr(DiscardAssignmentExpr *e, address = SGF.B.createMarkUninitialized(e, address, MarkUninitializedInst::Var); LValue lv; - lv.add(SGF.emitManagedBufferWithCleanup(address), - llvm::None, typeData); + lv.add(SGF.emitManagedBufferWithCleanup(address), llvm::None, + typeData); return lv; } @@ -3434,10 +3412,9 @@ LValue SILGenLValue::visitPackElementExpr(PackElementExpr *e, auto packIndex = SGF.getInnermostPackExpansion()->ExpansionIndex; auto elementAddr = SGF.B.createPackElementGet(e, packIndex, packAddr, elementTy); - return LValue::forAddress(accessKind, - ManagedValue::forLValue(elementAddr), - /*access enforcement*/ llvm::None, - origFormalType, substFormalType); + return LValue::forAddress( + accessKind, ManagedValue::forLValue(elementAddr), + /*access enforcement*/ llvm::None, origFormalType, substFormalType); } } @@ -3452,8 +3429,7 @@ LValue SILGenLValue::visitPackElementExpr(PackElementExpr *e, auto packIndex = activeExpansion->ExpansionIndex; auto elementAddr = SGF.B.createTuplePackElementAddr(e, packIndex, tupleAddr->second, elementTy); - return LValue::forAddress(accessKind, - ManagedValue::forLValue(elementAddr), + return LValue::forAddress(accessKind, ManagedValue::forLValue(elementAddr), /*access enforcement*/ llvm::None, AbstractionPattern(substFormalType), substFormalType); @@ -3463,9 +3439,9 @@ LValue SILGenLValue::visitPackElementExpr(PackElementExpr *e, "emission of 'each' for this kind of expression"); auto loweredTy = SGF.getLoweredType(substFormalType).getAddressType(); auto fakeAddr = ManagedValue::forLValue(SILUndef::get(loweredTy, SGF.F)); - return LValue::forAddress(accessKind, fakeAddr, /*access enforcement*/ llvm::None, - AbstractionPattern(substFormalType), - substFormalType); + return LValue::forAddress( + accessKind, fakeAddr, /*access enforcement*/ llvm::None, + AbstractionPattern(substFormalType), substFormalType); } LValue SILGenLValue::visitDotSyntaxBaseIgnoredExpr(DotSyntaxBaseIgnoredExpr *e, @@ -3661,13 +3637,12 @@ struct MemberStorageAccessEmitter : AccessEmitter { // If any, holds the actor we must switch to when performing the access. llvm::Optional ActorIso; - MemberStorageAccessEmitter(SILGenFunction &SGF, SILLocation loc, - StorageType *storage, SubstitutionMap subs, - bool isSuper, SGFAccessKind accessKind, - CanType formalRValueType, LValueOptions options, - LValue &lv, ArgumentList *argListForDiagnostics, - PreparedArguments &&indices, bool isSelf = false, - llvm::Optional actorIso = llvm::None) + MemberStorageAccessEmitter( + SILGenFunction &SGF, SILLocation loc, StorageType *storage, + SubstitutionMap subs, bool isSuper, SGFAccessKind accessKind, + CanType formalRValueType, LValueOptions options, LValue &lv, + ArgumentList *argListForDiagnostics, PreparedArguments &&indices, + bool isSelf = false, llvm::Optional actorIso = llvm::None) : super(SGF, storage, subs, accessKind, formalRValueType), LV(lv), Options(options), Loc(loc), IsSuper(isSuper), IsOnSelfParameter(isSelf), BaseFormalType(lv.getSubstFormalType()), @@ -3716,16 +3691,11 @@ struct MemberStorageAccessEmitter : AccessEmitter { }; } // end anonymous namespace -void LValue::addMemberVarComponent(SILGenFunction &SGF, SILLocation loc, - VarDecl *var, - SubstitutionMap subs, - LValueOptions options, - bool isSuper, - SGFAccessKind accessKind, - AccessStrategy strategy, - CanType formalRValueType, - bool isOnSelfParameter, - llvm::Optional actorIso) { +void LValue::addMemberVarComponent( + SILGenFunction &SGF, SILLocation loc, VarDecl *var, SubstitutionMap subs, + LValueOptions options, bool isSuper, SGFAccessKind accessKind, + AccessStrategy strategy, CanType formalRValueType, bool isOnSelfParameter, + llvm::Optional actorIso) { struct MemberVarAccessEmitter : MemberStorageAccessEmitter { using MemberStorageAccessEmitter::MemberStorageAccessEmitter; @@ -3936,18 +3906,12 @@ LValue SILGenLValue::visitKeyPathApplicationExpr(KeyPathApplicationExpr *e, return lv; } -void LValue::addMemberSubscriptComponent(SILGenFunction &SGF, SILLocation loc, - SubscriptDecl *decl, - SubstitutionMap subs, - LValueOptions options, - bool isSuper, - SGFAccessKind accessKind, - AccessStrategy strategy, - CanType formalRValueType, - PreparedArguments &&indices, - ArgumentList *argListForDiagnostics, - bool isOnSelfParameter, - llvm::Optional actorIso) { +void LValue::addMemberSubscriptComponent( + SILGenFunction &SGF, SILLocation loc, SubscriptDecl *decl, + SubstitutionMap subs, LValueOptions options, bool isSuper, + SGFAccessKind accessKind, AccessStrategy strategy, CanType formalRValueType, + PreparedArguments &&indices, ArgumentList *argListForDiagnostics, + bool isOnSelfParameter, llvm::Optional actorIso) { struct MemberSubscriptAccessEmitter : MemberStorageAccessEmitter { diff --git a/lib/SILGen/SILGenPattern.cpp b/lib/SILGen/SILGenPattern.cpp index b4523d34a27..d2ccca6958e 100644 --- a/lib/SILGen/SILGenPattern.cpp +++ b/lib/SILGen/SILGenPattern.cpp @@ -422,7 +422,8 @@ public: : SGF(SGF), PatternMatchStmt(S), CompletionHandler(completionHandler) {} - llvm::Optional getSubjectLocationOverride(SILLocation loc) const { + llvm::Optional + getSubjectLocationOverride(SILLocation loc) const { if (auto *Switch = dyn_cast(PatternMatchStmt)) if (!Switch->isImplicit()) return SILLocation(Switch->getSubjectExpr()); @@ -954,7 +955,7 @@ static unsigned getConstructorPrefix(const ClauseMatrix &matrix, } return row - firstRow; } - + /// Select the "necessary column", Maranget's term for the column /// most likely to give an optimal decision tree. /// @@ -1752,7 +1753,8 @@ void PatternMatchEmission::emitIsDispatch(ArrayRef rows, assert(!SGF.B.hasValidInsertionPoint() && "did not end block"); }, // Failure block: branch out to the continuation block. - [&](llvm::Optional mv) { (*innerFailure)(loc); }, rows[0].Count); + [&](llvm::Optional mv) { (*innerFailure)(loc); }, + rows[0].Count); } namespace { diff --git a/lib/SILGen/SILGenPoly.cpp b/lib/SILGen/SILGenPoly.cpp index 401e2b2e84c..d65b9f2297b 100644 --- a/lib/SILGen/SILGenPoly.cpp +++ b/lib/SILGen/SILGenPoly.cpp @@ -4939,15 +4939,10 @@ emitOpenExistentialInSelfConformance(SILGenFunction &SGF, SILLocation loc, } void SILGenFunction::emitProtocolWitness( - AbstractionPattern reqtOrigTy, - CanAnyFunctionType reqtSubstTy, - SILDeclRef requirement, - SubstitutionMap reqtSubs, - SILDeclRef witness, - SubstitutionMap witnessSubs, - IsFreeFunctionWitness_t isFree, - bool isSelfConformance, - llvm::Optional enterIsolation) { + AbstractionPattern reqtOrigTy, CanAnyFunctionType reqtSubstTy, + SILDeclRef requirement, SubstitutionMap reqtSubs, SILDeclRef witness, + SubstitutionMap witnessSubs, IsFreeFunctionWitness_t isFree, + bool isSelfConformance, llvm::Optional enterIsolation) { // FIXME: Disable checks that the protocol witness carries debug info. // Should we carry debug info for witnesses? F.setBare(IsBare); diff --git a/lib/SILGen/SILGenProlog.cpp b/lib/SILGen/SILGenProlog.cpp index eae1c39953a..d60b2fa5e61 100644 --- a/lib/SILGen/SILGenProlog.cpp +++ b/lib/SILGen/SILGenProlog.cpp @@ -768,8 +768,9 @@ private: // If it's a locally mutable parameter, then we need to move the argument // value into a local box to hold the mutated value. // We don't need to mark_uninitialized since we immediately initialize. - auto mutableBox = SGF.emitLocalVariableWithCleanup(pd, - /*uninitialized kind*/ llvm::None); + auto mutableBox = + SGF.emitLocalVariableWithCleanup(pd, + /*uninitialized kind*/ llvm::None); argrv.ensurePlusOne(SGF, loc).forwardInto(SGF, loc, mutableBox.get()); return; } @@ -1133,14 +1134,10 @@ static void emitCaptureArguments(SILGenFunction &SGF, } } -void SILGenFunction::emitProlog(CaptureInfo captureInfo, - ParameterList *paramList, - ParamDecl *selfParam, - DeclContext *DC, - Type resultType, - bool throws, - SourceLoc throwsLoc, - llvm::Optional origClosureType) { +void SILGenFunction::emitProlog( + CaptureInfo captureInfo, ParameterList *paramList, ParamDecl *selfParam, + DeclContext *DC, Type resultType, bool throws, SourceLoc throwsLoc, + llvm::Optional origClosureType) { // Emit the capture argument variables. These are placed last because they // become the first curry level of the SIL function. assert(captureInfo.hasBeenComputed() && @@ -1453,9 +1450,10 @@ SILValue SILGenFunction::emitLoadActorExecutor(SILLocation loc, return actorV; } -ExecutorBreadcrumb SILGenFunction::emitHopToTargetActor(SILLocation loc, - llvm::Optional maybeIso, - llvm::Optional maybeSelf) { +ExecutorBreadcrumb +SILGenFunction::emitHopToTargetActor(SILLocation loc, + llvm::Optional maybeIso, + llvm::Optional maybeSelf) { if (!maybeIso) return ExecutorBreadcrumb(); @@ -1475,9 +1473,9 @@ ExecutorBreadcrumb SILGenFunction::emitHopToTargetExecutor( return breadcrumb; } -llvm::Optional SILGenFunction::emitExecutor( - SILLocation loc, ActorIsolation isolation, - llvm::Optional maybeSelf) { +llvm::Optional +SILGenFunction::emitExecutor(SILLocation loc, ActorIsolation isolation, + llvm::Optional maybeSelf) { switch (isolation.getKind()) { case ActorIsolation::Unspecified: case ActorIsolation::Independent: @@ -1666,14 +1664,11 @@ static void emitIndirectResultParameters(SILGenFunction &SGF, (void)arg; } -uint16_t SILGenFunction::emitBasicProlog(ParameterList *paramList, - ParamDecl *selfParam, - Type resultType, - DeclContext *DC, - bool throws, - SourceLoc throwsLoc, - unsigned numIgnoredTrailingParameters, - llvm::Optional origClosureType) { +uint16_t SILGenFunction::emitBasicProlog( + ParameterList *paramList, ParamDecl *selfParam, Type resultType, + DeclContext *DC, bool throws, SourceLoc throwsLoc, + unsigned numIgnoredTrailingParameters, + llvm::Optional origClosureType) { // Create the indirect result parameters. auto genericSig = DC->getGenericSignatureOfContext(); resultType = resultType->getReducedType(genericSig); diff --git a/lib/SILGen/SILGenThunk.cpp b/lib/SILGen/SILGenThunk.cpp index 9dc37ce1e4d..fe87ba6fedd 100644 --- a/lib/SILGen/SILGenThunk.cpp +++ b/lib/SILGen/SILGenThunk.cpp @@ -248,28 +248,29 @@ SILFunction *SILGenModule::getOrCreateForeignAsyncCompletionHandlerImplFunction( blockType->getClangTypeInfo().getType(), getASTContext().getClangTypeForIRGen(blockStorageTy)); - auto implTy = SILFunctionType::get(sig, - blockType->getExtInfo().intoBuilder() - .withRepresentation(SILFunctionTypeRepresentation::CFunctionPointer) - .withClangFunctionType(newClangTy) - .withIsPseudogeneric((bool)sig) - .build(), - SILCoroutineKind::None, - ParameterConvention::Direct_Unowned, - implArgs, {}, blockType->getResults(), - llvm::None, - SubstitutionMap(), SubstitutionMap(), getASTContext()); + auto implTy = SILFunctionType::get( + sig, + blockType->getExtInfo() + .intoBuilder() + .withRepresentation(SILFunctionTypeRepresentation::CFunctionPointer) + .withClangFunctionType(newClangTy) + .withIsPseudogeneric((bool)sig) + .build(), + SILCoroutineKind::None, ParameterConvention::Direct_Unowned, implArgs, {}, + blockType->getResults(), llvm::None, SubstitutionMap(), SubstitutionMap(), + getASTContext()); auto loc = RegularLocation::getAutoGeneratedLocation(); Mangle::ASTMangler Mangler; auto name = Mangler.mangleObjCAsyncCompletionHandlerImpl( - blockType, resumeType, sig, - convention.completionHandlerFlagParamIndex() - ? llvm::Optional(convention.completionHandlerFlagIsErrorOnZero()) - : llvm::Optional(), - /*predefined*/ false); - + blockType, resumeType, sig, + convention.completionHandlerFlagParamIndex() + ? llvm::Optional( + convention.completionHandlerFlagIsErrorOnZero()) + : llvm::Optional(), + /*predefined*/ false); + SILGenFunctionBuilder builder(*this); auto F = builder.getOrCreateSharedFunction(loc, name, implTy, IsBare, IsTransparent, IsSerialized, diff --git a/lib/SILGen/SILGenType.cpp b/lib/SILGen/SILGenType.cpp index eb76fa14809..02a7b48a27c 100644 --- a/lib/SILGen/SILGenType.cpp +++ b/lib/SILGen/SILGenType.cpp @@ -39,10 +39,9 @@ using namespace swift; using namespace Lowering; - llvm::Optional -SILGenModule::emitVTableMethod(ClassDecl *theClass, - SILDeclRef derived, SILDeclRef base) { +SILGenModule::emitVTableMethod(ClassDecl *theClass, SILDeclRef derived, + SILDeclRef base) { assert(base.kind == derived.kind); auto *baseDecl = cast(base.getDecl()); @@ -907,9 +906,8 @@ static SILFunction *emitSelfConformanceWitness(SILGenModule &SGM, requirement.getDecl()); SGF.emitProtocolWitness(AbstractionPattern(reqtOrigTy), reqtSubstTy, - requirement, reqtSubs, requirement, - witnessSubs, isFree, /*isSelfConformance*/ true, - llvm::None); + requirement, reqtSubs, requirement, witnessSubs, + isFree, /*isSelfConformance*/ true, llvm::None); SGM.emitLazyConformancesForFunction(f); diff --git a/lib/SILGen/SpecializedEmitter.h b/lib/SILGen/SpecializedEmitter.h index 89775f2ed0e..6ac4a41dee3 100644 --- a/lib/SILGen/SpecializedEmitter.h +++ b/lib/SILGen/SpecializedEmitter.h @@ -89,8 +89,8 @@ public: : TheKind(Kind::LateEmitter), TheLateEmitter(emitter) {} /// Try to find an appropriate emitter for the given declaration. - static llvm::Optional - forDecl(SILGenModule &SGM, SILDeclRef decl); + static llvm::Optional forDecl(SILGenModule &SGM, + SILDeclRef decl); bool isEarlyEmitter() const { return TheKind == Kind::EarlyEmitter; } EarlyEmitter *getEarlyEmitter() const { diff --git a/lib/SILOptimizer/Analysis/ARCAnalysis.cpp b/lib/SILOptimizer/Analysis/ARCAnalysis.cpp index 986b4bab2a1..787b06b62db 100644 --- a/lib/SILOptimizer/Analysis/ARCAnalysis.cpp +++ b/lib/SILOptimizer/Analysis/ARCAnalysis.cpp @@ -357,11 +357,10 @@ bool swift::mustGuaranteedUseValue(SILInstruction *User, SILValue Ptr, /// first such instruction. Otherwise return None. We assume that /// Start and End are both in the same basic block. llvm::Optional -swift:: -valueHasARCUsesInInstructionRange(SILValue Op, - SILBasicBlock::iterator Start, - SILBasicBlock::iterator End, - AliasAnalysis *AA) { +swift::valueHasARCUsesInInstructionRange(SILValue Op, + SILBasicBlock::iterator Start, + SILBasicBlock::iterator End, + AliasAnalysis *AA) { assert(Start->getParent() == End->getParent() && "Start and End should be in the same basic block"); @@ -419,11 +418,9 @@ swift::valueHasARCUsesInReverseInstructionRange(SILValue Op, /// if no such instruction exists. We assume that Start and End are both in the /// same basic block. llvm::Optional -swift:: -valueHasARCDecrementOrCheckInInstructionRange(SILValue Op, - SILBasicBlock::iterator Start, - SILBasicBlock::iterator End, - AliasAnalysis *AA) { +swift::valueHasARCDecrementOrCheckInInstructionRange( + SILValue Op, SILBasicBlock::iterator Start, SILBasicBlock::iterator End, + AliasAnalysis *AA) { assert(Start->getParent() == End->getParent() && "Start and End should be in the same basic block"); diff --git a/lib/SILOptimizer/Differentiation/PullbackCloner.cpp b/lib/SILOptimizer/Differentiation/PullbackCloner.cpp index 84a5fc80c8c..48807226f52 100644 --- a/lib/SILOptimizer/Differentiation/PullbackCloner.cpp +++ b/lib/SILOptimizer/Differentiation/PullbackCloner.cpp @@ -652,8 +652,7 @@ private: /// Helper for `getAdjointBuffer`. AllocStackInst *createFunctionLocalAllocation( SILType type, SILLocation loc, bool zeroInitialize = false, - llvm::Optional varInfo = llvm::None) - { + llvm::Optional varInfo = llvm::None) { // Set insertion point for local allocation builder: before the last local // allocation, or at the start of the pullback function's entry if no local // allocations exist yet. diff --git a/lib/SILOptimizer/FunctionSignatureTransforms/FunctionSignatureOpts.cpp b/lib/SILOptimizer/FunctionSignatureTransforms/FunctionSignatureOpts.cpp index 27db8095127..96ccf7362f3 100644 --- a/lib/SILOptimizer/FunctionSignatureTransforms/FunctionSignatureOpts.cpp +++ b/lib/SILOptimizer/FunctionSignatureTransforms/FunctionSignatureOpts.cpp @@ -284,10 +284,11 @@ static bool usesGenerics(SILFunction *F, // Map the parameter, result and error types out of context to get the interface // type. -static void mapInterfaceTypes(SILFunction *F, - MutableArrayRef InterfaceParams, - MutableArrayRef InterfaceResults, - llvm::Optional &InterfaceErrorResult) { +static void +mapInterfaceTypes(SILFunction *F, + MutableArrayRef InterfaceParams, + MutableArrayRef InterfaceResults, + llvm::Optional &InterfaceErrorResult) { for (auto &Param : InterfaceParams) { if (!Param.getInterfaceType()->hasArchetype()) diff --git a/lib/SILOptimizer/LoopTransforms/LoopUnroll.cpp b/lib/SILOptimizer/LoopTransforms/LoopUnroll.cpp index f6631ce24af..ec142480633 100644 --- a/lib/SILOptimizer/LoopTransforms/LoopUnroll.cpp +++ b/lib/SILOptimizer/LoopTransforms/LoopUnroll.cpp @@ -109,9 +109,9 @@ void LoopCloner::cloneLoop() { /// might contain early exits so this is the maximum if no early exits are /// taken. static llvm::Optional getMaxLoopTripCount(SILLoop *Loop, - SILBasicBlock *Preheader, - SILBasicBlock *Header, - SILBasicBlock *Latch) { + SILBasicBlock *Preheader, + SILBasicBlock *Header, + SILBasicBlock *Latch) { // Skip a split backedge. SILBasicBlock *OrigLatch = Latch; diff --git a/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp b/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp index e9f8a4302ca..c0bc86b22b5 100644 --- a/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp +++ b/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp @@ -100,7 +100,8 @@ enum class DIKind : uint8_t { No, Yes, Partial }; } // end anonymous namespace /// This implements the lattice merge operation for 2 optional DIKinds. -static llvm::Optional mergeKinds(llvm::Optional OK1, llvm::Optional OK2) { +static llvm::Optional mergeKinds(llvm::Optional OK1, + llvm::Optional OK2) { // If OK1 is unset, ignore it. if (!OK1.has_value()) return OK2; @@ -126,7 +127,6 @@ static llvm::Optional mergeKinds(llvm::Optional OK1, llvm::Optio return K1; } - namespace { /// AvailabilitySet - This class stores an array of lattice values for tuple /// elements being analyzed for liveness computations. Each element is @@ -172,7 +172,7 @@ namespace { case DIKind::Partial: Data[Elt*2] = true, Data[Elt*2+1] = false; break; } } - + void set(unsigned Elt, llvm::Optional K) { if (!K.has_value()) Data[Elt*2] = true, Data[Elt*2+1] = true; @@ -526,7 +526,8 @@ namespace { void putIntoWorkList(SILBasicBlock *BB, WorkListType &WorkList); void computePredsLiveOut(SILBasicBlock *BB); void getOutAvailability(SILBasicBlock *BB, AvailabilitySet &Result); - void getOutSelfInitialized(SILBasicBlock *BB, llvm::Optional &Result); + void getOutSelfInitialized(SILBasicBlock *BB, + llvm::Optional &Result); bool shouldEmitError(const SILInstruction *Inst); std::string getUninitElementName(const DIMemoryUse &Use); @@ -3405,8 +3406,8 @@ getOutAvailability(SILBasicBlock *BB, AvailabilitySet &Result) { LLVM_DEBUG(llvm::dbgs() << " Result: " << Result << "\n"); } -void LifetimeChecker:: -getOutSelfInitialized(SILBasicBlock *BB, llvm::Optional &Result) { +void LifetimeChecker::getOutSelfInitialized(SILBasicBlock *BB, + llvm::Optional &Result) { computePredsLiveOut(BB); for (auto *Pred : BB->getPredecessorBlocks()) diff --git a/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp b/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp index 4973f45a165..36663cc45cd 100644 --- a/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp +++ b/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp @@ -631,7 +631,7 @@ static llvm::cl::opt ShouldAssertOnFailure( /// would conflict, returns the first recorded access it would conflict /// with. Otherwise, returns llvm::None. static llvm::Optional -shouldReportAccess(const AccessInfo &Info,swift::SILAccessKind Kind, +shouldReportAccess(const AccessInfo &Info, swift::SILAccessKind Kind, const IndexTrieNode *SubPath) { if (Info.alreadyHadConflict()) return llvm::None; diff --git a/lib/SILOptimizer/Mandatory/FlowIsolation.cpp b/lib/SILOptimizer/Mandatory/FlowIsolation.cpp index c95facc8ea5..fb8a2b4838f 100644 --- a/lib/SILOptimizer/Mandatory/FlowIsolation.cpp +++ b/lib/SILOptimizer/Mandatory/FlowIsolation.cpp @@ -156,7 +156,8 @@ public: /// a normal return is reached, along with the block that returns normally. /// Only computed after calling solve(), where it remains None if the function /// doesn't return normally. - llvm::Optional> normalReturn = llvm::None; + llvm::Optional> normalReturn = + llvm::None; /// indicates whether the SILFunction is (or contained in) a deinit. bool forDeinit; diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyWrappedTypeEliminator.cpp b/lib/SILOptimizer/Mandatory/MoveOnlyWrappedTypeEliminator.cpp index 120f0745175..9439ada3bd4 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyWrappedTypeEliminator.cpp +++ b/lib/SILOptimizer/Mandatory/MoveOnlyWrappedTypeEliminator.cpp @@ -221,7 +221,8 @@ struct SILMoveOnlyWrappedTypeEliminatorVisitor // the original function type into a function type without move only. This is // safe since adding/removing moveonlywrapped types is ABI neutral. bool visitApplySite(ApplySite ai) { - auto eliminateMoveOnlyWrapped = [&](TypeBase *type) -> llvm::Optional { + auto eliminateMoveOnlyWrapped = + [&](TypeBase *type) -> llvm::Optional { if (auto *moveType = dyn_cast(type)) return moveType->getInnerType(); return llvm::None; diff --git a/lib/SILOptimizer/Mandatory/PredictableMemOpt.cpp b/lib/SILOptimizer/Mandatory/PredictableMemOpt.cpp index 45b4c432f01..6845c8ea93e 100644 --- a/lib/SILOptimizer/Mandatory/PredictableMemOpt.cpp +++ b/lib/SILOptimizer/Mandatory/PredictableMemOpt.cpp @@ -1546,19 +1546,20 @@ void AvailableValueDataflowContext::updateAvailableValues( if (auto *LI = dyn_cast(Inst)) { // First see if this is a load inst that we are tracking. if (LoadTakeUses.count(LI)) { - updateAvailableValuesHelper(TheMemory, LI, LI->getOperand(), RequiredElts, - Result, ConflictingValues, - /*default*/ - [](unsigned) -> llvm::Optional { - // We never initialize values. We only - // want to invalidate. - return llvm::None; - }, - /*isSafe*/ - [](AvailableValue &, unsigned) -> bool { - // Always assume values conflict. - return false; - }); + updateAvailableValuesHelper( + TheMemory, LI, LI->getOperand(), RequiredElts, Result, + ConflictingValues, + /*default*/ + [](unsigned) -> llvm::Optional { + // We never initialize values. We only + // want to invalidate. + return llvm::None; + }, + /*isSafe*/ + [](AvailableValue &, unsigned) -> bool { + // Always assume values conflict. + return false; + }); return; } } @@ -1596,19 +1597,20 @@ void AvailableValueDataflowContext::updateAvailableValues( if (auto *CAI = dyn_cast(Inst)) { // If we have a load take use, we must be tracking a store of CAI. if (LoadTakeUses.count(CAI)) { - updateAvailableValuesHelper(TheMemory, CAI, CAI->getSrc(), RequiredElts, - Result, ConflictingValues, - /*default*/ - [](unsigned) -> llvm::Optional { - // We never give values default initialized - // values. We only want to invalidate. - return llvm::None; - }, - /*isSafe*/ - [](AvailableValue &, unsigned) -> bool { - // Always assume values conflict. - return false; - }); + updateAvailableValuesHelper( + TheMemory, CAI, CAI->getSrc(), RequiredElts, Result, + ConflictingValues, + /*default*/ + [](unsigned) -> llvm::Optional { + // We never give values default initialized + // values. We only want to invalidate. + return llvm::None; + }, + /*isSafe*/ + [](AvailableValue &, unsigned) -> bool { + // Always assume values conflict. + return false; + }); return; } @@ -1990,7 +1992,8 @@ private: } // end anonymous namespace -llvm::Optional> AllocOptimize::computeAvailableValues( +llvm::Optional> +AllocOptimize::computeAvailableValues( SILValue SrcAddr, SILInstruction *Inst, SmallVectorImpl &AvailableValues) { // If the box has escaped at this instruction, we can't safely promote the diff --git a/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp b/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp index f2e99529af3..6bf48c3d7f1 100644 --- a/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp +++ b/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp @@ -820,7 +820,7 @@ SILCombiner::buildConcreteOpenedExistentialInfoFromSoleConformingType( auto abstractionPattern = Lowering::AbstractionPattern::getOpaque(); auto abstractTy = F->getLoweredType(abstractionPattern, ConcreteType); if (abstractTy != concreteSILType) - return llvm::None; + return llvm::None; SoleCEI.ConcreteValue = Builder.createUncheckedAddrCast( diff --git a/lib/SILOptimizer/SemanticARC/SemanticARCOptVisitor.h b/lib/SILOptimizer/SemanticARC/SemanticARCOptVisitor.h index 5c6a056e2d8..79740b05e36 100644 --- a/lib/SILOptimizer/SemanticARC/SemanticARCOptVisitor.h +++ b/lib/SILOptimizer/SemanticARC/SemanticARCOptVisitor.h @@ -96,7 +96,8 @@ struct LLVM_LIBRARY_VISIBILITY SemanticARCOptVisitor /// worklist. void drainVisitedSinceLastMutationIntoWorklist() { while (!visitedSinceLastMutation.empty()) { - llvm::Optional nextValue = visitedSinceLastMutation.pop_back_val(); + llvm::Optional nextValue = + visitedSinceLastMutation.pop_back_val(); if (!nextValue.has_value()) { continue; } diff --git a/lib/SILOptimizer/Transforms/DeadStoreElimination.cpp b/lib/SILOptimizer/Transforms/DeadStoreElimination.cpp index 13fb17cdc75..03986935983 100644 --- a/lib/SILOptimizer/Transforms/DeadStoreElimination.cpp +++ b/lib/SILOptimizer/Transforms/DeadStoreElimination.cpp @@ -1012,7 +1012,8 @@ void DSEContext::processWrite(SILInstruction *I, SILValue Val, SILValue Mem, // particular instruction may not be accessing the base, so we need to // *rebase* the locations w.r.t. to the current instruction. SILValue B = Locs[0].getBase(); - llvm::Optional BP = ProjectionPath::getProjectionPath(B, Mem); + llvm::Optional BP = + ProjectionPath::getProjectionPath(B, Mem); // Strip off the projection path from base to the accessed field. for (auto &X : Alives) { X.removePathPrefix(BP); diff --git a/lib/SILOptimizer/Transforms/Outliner.cpp b/lib/SILOptimizer/Transforms/Outliner.cpp index 7dc66014218..bf9791a64d7 100644 --- a/lib/SILOptimizer/Transforms/Outliner.cpp +++ b/lib/SILOptimizer/Transforms/Outliner.cpp @@ -319,10 +319,8 @@ CanSILFunctionType BridgedProperty::getOutlinedFunctionType(SILModule &M) { auto ExtInfo = SILFunctionType::ExtInfo::getThin(); auto FunctionType = SILFunctionType::get( nullptr, ExtInfo, SILCoroutineKind::None, - ParameterConvention::Direct_Unowned, Parameters, /*yields*/ {}, - Results, llvm::None, - SubstitutionMap(), SubstitutionMap(), - M.getASTContext()); + ParameterConvention::Direct_Unowned, Parameters, /*yields*/ {}, Results, + llvm::None, SubstitutionMap(), SubstitutionMap(), M.getASTContext()); return FunctionType; } @@ -1291,10 +1289,8 @@ CanSILFunctionType ObjCMethodCall::getOutlinedFunctionType(SILModule &M) { } auto FunctionType = SILFunctionType::get( nullptr, ExtInfo, SILCoroutineKind::None, - ParameterConvention::Direct_Unowned, Parameters, {}, - Results, llvm::None, - SubstitutionMap(), SubstitutionMap(), - M.getASTContext()); + ParameterConvention::Direct_Unowned, Parameters, {}, Results, llvm::None, + SubstitutionMap(), SubstitutionMap(), M.getASTContext()); return FunctionType; } diff --git a/lib/SILOptimizer/Transforms/PartialApplySimplification.cpp b/lib/SILOptimizer/Transforms/PartialApplySimplification.cpp index 8fe2d712a3f..cb0db697efe 100644 --- a/lib/SILOptimizer/Transforms/PartialApplySimplification.cpp +++ b/lib/SILOptimizer/Transforms/PartialApplySimplification.cpp @@ -752,11 +752,11 @@ rewriteKnownCalleeWithExplicitContext(SILFunction *callee, // Continue emitting code to populate the context. B.setInsertionPoint(contextAlloc->getNextInstruction()); } else { - contextBuffer = B.createAllocBox(loc, - contextStorageTy.castTo(), - /*debug variable*/ llvm::None, - /*dynamic lifetime*/ false, - /*reflection*/ true); + contextBuffer = + B.createAllocBox(loc, contextStorageTy.castTo(), + /*debug variable*/ llvm::None, + /*dynamic lifetime*/ false, + /*reflection*/ true); contextProj = B.createProjectBox(loc, contextBuffer, 0); } diff --git a/lib/SILOptimizer/Transforms/PerformanceInliner.cpp b/lib/SILOptimizer/Transforms/PerformanceInliner.cpp index 9019b23585d..e2aa98537d7 100644 --- a/lib/SILOptimizer/Transforms/PerformanceInliner.cpp +++ b/lib/SILOptimizer/Transforms/PerformanceInliner.cpp @@ -653,7 +653,8 @@ static bool isInlineAlwaysCallSite(SILFunction *Callee, int numCallerBlocks) { /// It returns false if a function should not be inlined. /// It returns None if the decision cannot be made without a more complex /// analysis. -static llvm::Optional shouldInlineGeneric(FullApplySite AI, int numCallerBlocks) { +static llvm::Optional shouldInlineGeneric(FullApplySite AI, + int numCallerBlocks) { assert(AI.hasSubstitutions() && "Expected a generic apply"); diff --git a/lib/SILOptimizer/Transforms/PhiArgumentOptimizations.cpp b/lib/SILOptimizer/Transforms/PhiArgumentOptimizations.cpp index 52415585be3..931436e99e8 100644 --- a/lib/SILOptimizer/Transforms/PhiArgumentOptimizations.cpp +++ b/lib/SILOptimizer/Transforms/PhiArgumentOptimizations.cpp @@ -369,7 +369,7 @@ bool PhiExpansionPass::optimizeArg(SILPhiArgument *initialArg) { VarDecl *field = nullptr; SILType newType; llvm::Optional loc; - + // First step: collect all phi-arguments which can be transformed. unsigned workIdx = 0; while (workIdx < collectedPhiArgs.size()) { diff --git a/lib/SILOptimizer/Transforms/SILMem2Reg.cpp b/lib/SILOptimizer/Transforms/SILMem2Reg.cpp index c07e2252c0e..c146de98a4d 100644 --- a/lib/SILOptimizer/Transforms/SILMem2Reg.cpp +++ b/lib/SILOptimizer/Transforms/SILMem2Reg.cpp @@ -991,7 +991,7 @@ private: /// Get the values for this AllocStack variable that are flowing out of /// StartBB. llvm::Optional getLiveOutValues(BlockSetVector &phiBlocks, - SILBasicBlock *startBlock); + SILBasicBlock *startBlock); /// Get the values for this AllocStack variable that are flowing out of /// StartBB or undef if there are none. @@ -1000,7 +1000,7 @@ private: /// Get the values for this AllocStack variable that are flowing into block. llvm::Optional getLiveInValues(BlockSetVector &phiBlocks, - SILBasicBlock *block); + SILBasicBlock *block); /// Get the values for this AllocStack variable that are flowing into block or /// undef if there are none. diff --git a/lib/SILOptimizer/Transforms/StringOptimization.cpp b/lib/SILOptimizer/Transforms/StringOptimization.cpp index e712fe675c6..7e1b6f75fbf 100644 --- a/lib/SILOptimizer/Transforms/StringOptimization.cpp +++ b/lib/SILOptimizer/Transforms/StringOptimization.cpp @@ -304,7 +304,8 @@ bool StringOptimization::optimizeTypeName(ApplyInst *typeNameCall) { return false; // Usually the "qualified" parameter of _typeName() is a constant boolean. - llvm::Optional isQualifiedOpt = getIntConstant(typeNameCall->getArgument(1)); + llvm::Optional isQualifiedOpt = + getIntConstant(typeNameCall->getArgument(1)); if (!isQualifiedOpt) return false; bool isQualified = isQualifiedOpt.value(); @@ -662,7 +663,7 @@ llvm::Optional StringOptimization::getIntConstant(SILValue value) { auto *boolOrIntStruct = dyn_cast(value); if (!boolOrIntStruct || boolOrIntStruct->getNumOperands() != 1) return llvm::None; - + auto *literal = dyn_cast(boolOrIntStruct->getOperand(0)); if (!literal || literal->getValue().getActiveBits() > 64) return llvm::None; diff --git a/lib/SILOptimizer/UtilityPasses/BugReducerTester.cpp b/lib/SILOptimizer/UtilityPasses/BugReducerTester.cpp index d476a214699..50d3842873c 100644 --- a/lib/SILOptimizer/UtilityPasses/BugReducerTester.cpp +++ b/lib/SILOptimizer/UtilityPasses/BugReducerTester.cpp @@ -85,8 +85,9 @@ class BugReducerTester : public SILFunctionTransform { auto FuncType = SILFunctionType::get( nullptr, SILFunctionType::ExtInfo::getThin(), SILCoroutineKind::None, ParameterConvention::Direct_Unowned, ArrayRef(), - ArrayRef(), ResultInfoArray, llvm::None, SubstitutionMap(), - SubstitutionMap(), getFunction()->getModule().getASTContext()); + ArrayRef(), ResultInfoArray, llvm::None, + SubstitutionMap(), SubstitutionMap(), + getFunction()->getModule().getASTContext()); SILOptFunctionBuilder FunctionBuilder(*this); SILFunction *F = FunctionBuilder.getOrCreateSharedFunction( diff --git a/lib/SILOptimizer/Utils/CanonicalizeBorrowScope.cpp b/lib/SILOptimizer/Utils/CanonicalizeBorrowScope.cpp index 7a1a21604cf..2a557656ca1 100644 --- a/lib/SILOptimizer/Utils/CanonicalizeBorrowScope.cpp +++ b/lib/SILOptimizer/Utils/CanonicalizeBorrowScope.cpp @@ -780,7 +780,8 @@ bool CanonicalizeBorrowScope::consolidateBorrowScope() { // Gather all potential outer uses before rewriting any to avoid scanning // any basic block more than once. - llvm::Optional outerUsers = FindBorrowScopeUses(*this).findUses(); + llvm::Optional outerUsers = + FindBorrowScopeUses(*this).findUses(); if (!outerUsers) return false; diff --git a/lib/SILOptimizer/Utils/CompileTimeInterpolationUtils.cpp b/lib/SILOptimizer/Utils/CompileTimeInterpolationUtils.cpp index 87481e4938a..33c7699bbc6 100644 --- a/lib/SILOptimizer/Utils/CompileTimeInterpolationUtils.cpp +++ b/lib/SILOptimizer/Utils/CompileTimeInterpolationUtils.cpp @@ -26,7 +26,8 @@ bool swift::shouldAttemptEvaluation(SILInstruction *inst) { return isConstantEvaluable(calleeFun); } -std::pair, llvm::Optional> +std::pair, + llvm::Optional> swift::evaluateOrSkip(ConstExprStepEvaluator &stepEval, SILBasicBlock::iterator instI) { SILInstruction *inst = &(*instI); diff --git a/lib/SILOptimizer/Utils/ConstExpr.cpp b/lib/SILOptimizer/Utils/ConstExpr.cpp index 41e2ee33b1d..a3f252bc756 100644 --- a/lib/SILOptimizer/Utils/ConstExpr.cpp +++ b/lib/SILOptimizer/Utils/ConstExpr.cpp @@ -252,7 +252,8 @@ public: /// /// Second element is None, if the evaluation is successful. /// Otherwise, is an unknown symbolic value that contains the error. - std::pair, llvm::Optional> + std::pair, + llvm::Optional> evaluateInstructionAndGetNext( SILBasicBlock::iterator instI, SmallPtrSetImpl &visitedBlocks); @@ -1877,7 +1878,8 @@ ConstExprFunctionState::evaluateFlowSensitive(SILInstruction *inst) { UnknownReason::UnsupportedInstruction); } -std::pair, llvm::Optional> +std::pair, + llvm::Optional> ConstExprFunctionState::evaluateInstructionAndGetNext( SILBasicBlock::iterator instI, SmallPtrSetImpl &visitedBlocks) { @@ -1994,7 +1996,7 @@ ConstExprFunctionState::evaluateInstructionAndGetNext( inst->getModule().getSwiftModule(), sourceType, targetType); if (castResult == DynamicCastFeasibility::MaySucceed) { return {llvm::None, getUnknown(evaluator, inst->asSILNode(), - UnknownReason::UnknownCastResult)}; + UnknownReason::UnknownCastResult)}; } // Determine the basic block to jump to. SILBasicBlock *resultBB = @@ -2016,7 +2018,7 @@ ConstExprFunctionState::evaluateInstructionAndGetNext( << "\n"); return {llvm::None, getUnknown(evaluator, inst->asSILNode(), - UnknownReason::UnsupportedInstruction)}; + UnknownReason::UnsupportedInstruction)}; } /// Evaluate a call to the specified function as if it were a constant @@ -2155,7 +2157,8 @@ ConstExprStepEvaluator::ConstExprStepEvaluator(SymbolicValueAllocator &alloc, ConstExprStepEvaluator::~ConstExprStepEvaluator() { delete internalState; } -std::pair, llvm::Optional> +std::pair, + llvm::Optional> ConstExprStepEvaluator::evaluate(SILBasicBlock::iterator instI) { // Reset `stepsEvaluated` to zero. stepsEvaluated = 0; @@ -2222,7 +2225,8 @@ void ConstExprStepEvaluator::setMutableAddressesToUnknown( } } -std::pair, llvm::Optional> +std::pair, + llvm::Optional> ConstExprStepEvaluator::skipByMakingEffectsNonConstant( SILBasicBlock::iterator instI) { SILInstruction *inst = &(*instI); @@ -2263,7 +2267,8 @@ bool swift::isFailStopError(SymbolicValue errorVal) { } } -std::pair, llvm::Optional> +std::pair, + llvm::Optional> ConstExprStepEvaluator::tryEvaluateOrElseMakeEffectsNonConstant( SILBasicBlock::iterator instI) { auto evaluateResult = evaluate(instI); diff --git a/lib/SILOptimizer/Utils/ConstantFolding.cpp b/lib/SILOptimizer/Utils/ConstantFolding.cpp index 0fa564acee8..8af590a8f6e 100644 --- a/lib/SILOptimizer/Utils/ConstantFolding.cpp +++ b/lib/SILOptimizer/Utils/ConstantFolding.cpp @@ -561,8 +561,7 @@ static SILValue specializePolymorphicBuiltin(BuiltinInst *bi, /// /// The list of operations we constant fold might not be complete. Start with /// folding the operations used by the standard library. -static SILValue constantFoldBinary(BuiltinInst *BI, - BuiltinValueKind ID, +static SILValue constantFoldBinary(BuiltinInst *BI, BuiltinValueKind ID, llvm::Optional &ResultsInError) { switch (ID) { default: @@ -837,7 +836,6 @@ constantFoldAndCheckIntegerConversions(BuiltinInst *BI, // The call to the builtin should be replaced with the constant value. return constructResultWithOverflowTuple(BI, Result, false); - } /// A utility function that extracts the literal text corresponding @@ -862,7 +860,8 @@ static bool tryExtractLiteralText(FloatLiteralInst *flitInst, } static SILValue foldFPToIntConversion(BuiltinInst *BI, - const BuiltinInfo &Builtin, llvm::Optional &ResultsInError) { + const BuiltinInfo &Builtin, + llvm::Optional &ResultsInError) { assert(Builtin.ID == BuiltinValueKind::FPToSI || Builtin.ID == BuiltinValueKind::FPToUI); @@ -1316,7 +1315,8 @@ case BuiltinValueKind::id: /// as results of User. If we could only simplify /some/ of an instruction's /// results, we still return true, but signal that we couldn't simplify by /// placing SILValue() in that position instead. -static bool constantFoldInstruction(Operand *Op, llvm::Optional &ResultsInError, +static bool constantFoldInstruction(Operand *Op, + llvm::Optional &ResultsInError, SmallVectorImpl &Results) { auto *User = Op->getUser(); diff --git a/lib/SILOptimizer/Utils/DistributedActor.cpp b/lib/SILOptimizer/Utils/DistributedActor.cpp index fbec4a118c3..089a9a33748 100644 --- a/lib/SILOptimizer/Utils/DistributedActor.cpp +++ b/lib/SILOptimizer/Utils/DistributedActor.cpp @@ -19,8 +19,7 @@ namespace swift { void emitDistributedActorSystemWitnessCall( - SILBuilder &B, SILLocation loc, DeclName methodName, - SILValue base, + SILBuilder &B, SILLocation loc, DeclName methodName, SILValue base, // types to be passed through to SubstitutionMap: SILType actorType, // call arguments, except the base which will be passed last diff --git a/lib/SILOptimizer/Utils/InstOptUtils.cpp b/lib/SILOptimizer/Utils/InstOptUtils.cpp index d84357a37ff..8e8e48c9905 100644 --- a/lib/SILOptimizer/Utils/InstOptUtils.cpp +++ b/lib/SILOptimizer/Utils/InstOptUtils.cpp @@ -55,7 +55,8 @@ static llvm::cl::opt KeepWillThrowCall( llvm::cl::desc( "Keep calls to swift_willThrow, even if the throw is optimized away")); -llvm::Optional swift::getInsertAfterPoint(SILValue val) { +llvm::Optional +swift::getInsertAfterPoint(SILValue val) { if (auto *inst = val->getDefiningInstruction()) { return std::next(inst->getIterator()); } diff --git a/lib/SILOptimizer/Utils/KeyPathProjector.cpp b/lib/SILOptimizer/Utils/KeyPathProjector.cpp index 9c913f85b20..073ba49a563 100644 --- a/lib/SILOptimizer/Utils/KeyPathProjector.cpp +++ b/lib/SILOptimizer/Utils/KeyPathProjector.cpp @@ -223,8 +223,8 @@ public: // The callback expects a memory address it can read from, // so allocate a buffer. auto &function = builder.getFunction(); - auto substType = component.getComponentType().subst(keyPath->getSubstitutions(), - llvm::None); + auto substType = component.getComponentType().subst( + keyPath->getSubstitutions(), llvm::None); SILType type = function.getLoweredType( Lowering::AbstractionPattern::getOpaque(), substType); auto addr = builder.createAllocStack(loc, type); @@ -301,8 +301,8 @@ public: // The callback expects a memory address it can write to, // so allocate a writeback buffer. auto &function = builder.getFunction(); - auto substType = component.getComponentType().subst(keyPath->getSubstitutions(), - llvm::None); + auto substType = component.getComponentType().subst( + keyPath->getSubstitutions(), llvm::None); SILType type = function.getLoweredType( Lowering::AbstractionPattern::getOpaque(), substType); auto addr = builder.createAllocStack(loc, type); @@ -351,8 +351,8 @@ public: parent->project(AccessType::Get, [&](SILValue parentValue) { auto &function = builder.getFunction(); - auto substType = component.getComponentType().subst(keyPath->getSubstitutions(), - llvm::None); + auto substType = component.getComponentType().subst( + keyPath->getSubstitutions(), llvm::None); SILType optType = function.getLoweredType( Lowering::AbstractionPattern::getOpaque(), substType); SILType objType = optType.getOptionalObjectType().getAddressType(); @@ -568,7 +568,8 @@ public: // If we're reading an optional chain, create an optional result. auto resultCanType = components.back().getComponentType(); auto &function = builder.getFunction(); - auto substType = resultCanType.subst(keyPath->getSubstitutions(), llvm::None); + auto substType = + resultCanType.subst(keyPath->getSubstitutions(), llvm::None); auto optType = function.getLoweredType( Lowering::AbstractionPattern::getOpaque(), substType); diff --git a/lib/SILOptimizer/Utils/LexicalDestroyFolding.cpp b/lib/SILOptimizer/Utils/LexicalDestroyFolding.cpp index 3c82d0b83da..a3bc0bd0f0c 100644 --- a/lib/SILOptimizer/Utils/LexicalDestroyFolding.cpp +++ b/lib/SILOptimizer/Utils/LexicalDestroyFolding.cpp @@ -225,7 +225,8 @@ private: /// other scope ending instructions. /// If a Match WITH an apply is returned, we might be able to transform this /// instruction, so more expensive checks are in order. - llvm::Optional definesMatchingInstructionSequence(SILInstruction *) const; + llvm::Optional + definesMatchingInstructionSequence(SILInstruction *) const; /// Whether the specified instruction is or might be the beginning of a /// sequence of "inconsequential" instructions the last of which destroys diff --git a/lib/SILOptimizer/Utils/SILInliner.cpp b/lib/SILOptimizer/Utils/SILInliner.cpp index 99303bbc3eb..2101fbb93e5 100644 --- a/lib/SILOptimizer/Utils/SILInliner.cpp +++ b/lib/SILOptimizer/Utils/SILInliner.cpp @@ -101,7 +101,7 @@ public: : Loc(Loc), Builder(Builder), BeginApply(BeginApply) {} static llvm::Optional get(FullApplySite AI, SILLocation Loc, - SILBuilder *Builder) { + SILBuilder *Builder) { auto *BeginApply = dyn_cast(AI); if (!BeginApply) return llvm::None; diff --git a/lib/SILOptimizer/Utils/StackNesting.cpp b/lib/SILOptimizer/Utils/StackNesting.cpp index 1d3195bc707..6ae5c981171 100644 --- a/lib/SILOptimizer/Utils/StackNesting.cpp +++ b/lib/SILOptimizer/Utils/StackNesting.cpp @@ -293,7 +293,8 @@ StackNesting::Changes StackNesting::insertDeallocsAtBlockBoundaries() { changes = Changes::CFG; } if (insertDeallocs(bd.data.AliveStackLocsAtExit, - SuccBI.AliveStackLocsAtEntry, &InsertionBlock->front(), llvm::None)) { + SuccBI.AliveStackLocsAtEntry, &InsertionBlock->front(), + llvm::None)) { if (changes == Changes::None) changes = Changes::Instructions; } diff --git a/lib/Sema/BuilderTransform.cpp b/lib/Sema/BuilderTransform.cpp index 43e1b0219ed..aad4a5207ba 100644 --- a/lib/Sema/BuilderTransform.cpp +++ b/lib/Sema/BuilderTransform.cpp @@ -276,7 +276,8 @@ protected: } return std::make_pair( - builder.buildVarRef(buildBlockVar, braceStmt->getStartLoc()), llvm::None); + builder.buildVarRef(buildBlockVar, braceStmt->getStartLoc()), + llvm::None); } // If `buildBlock` does not exist at this point, it could be the case that // `buildPartialBlock` did not have the sufficient availability for this @@ -594,7 +595,8 @@ protected: return DoStmt::createImplicit(ctx, LabeledStmtInfo(), doBody); } - llvm::Optional> transformCase(CaseStmt *caseStmt) { + llvm::Optional> + transformCase(CaseStmt *caseStmt) { auto *body = caseStmt->getBody(); // Explicitly disallow `case` statements with empty bodies @@ -1483,9 +1485,9 @@ swift::determineResultBuilderBuildFixItInfo(NominalTypeDecl *builder) { } void swift::printResultBuilderBuildFunction( - NominalTypeDecl *builder, Type componentType, - ResultBuilderBuildFunction function, - llvm::Optional stubIndent, llvm::raw_ostream &out) { + NominalTypeDecl *builder, Type componentType, + ResultBuilderBuildFunction function, llvm::Optional stubIndent, + llvm::raw_ostream &out) { // Render the component type into a string. std::string componentTypeString; if (componentType) diff --git a/lib/Sema/CSApply.cpp b/lib/Sema/CSApply.cpp index f00f512cb36..2c9066e3f1d 100644 --- a/lib/Sema/CSApply.cpp +++ b/lib/Sema/CSApply.cpp @@ -470,8 +470,8 @@ namespace { // Returns None if the AST does not contain enough information to recover // substitutions; this is different from an Optional(SubstitutionMap()), // indicating a valid call to a non-generic operator. - llvm::Optional - getOperatorSubstitutions(ValueDecl *witness, Type refType) { + llvm::Optional getOperatorSubstitutions(ValueDecl *witness, + Type refType) { // We have to recover substitutions in this hacky way because // the AST does not retain enough information to devirtualize // calls like this. @@ -2950,8 +2950,9 @@ namespace { DeclNameLoc(expr->getLoc()), SourceLoc(), {}, SourceLoc(), nullptr, MacroRole::Expression, /*isImplicit=*/true, expandedType); expansion->setMacroRef(macroRef); - (void)evaluateOrDefault( - ctx.evaluator, ExpandMacroExpansionExprRequest{expansion}, llvm::None); + (void)evaluateOrDefault(ctx.evaluator, + ExpandMacroExpansionExprRequest{expansion}, + llvm::None); if (expansion->getRewritten()) { cs.cacheExprTypes(expansion); return expansion; @@ -6613,7 +6614,8 @@ bool ExprRewriter::peepholeCollectionUpcast(Expr *expr, Type toType, return true; } - if (llvm::Optional elementType = ConstraintSystem::isSetType(toType)) { + if (llvm::Optional elementType = + ConstraintSystem::isSetType(toType)) { peepholeArrayUpcast(arrayLiteral, toType, bridged, *elementType, locator); return true; } @@ -9127,7 +9129,8 @@ applySolutionToInitialization(Solution &solution, SyntacticElementTarget target, /// \returns the resulting initialization expression. static llvm::Optional applySolutionToForEachStmt( Solution &solution, SyntacticElementTarget target, - llvm::function_ref(SyntacticElementTarget)> + llvm::function_ref< + llvm::Optional(SyntacticElementTarget)> rewriteTarget) { auto resultTarget = target; auto &forEachStmtInfo = resultTarget.getForEachStmtInfo(); @@ -9704,7 +9707,7 @@ ConstraintSystem::applySolution(Solution &solution, // If any of them failed to type check, bail. if (hadError) return llvm::None; - + if (isDebugMode()) { // If we had partially type-checked expressions, lets print // fully type-checked target after processDelayed is done. @@ -9799,7 +9802,8 @@ SolutionResult SolutionResult::forAmbiguous( return result; } -SolutionResult SolutionResult::forTooComplex(llvm::Optional affected) { +SolutionResult +SolutionResult::forTooComplex(llvm::Optional affected) { SolutionResult result(Kind::TooComplex); result.TooComplexAt = affected; return result; diff --git a/lib/Sema/CSBindings.cpp b/lib/Sema/CSBindings.cpp index eff3246699c..a735a76aa38 100644 --- a/lib/Sema/CSBindings.cpp +++ b/lib/Sema/CSBindings.cpp @@ -1167,7 +1167,8 @@ BindingSet ConstraintSystem::getBindingsFor(TypeVariableType *typeVar, /// type variable. /// /// \returns the type to bind to, if the binding is okay. -static llvm::Optional checkTypeOfBinding(TypeVariableType *typeVar, Type type) { +static llvm::Optional checkTypeOfBinding(TypeVariableType *typeVar, + Type type) { // If the type references the type variable, don't permit the binding. if (type->hasTypeVariable()) { SmallPtrSet referencedTypeVars; diff --git a/lib/Sema/CSDiagnostics.cpp b/lib/Sema/CSDiagnostics.cpp index ea56aade37c..f70d4cadff4 100644 --- a/lib/Sema/CSDiagnostics.cpp +++ b/lib/Sema/CSDiagnostics.cpp @@ -753,7 +753,8 @@ bool SameShapeExpansionFailure::diagnoseAsError() { return true; } -llvm::Optional> GenericArgumentsMismatchFailure::getDiagnosticFor( +llvm::Optional> +GenericArgumentsMismatchFailure::getDiagnosticFor( ContextualTypePurpose context) { switch (context) { case CTP_Initialization: @@ -2417,7 +2418,8 @@ AssignmentFailure::getMemberRef(ConstraintLocator *locator) const { locator, LocatorPathElt::KeyPathDynamicMember(keyPath)); auto memberRef = getOverloadChoiceIfAvailable(memberLoc); - return memberRef ? llvm::Optional(memberRef->choice) : llvm::None; + return memberRef ? llvm::Optional(memberRef->choice) + : llvm::None; } // If this is a string based dynamic lookup, there is no member declaration. diff --git a/lib/Sema/CSDiagnostics.h b/lib/Sema/CSDiagnostics.h index 6aa1957041c..8e080d7e0fa 100644 --- a/lib/Sema/CSDiagnostics.h +++ b/lib/Sema/CSDiagnostics.h @@ -896,7 +896,8 @@ private: void emitNoteForMismatch(int mismatchPosition); - llvm::Optional> getDiagnosticFor(ContextualTypePurpose context); + llvm::Optional> + getDiagnosticFor(ContextualTypePurpose context); /// The actual type being used. BoundGenericType *getActual() const { @@ -1491,7 +1492,8 @@ private: /// Gather information associated with expression that represents /// a call - function and argument list. - llvm::Optional> getCallInfo(ASTNode anchor) const; + llvm::Optional> + getCallInfo(ASTNode anchor) const; /// Transform given argument into format suitable for a fix-it /// text e.g. `[