diff options
author | Kazu Hirata <kazu@google.com> | 2022-06-25 11:55:57 -0700 |
---|---|---|
committer | Kazu Hirata <kazu@google.com> | 2022-06-25 11:55:57 -0700 |
commit | aa8feeefd3ac6c78ee8f67bf033976fc7d68bc6d (patch) | |
tree | d207b35cfb445636f41204bcfe51f6ca3a94a3ba | |
parent | b8df4093e4d82c67a419911a46b63482043643e5 (diff) | |
download | llvm-aa8feeefd3ac6c78ee8f67bf033976fc7d68bc6d.zip llvm-aa8feeefd3ac6c78ee8f67bf033976fc7d68bc6d.tar.gz llvm-aa8feeefd3ac6c78ee8f67bf033976fc7d68bc6d.tar.bz2 |
Don't use Optional::hasValue (NFC)
372 files changed, 2098 insertions, 2180 deletions
diff --git a/clang-tools-extra/clang-doc/HTMLGenerator.cpp b/clang-tools-extra/clang-doc/HTMLGenerator.cpp index 3e5a533..12c07ac 100644 --- a/clang-tools-extra/clang-doc/HTMLGenerator.cpp +++ b/clang-tools-extra/clang-doc/HTMLGenerator.cpp @@ -653,10 +653,10 @@ genHTML(const EnumInfo &I, const ClangDocContext &CDCtx) { if (I.DefLoc) { if (!CDCtx.RepositoryUrl) - Out.emplace_back(writeFileDefinition(I.DefLoc.getValue())); + Out.emplace_back(writeFileDefinition(*I.DefLoc)); else - Out.emplace_back(writeFileDefinition( - I.DefLoc.getValue(), StringRef{CDCtx.RepositoryUrl.getValue()})); + Out.emplace_back( + writeFileDefinition(*I.DefLoc, StringRef{*CDCtx.RepositoryUrl})); } std::string Description; @@ -702,10 +702,10 @@ genHTML(const FunctionInfo &I, const ClangDocContext &CDCtx, if (I.DefLoc) { if (!CDCtx.RepositoryUrl) - Out.emplace_back(writeFileDefinition(I.DefLoc.getValue())); + Out.emplace_back(writeFileDefinition(*I.DefLoc)); else - Out.emplace_back(writeFileDefinition( - I.DefLoc.getValue(), StringRef{CDCtx.RepositoryUrl.getValue()})); + Out.emplace_back( + writeFileDefinition(*I.DefLoc, StringRef{*CDCtx.RepositoryUrl})); } std::string Description; @@ -768,10 +768,10 @@ genHTML(const RecordInfo &I, Index &InfoIndex, const ClangDocContext &CDCtx, if (I.DefLoc) { if (!CDCtx.RepositoryUrl) - Out.emplace_back(writeFileDefinition(I.DefLoc.getValue())); + Out.emplace_back(writeFileDefinition(*I.DefLoc)); else - Out.emplace_back(writeFileDefinition( - I.DefLoc.getValue(), StringRef{CDCtx.RepositoryUrl.getValue()})); + Out.emplace_back( + writeFileDefinition(*I.DefLoc, StringRef{*CDCtx.RepositoryUrl})); } std::string Description; diff --git a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp index 1efd88d..418b749 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp @@ -817,8 +817,8 @@ void NotNullTerminatedResultCheck::check( ++It; } - if (AreSafeFunctionsWanted.hasValue()) - UseSafeFunctions = AreSafeFunctionsWanted.getValue(); + if (AreSafeFunctionsWanted) + UseSafeFunctions = *AreSafeFunctionsWanted; } StringRef Name = FunctionExpr->getDirectCallee()->getName(); diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp b/clang-tools-extra/clangd/ClangdLSPServer.cpp index 3bade14..4a26b5a 100644 --- a/clang-tools-extra/clangd/ClangdLSPServer.cpp +++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp @@ -663,9 +663,9 @@ void ClangdLSPServer::onDocumentDidOpen( void ClangdLSPServer::onDocumentDidChange( const DidChangeTextDocumentParams &Params) { auto WantDiags = WantDiagnostics::Auto; - if (Params.wantDiagnostics.hasValue()) - WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes - : WantDiagnostics::No; + if (Params.wantDiagnostics) + WantDiags = + *Params.wantDiagnostics ? WantDiagnostics::Yes : WantDiagnostics::No; PathRef File = Params.textDocument.uri.file(); auto Code = Server->getDraft(File); diff --git a/clang-tools-extra/clangd/ClangdServer.cpp b/clang-tools-extra/clangd/ClangdServer.cpp index fa6c70b..1fe63c1f 100644 --- a/clang-tools-extra/clangd/ClangdServer.cpp +++ b/clang-tools-extra/clangd/ClangdServer.cpp @@ -411,10 +411,9 @@ void ClangdServer::codeComplete(PathRef File, Position Pos, clang::clangd::trace::Span Tracer("Completion results callback"); CB(std::move(Result)); } - if (SpecFuzzyFind && SpecFuzzyFind->NewReq.hasValue()) { + if (SpecFuzzyFind && SpecFuzzyFind->NewReq) { std::lock_guard<std::mutex> Lock(CachedCompletionFuzzyFindRequestMutex); - CachedCompletionFuzzyFindRequestByFile[File] = - SpecFuzzyFind->NewReq.getValue(); + CachedCompletionFuzzyFindRequestByFile[File] = *SpecFuzzyFind->NewReq; } // SpecFuzzyFind is only destroyed after speculative fuzzy find finishes. // We don't want `codeComplete` to wait for the async call if it doesn't use diff --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp index fbd7488..d17a14b 100644 --- a/clang-tools-extra/clangd/CodeComplete.cpp +++ b/clang-tools-extra/clangd/CodeComplete.cpp @@ -391,11 +391,9 @@ struct CodeCompletionBuilder { ToInclude.takeError()); } // Prefer includes that do not need edits (i.e. already exist). - std::stable_partition(Completion.Includes.begin(), - Completion.Includes.end(), - [](const CodeCompletion::IncludeCandidate &I) { - return !I.Insertion.hasValue(); - }); + std::stable_partition( + Completion.Includes.begin(), Completion.Includes.end(), + [](const CodeCompletion::IncludeCandidate &I) { return !I.Insertion; }); } void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) { diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp b/clang-tools-extra/clangd/ConfigCompile.cpp index 2de8816..8f207ab 100644 --- a/clang-tools-extra/clangd/ConfigCompile.cpp +++ b/clang-tools-extra/clangd/ConfigCompile.cpp @@ -358,8 +358,8 @@ struct FragmentCompiler { } #endif // Make sure exactly one of the Sources is set. - unsigned SourceCount = External.File.hasValue() + - External.Server.hasValue() + *External.IsNone; + unsigned SourceCount = External.File.has_value() + + External.Server.has_value() + *External.IsNone; if (SourceCount != 1) { diag(Error, "Exactly one of File, Server or None must be set.", BlockRange); diff --git a/clang-tools-extra/clangd/FeatureModule.cpp b/clang-tools-extra/clangd/FeatureModule.cpp index 85977aa..872cea1 100644 --- a/clang-tools-extra/clangd/FeatureModule.cpp +++ b/clang-tools-extra/clangd/FeatureModule.cpp @@ -13,12 +13,12 @@ namespace clang { namespace clangd { void FeatureModule::initialize(const Facilities &F) { - assert(!Fac.hasValue() && "Initialized twice"); + assert(!Fac && "Initialized twice"); Fac.emplace(F); } FeatureModule::Facilities &FeatureModule::facilities() { - assert(Fac.hasValue() && "Not initialized yet"); + assert(Fac && "Not initialized yet"); return *Fac; } diff --git a/clang-tools-extra/clangd/index/YAMLSerialization.cpp b/clang-tools-extra/clangd/index/YAMLSerialization.cpp index 79c9e1d..1ac7433 100644 --- a/clang-tools-extra/clangd/index/YAMLSerialization.cpp +++ b/clang-tools-extra/clangd/index/YAMLSerialization.cpp @@ -354,23 +354,23 @@ template <> struct MappingTraits<CompileCommandYAML> { template <> struct MappingTraits<VariantEntry> { static void mapping(IO &IO, VariantEntry &Variant) { - if (IO.mapTag("!Symbol", Variant.Symbol.hasValue())) { + if (IO.mapTag("!Symbol", Variant.Symbol.has_value())) { if (!IO.outputting()) Variant.Symbol.emplace(); MappingTraits<Symbol>::mapping(IO, *Variant.Symbol); - } else if (IO.mapTag("!Refs", Variant.Refs.hasValue())) { + } else if (IO.mapTag("!Refs", Variant.Refs.has_value())) { if (!IO.outputting()) Variant.Refs.emplace(); MappingTraits<RefBundle>::mapping(IO, *Variant.Refs); - } else if (IO.mapTag("!Relations", Variant.Relation.hasValue())) { + } else if (IO.mapTag("!Relations", Variant.Relation.has_value())) { if (!IO.outputting()) Variant.Relation.emplace(); MappingTraits<Relation>::mapping(IO, *Variant.Relation); - } else if (IO.mapTag("!Source", Variant.Source.hasValue())) { + } else if (IO.mapTag("!Source", Variant.Source.has_value())) { if (!IO.outputting()) Variant.Source.emplace(); MappingTraits<IncludeGraphNode>::mapping(IO, *Variant.Source); - } else if (IO.mapTag("!Cmd", Variant.Cmd.hasValue())) { + } else if (IO.mapTag("!Cmd", Variant.Cmd.has_value())) { if (!IO.outputting()) Variant.Cmd.emplace(); MappingTraits<CompileCommandYAML>::mapping( diff --git a/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp b/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp index ddf6f4f..6af1e3b 100644 --- a/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp +++ b/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp @@ -82,12 +82,12 @@ Diagnostics: EXPECT_THAT(Results[1].CompileFlags.Add, ElementsAre(val("b\naz\n"))); ASSERT_TRUE(Results[2].Index.Background); - EXPECT_EQ("Skip", *Results[2].Index.Background.getValue()); + EXPECT_EQ("Skip", *Results[2].Index.Background.value()); EXPECT_THAT(Results[3].Diagnostics.ClangTidy.CheckOptions, ElementsAre(PairVal("IgnoreMacros", "true"), PairVal("example-check.ExampleOption", "0"))); EXPECT_TRUE(Results[3].Diagnostics.UnusedIncludes); - EXPECT_EQ("Strict", *Results[3].Diagnostics.UnusedIncludes.getValue()); + EXPECT_EQ("Strict", *Results[3].Diagnostics.UnusedIncludes.value()); } TEST(ParseYAML, Locations) { @@ -163,10 +163,10 @@ Index: ASSERT_THAT(Diags.Diagnostics, IsEmpty()); ASSERT_EQ(Results.size(), 1u); ASSERT_TRUE(Results[0].Index.External); - EXPECT_FALSE(Results[0].Index.External.getValue()->File.hasValue()); - EXPECT_FALSE(Results[0].Index.External.getValue()->MountPoint.hasValue()); - EXPECT_FALSE(Results[0].Index.External.getValue()->Server.hasValue()); - EXPECT_THAT(*Results[0].Index.External.getValue()->IsNone, testing::Eq(true)); + EXPECT_FALSE(Results[0].Index.External.value()->File.has_value()); + EXPECT_FALSE(Results[0].Index.External.value()->MountPoint.has_value()); + EXPECT_FALSE(Results[0].Index.External.value()->Server.has_value()); + EXPECT_THAT(*Results[0].Index.External.value()->IsNone, testing::Eq(true)); } TEST(ParseYAML, ExternalBlock) { @@ -182,10 +182,10 @@ Index: Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback()); ASSERT_EQ(Results.size(), 1u); ASSERT_TRUE(Results[0].Index.External); - EXPECT_THAT(*Results[0].Index.External.getValue()->File, val("foo")); - EXPECT_THAT(*Results[0].Index.External.getValue()->MountPoint, val("baz")); + EXPECT_THAT(*Results[0].Index.External.value()->File, val("foo")); + EXPECT_THAT(*Results[0].Index.External.value()->MountPoint, val("baz")); ASSERT_THAT(Diags.Diagnostics, IsEmpty()); - EXPECT_THAT(*Results[0].Index.External.getValue()->Server, val("bar")); + EXPECT_THAT(*Results[0].Index.External.value()->Server, val("bar")); } TEST(ParseYAML, AllScopes) { diff --git a/clang-tools-extra/clangd/unittests/FSTests.cpp b/clang-tools-extra/clangd/unittests/FSTests.cpp index 575111e..81129fe 100644 --- a/clang-tools-extra/clangd/unittests/FSTests.cpp +++ b/clang-tools-extra/clangd/unittests/FSTests.cpp @@ -28,10 +28,10 @@ TEST(FSTests, PreambleStatusCache) { EXPECT_TRUE(ProduceFS->status("y")); EXPECT_TRUE(ProduceFS->status("main")); - EXPECT_TRUE(StatCache.lookup(testPath("x")).hasValue()); - EXPECT_TRUE(StatCache.lookup(testPath("y")).hasValue()); + EXPECT_TRUE(StatCache.lookup(testPath("x")).has_value()); + EXPECT_TRUE(StatCache.lookup(testPath("y")).has_value()); // Main file is not cached. - EXPECT_FALSE(StatCache.lookup(testPath("main")).hasValue()); + EXPECT_FALSE(StatCache.lookup(testPath("main")).has_value()); llvm::vfs::Status S("fake", llvm::sys::fs::UniqueID(123, 456), std::chrono::system_clock::now(), 0, 0, 1024, diff --git a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp index fbf07aa..3959c3e 100644 --- a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp +++ b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp @@ -331,14 +331,14 @@ TEST(GlobalCompilationDatabaseTest, CompileFlagsDirectory) { FS.Files[testPath("x/compile_flags.txt")] = "-DFOO"; DirectoryBasedGlobalCompilationDatabase CDB(FS); auto Commands = CDB.getCompileCommand(testPath("x/y.cpp")); - ASSERT_TRUE(Commands.hasValue()); - EXPECT_THAT(Commands.getValue().CommandLine, Contains("-DFOO")); + ASSERT_TRUE(Commands.has_value()); + EXPECT_THAT(Commands->CommandLine, Contains("-DFOO")); // Make sure we pick the right working directory. - EXPECT_EQ(testPath("x"), Commands.getValue().Directory); + EXPECT_EQ(testPath("x"), Commands->Directory); } MATCHER_P(hasArg, Flag, "") { - if (!arg.hasValue()) { + if (!arg) { *result_listener << "command is null"; return false; } diff --git a/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp b/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp index b2d7a7e..5b9467f 100644 --- a/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp +++ b/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp @@ -33,12 +33,12 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) { FS.Files[Invalid]; Optional<Path> PathResult = getCorrespondingHeaderOrSource(FooCpp, FS.view(llvm::None)); - EXPECT_TRUE(PathResult.hasValue()); - ASSERT_EQ(PathResult.getValue(), FooH); + EXPECT_TRUE(PathResult.has_value()); + ASSERT_EQ(*PathResult, FooH); PathResult = getCorrespondingHeaderOrSource(FooH, FS.view(llvm::None)); - EXPECT_TRUE(PathResult.hasValue()); - ASSERT_EQ(PathResult.getValue(), FooCpp); + EXPECT_TRUE(PathResult.has_value()); + ASSERT_EQ(*PathResult, FooCpp); // Test with header file in capital letters and different extension, source // file with different extension @@ -48,8 +48,8 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) { FS.Files[FooC]; FS.Files[FooHH]; PathResult = getCorrespondingHeaderOrSource(FooC, FS.view(llvm::None)); - EXPECT_TRUE(PathResult.hasValue()); - ASSERT_EQ(PathResult.getValue(), FooHH); + EXPECT_TRUE(PathResult.has_value()); + ASSERT_EQ(*PathResult, FooHH); // Test with both capital letters auto Foo2C = testPath("foo2.C"); @@ -57,8 +57,8 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) { FS.Files[Foo2C]; FS.Files[Foo2HH]; PathResult = getCorrespondingHeaderOrSource(Foo2C, FS.view(llvm::None)); - EXPECT_TRUE(PathResult.hasValue()); - ASSERT_EQ(PathResult.getValue(), Foo2HH); + EXPECT_TRUE(PathResult.has_value()); + ASSERT_EQ(*PathResult, Foo2HH); // Test with source file as capital letter and .hxx header file auto Foo3C = testPath("foo3.C"); @@ -67,13 +67,13 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) { FS.Files[Foo3C]; FS.Files[Foo3HXX]; PathResult = getCorrespondingHeaderOrSource(Foo3C, FS.view(llvm::None)); - EXPECT_TRUE(PathResult.hasValue()); - ASSERT_EQ(PathResult.getValue(), Foo3HXX); + EXPECT_TRUE(PathResult.has_value()); + ASSERT_EQ(*PathResult, Foo3HXX); // Test if asking for a corresponding file that doesn't exist returns an empty // string. PathResult = getCorrespondingHeaderOrSource(Invalid, FS.view(llvm::None)); - EXPECT_FALSE(PathResult.hasValue()); + EXPECT_FALSE(PathResult.has_value()); } MATCHER_P(declNamed, Name, "") { diff --git a/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp b/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp index 8b9363b..97a4316 100644 --- a/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp +++ b/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp @@ -93,19 +93,18 @@ TEST(LSPBinderTest, IncomingCalls) { auto &RawPlusOne = RawHandlers.MethodHandlers["plusOne"]; RawPlusOne(1, capture(Reply)); - ASSERT_TRUE(Reply.hasValue()); - EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::HasValue(2)); + ASSERT_TRUE(Reply.has_value()); + EXPECT_THAT_EXPECTED(*Reply, llvm::HasValue(2)); RawPlusOne("foo", capture(Reply)); - ASSERT_TRUE(Reply.hasValue()); + ASSERT_TRUE(Reply.has_value()); EXPECT_THAT_EXPECTED( - Reply.getValue(), - llvm::FailedWithMessage( - HasSubstr("failed to decode plusOne request: expected integer"))); + *Reply, llvm::FailedWithMessage(HasSubstr( + "failed to decode plusOne request: expected integer"))); auto &RawFail = RawHandlers.MethodHandlers["fail"]; RawFail(2, capture(Reply)); - ASSERT_TRUE(Reply.hasValue()); - EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::FailedWithMessage("X=2")); + ASSERT_TRUE(Reply.has_value()); + EXPECT_THAT_EXPECTED(*Reply, llvm::FailedWithMessage("X=2")); auto &RawNotify = RawHandlers.NotificationHandlers["notify"]; RawNotify(42); @@ -117,8 +116,8 @@ TEST(LSPBinderTest, IncomingCalls) { auto &RawCmdPlusOne = RawHandlers.CommandHandlers["cmdPlusOne"]; RawCmdPlusOne(1, capture(Reply)); - ASSERT_TRUE(Reply.hasValue()); - EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::HasValue(2)); + ASSERT_TRUE(Reply.has_value()); + EXPECT_THAT_EXPECTED(*Reply, llvm::HasValue(2)); // None of this generated any outgoing traffic. EXPECT_THAT(RawOutgoing.Received, IsEmpty()); @@ -139,23 +138,23 @@ TEST(LSPBinderTest, OutgoingCalls) { llvm::Optional<llvm::Expected<Foo>> Reply; Echo(Foo{2}, capture(Reply)); EXPECT_THAT(RawOutgoing.take("echo"), ElementsAre(llvm::json::Value(2))); - ASSERT_TRUE(Reply.hasValue()); - EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::HasValue(Foo{2})); + ASSERT_TRUE(Reply.has_value()); + EXPECT_THAT_EXPECTED(*Reply, llvm::HasValue(Foo{2})); // JSON response is integer, can't be parsed as string. llvm::Optional<llvm::Expected<std::string>> WrongTypeReply; WrongSignature(Foo{2}, capture(WrongTypeReply)); EXPECT_THAT(RawOutgoing.take("wrongSignature"), ElementsAre(llvm::json::Value(2))); - ASSERT_TRUE(Reply.hasValue()); - EXPECT_THAT_EXPECTED(WrongTypeReply.getValue(), + ASSERT_TRUE(Reply.has_value()); + EXPECT_THAT_EXPECTED(*WrongTypeReply, llvm::FailedWithMessage( HasSubstr("failed to decode wrongSignature reply"))); Fail(Foo{2}, capture(Reply)); EXPECT_THAT(RawOutgoing.take("fail"), ElementsAre(llvm::json::Value(2))); - ASSERT_TRUE(Reply.hasValue()); - EXPECT_THAT_EXPECTED(Reply.getValue(), llvm::FailedWithMessage("Params=2")); + ASSERT_TRUE(Reply.has_value()); + EXPECT_THAT_EXPECTED(*Reply, llvm::FailedWithMessage("Params=2")); } } // namespace diff --git a/clang-tools-extra/clangd/unittests/TidyProviderTests.cpp b/clang-tools-extra/clangd/unittests/TidyProviderTests.cpp index df3dcac..ece7f52 100644 --- a/clang-tools-extra/clangd/unittests/TidyProviderTests.cpp +++ b/clang-tools-extra/clangd/unittests/TidyProviderTests.cpp @@ -37,18 +37,18 @@ TEST(TidyProvider, NestedDirectories) { TidyProvider Provider = provideClangTidyFiles(FS); auto BaseOptions = getTidyOptionsForFile(Provider, testPath("File.cpp")); - ASSERT_TRUE(BaseOptions.Checks.hasValue()); + ASSERT_TRUE(BaseOptions.Checks.has_value()); EXPECT_EQ(*BaseOptions.Checks, "llvm-*"); EXPECT_EQ(BaseOptions.CheckOptions.lookup("TestKey").Value, "1"); auto Sub1Options = getTidyOptionsForFile(Provider, testPath("sub1/File.cpp")); - ASSERT_TRUE(Sub1Options.Checks.hasValue()); + ASSERT_TRUE(Sub1Options.Checks.has_value()); EXPECT_EQ(*Sub1Options.Checks, "misc-*"); EXPECT_EQ(Sub1Options.CheckOptions.lookup("TestKey").Value, "2"); auto Sub2Options = getTidyOptionsForFile(Provider, testPath("sub1/sub2/File.cpp")); - ASSERT_TRUE(Sub2Options.Checks.hasValue()); + ASSERT_TRUE(Sub2Options.Checks.has_value()); EXPECT_EQ(*Sub2Options.Checks, "misc-*,bugprone-*"); EXPECT_EQ(Sub2Options.CheckOptions.lookup("TestKey").Value, "3"); } diff --git a/clang-tools-extra/pseudo/lib/GLR.cpp b/clang-tools-extra/pseudo/lib/GLR.cpp index 1cee8f8..d93f682 100644 --- a/clang-tools-extra/pseudo/lib/GLR.cpp +++ b/clang-tools-extra/pseudo/lib/GLR.cpp @@ -375,11 +375,11 @@ private: for (auto &A : Params.Table.getActions(Head->State, Lookahead)) { if (A.kind() != LRTable::Action::Reduce) continue; - if (RID.hasValue()) + if (RID) return false; RID = A.getReduceRule(); } - if (!RID.hasValue()) + if (!RID) return true; // no reductions available, but we've processed the head! const auto &Rule = Params.G.lookupRule(*RID); const GSS::Node *Base = Head; diff --git a/clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp b/clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp index 970ffce..ea1ef73 100644 --- a/clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp +++ b/clang-tools-extra/unittests/clang-doc/ClangDocTest.cpp @@ -95,8 +95,8 @@ void CheckBaseInfo(Info *Expected, Info *Actual) { void CheckSymbolInfo(SymbolInfo *Expected, SymbolInfo *Actual) { CheckBaseInfo(Expected, Actual); - EXPECT_EQ(Expected->DefLoc.hasValue(), Actual->DefLoc.hasValue()); - if (Expected->DefLoc.hasValue() && Actual->DefLoc.hasValue()) { + EXPECT_EQ(Expected->DefLoc.has_value(), Actual->DefLoc.has_value()); + if (Expected->DefLoc && Actual->DefLoc) { EXPECT_EQ(Expected->DefLoc->LineNumber, Actual->DefLoc->LineNumber); EXPECT_EQ(Expected->DefLoc->Filename, Actual->DefLoc->Filename); } diff --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp index 3558b5f..5dcec03 100644 --- a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp @@ -129,14 +129,14 @@ TEST(ParseConfiguration, MergeConfigurations) { EXPECT_EQ("check1,check2,check3,check4", *Options.Checks); EXPECT_EQ("filter2", *Options.HeaderFilterRegex); EXPECT_EQ("user2", *Options.User); - ASSERT_TRUE(Options.ExtraArgs.hasValue()); + ASSERT_TRUE(Options.ExtraArgs.has_value()); EXPECT_EQ("arg1,arg2,arg3,arg4", llvm::join(Options.ExtraArgs->begin(), Options.ExtraArgs->end(), ",")); - ASSERT_TRUE(Options.ExtraArgsBefore.hasValue()); + ASSERT_TRUE(Options.ExtraArgsBefore.has_value()); EXPECT_EQ("arg-before1,arg-before2,arg-before3,arg-before4", llvm::join(Options.ExtraArgsBefore->begin(), Options.ExtraArgsBefore->end(), ",")); - ASSERT_TRUE(Options.UseColor.hasValue()); + ASSERT_TRUE(Options.UseColor.has_value()); EXPECT_TRUE(*Options.UseColor); } @@ -325,9 +325,9 @@ TEST(CheckOptionsValidation, ValidIntOptions) { CHECK_VAL(TestCheck.getIntLocal("IntExpected"), 1); CHECK_VAL(TestCheck.getIntGlobal("GlobalIntExpected"), 1); - EXPECT_FALSE(TestCheck.getIntLocal("IntInvalid1").hasValue()); - EXPECT_FALSE(TestCheck.getIntLocal("IntInvalid2").hasValue()); - EXPECT_FALSE(TestCheck.getIntGlobal("GlobalIntInvalid").hasValue()); + EXPECT_FALSE(TestCheck.getIntLocal("IntInvalid1").has_value()); + EXPECT_FALSE(TestCheck.getIntLocal("IntInvalid2").has_value()); + EXPECT_FALSE(TestCheck.getIntGlobal("GlobalIntInvalid").has_value()); ASSERT_EQ(TestCheck.getIntLocal("DefaultedIntInvalid", 1), 1); CHECK_VAL(TestCheck.getIntLocal<bool>("BoolITrueValue"), true); @@ -395,14 +395,14 @@ TEST(ValidConfiguration, ValidEnumOptions) { /*IgnoreCase*/ true), Colours::Violet); - EXPECT_FALSE(TestCheck.getIntLocal<Colours>("ValidWrongCase").hasValue()); - EXPECT_FALSE(TestCheck.getIntLocal<Colours>("NearMiss").hasValue()); - EXPECT_FALSE(TestCheck.getIntGlobal<Colours>("GlobalInvalid").hasValue()); + EXPECT_FALSE(TestCheck.getIntLocal<Colours>("ValidWrongCase").has_value()); + EXPECT_FALSE(TestCheck.getIntLocal<Colours>("NearMiss").has_value()); + EXPECT_FALSE(TestCheck.getIntGlobal<Colours>("GlobalInvalid").has_value()); EXPECT_FALSE( - TestCheck.getIntGlobal<Colours>("GlobalValidWrongCase").hasValue()); - EXPECT_FALSE(TestCheck.getIntGlobal<Colours>("GlobalNearMiss").hasValue()); + TestCheck.getIntGlobal<Colours>("GlobalValidWrongCase").has_value()); + EXPECT_FALSE(TestCheck.getIntGlobal<Colours>("GlobalNearMiss").has_value()); - EXPECT_FALSE(TestCheck.getIntLocal<Colours>("Invalid").hasValue()); + EXPECT_FALSE(TestCheck.getIntLocal<Colours>("Invalid").has_value()); EXPECT_THAT( DiagConsumer.take(), UnorderedElementsAre( diff --git a/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp b/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp index e4cd74e..c7ebd5e 100644 --- a/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp @@ -34,8 +34,8 @@ public: assert(Call != nullptr && "Did not find node \"foo\""); auto Hint = Aliaser->createAlias(*Result.Context, *Call, "::foo::bar", {"b", "some_alias"}); - if (Hint.hasValue()) - diag(Call->getBeginLoc(), "Fix for testing") << Hint.getValue(); + if (Hint) + diag(Call->getBeginLoc(), "Fix for testing") << *Hint; diag(Call->getBeginLoc(), "insert call") << FixItHint::CreateInsertion( Call->getBeginLoc(), diff --git a/clang-tools-extra/unittests/clang-tidy/OptionsProviderTest.cpp b/clang-tools-extra/unittests/clang-tidy/OptionsProviderTest.cpp index b99d078..5aa3730 100644 --- a/clang-tools-extra/unittests/clang-tidy/OptionsProviderTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/OptionsProviderTest.cpp @@ -53,9 +53,9 @@ TEST(ClangTidyOptionsProvider, InMemoryFileSystems) { ClangTidyOptions File3Options = FileOpt.getOptions("ProjectRoot/SubDir1/SubDir2/SubDir3/File.cpp"); - ASSERT_TRUE(File1Options.Checks.hasValue()); + ASSERT_TRUE(File1Options.Checks.has_value()); EXPECT_EQ(*File1Options.Checks, "-*,clang-diagnostic-*,readability-*"); - ASSERT_TRUE(File2Options.Checks.hasValue()); + ASSERT_TRUE(File2Options.Checks.has_value()); EXPECT_EQ(*File2Options.Checks, "bugprone-*,misc-*,clang-diagnostic-*"); // 2 and 3 should use the same config so these should also be the same. diff --git a/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp b/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp index 71c7159..43350cb 100644 --- a/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp @@ -37,8 +37,8 @@ public: auto Hint = Inserter->createUsingDeclaration(*Result.Context, *Call, "::foo::func"); - if (Hint.hasValue()) - diag(Call->getBeginLoc(), "Fix for testing") << Hint.getValue(); + if (Hint) + diag(Call->getBeginLoc(), "Fix for testing") << *Hint; diag(Call->getBeginLoc(), "insert call") << clang::FixItHint::CreateReplacement( diff --git a/clang/include/clang/APINotes/Types.h b/clang/include/clang/APINotes/Types.h index ed5250f..d98b3d9 100644 --- a/clang/include/clang/APINotes/Types.h +++ b/clang/include/clang/APINotes/Types.h @@ -76,8 +76,8 @@ public: } void setSwiftPrivate(llvm::Optional<bool> Private) { - SwiftPrivateSpecified = Private.hasValue(); - SwiftPrivate = Private.hasValue() ? *Private : 0; + SwiftPrivateSpecified = Private.has_value(); + SwiftPrivate = Private.value_or(0); } friend bool operator==(const CommonEntityInfo &, const CommonEntityInfo &); diff --git a/clang/include/clang/AST/PropertiesBase.td b/clang/include/clang/AST/PropertiesBase.td index 559f29e..0f7acf6 100644 --- a/clang/include/clang/AST/PropertiesBase.td +++ b/clang/include/clang/AST/PropertiesBase.td @@ -520,15 +520,15 @@ let Class = PropertyTypeCase<APValue, "LValue"> in { if (hasBase) { if (isTypeInfo) { base = APValue::LValueBase::getTypeInfo( - TypeInfoLValue(typeInfo.getValue().getTypePtr()), type.getValue()); + TypeInfoLValue(typeInfo->getTypePtr()), *type); elemTy = base.getTypeInfoType(); } else if (isExpr) { - base = APValue::LValueBase(cast<Expr>(stmt.getValue()), - callIndex.getValue(), version.getValue()); + base = APValue::LValueBase(cast<Expr>(*stmt), + *callIndex, *version); elemTy = base.get<const Expr *>()->getType(); } else { - base = APValue::LValueBase(cast<ValueDecl>(decl.getValue()), - callIndex.getValue(), version.getValue()); + base = APValue::LValueBase(cast<ValueDecl>(*decl), + *callIndex, *version); elemTy = base.get<const ValueDecl *>()->getType(); } } diff --git a/clang/include/clang/Analysis/PathDiagnostic.h b/clang/include/clang/Analysis/PathDiagnostic.h index 47cb549..9877f1e 100644 --- a/clang/include/clang/Analysis/PathDiagnostic.h +++ b/clang/include/clang/Analysis/PathDiagnostic.h @@ -544,8 +544,8 @@ public: /// flag may have been previously set, at which point it will not /// be reset unless one specifies to do so. void setPrunable(bool isPrunable, bool override = false) { - if (IsPrunable.hasValue() && !override) - return; + if (IsPrunable && !override) + return; IsPrunable = isPrunable; } diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index ba4d0bb..8b8b1b2 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -1766,9 +1766,9 @@ public: template <typename T> friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { - if (Diag.ImmediateDiag.hasValue()) + if (Diag.ImmediateDiag) *Diag.ImmediateDiag << Value; - else if (Diag.PartialDiagId.hasValue()) + else if (Diag.PartialDiagId) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; @@ -1780,26 +1780,26 @@ public: template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const SemaDiagnosticBuilder &operator<<(T &&V) const { - if (ImmediateDiag.hasValue()) + if (ImmediateDiag) *ImmediateDiag << std::move(V); - else if (PartialDiagId.hasValue()) + else if (PartialDiagId) S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); return *this; } friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { - if (Diag.ImmediateDiag.hasValue()) + if (Diag.ImmediateDiag) PD.Emit(*Diag.ImmediateDiag); - else if (Diag.PartialDiagId.hasValue()) + else if (Diag.PartialDiagId) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; return Diag; } void AddFixItHint(const FixItHint &Hint) const { - if (ImmediateDiag.hasValue()) + if (ImmediateDiag) ImmediateDiag->AddFixItHint(Hint); - else if (PartialDiagId.hasValue()) + else if (PartialDiagId) S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); } diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h index a01b326..59fe535e 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h @@ -414,7 +414,8 @@ public: bool isArgumentConstructedDirectly(unsigned Index) const { // This assumes that the object was not yet removed from the state. return ExprEngine::getObjectUnderConstruction( - getState(), {getOriginExpr(), Index}, getLocationContext()).hasValue(); + getState(), {getOriginExpr(), Index}, getLocationContext()) + .has_value(); } /// Some calls have parameter numbering mismatched from argument numbering. @@ -1016,9 +1017,8 @@ public: } SVal getObjectUnderConstruction() const { - return ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(), - getLocationContext()) - .getValue(); + return *ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(), + getLocationContext()); } /// Number of non-placement arguments to the call. It is equal to 2 for diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h index 11c60b6..92a37c6 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h @@ -53,25 +53,17 @@ public: } /// Return true if the constraint is perfectly constrained to 'true'. - bool isConstrainedTrue() const { - return Val.hasValue() && Val.getValue(); - } + bool isConstrainedTrue() const { return Val && *Val; } /// Return true if the constraint is perfectly constrained to 'false'. - bool isConstrainedFalse() const { - return Val.hasValue() && !Val.getValue(); - } + bool isConstrainedFalse() const { return Val && !*Val; } /// Return true if the constrained is perfectly constrained. - bool isConstrained() const { - return Val.hasValue(); - } + bool isConstrained() const { return Val.has_value(); } /// Return true if the constrained is underconstrained and we do not know /// if the constraint is true of value. - bool isUnderconstrained() const { - return !Val.hasValue(); - } + bool isUnderconstrained() const { return !Val.has_value(); } }; class ConstraintManager { diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h index 250ba4f..6c8ed07 100644 --- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h +++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h @@ -341,10 +341,10 @@ protected: addStateConstraints(NewState); Optional<bool> res = Solver->check(); - if (!res.hasValue()) + if (!res) Cached[hash] = ConditionTruthVal(); else - Cached[hash] = ConditionTruthVal(res.getValue()); + Cached[hash] = ConditionTruthVal(*res); return Cached[hash]; } diff --git a/clang/include/clang/Support/RISCVVIntrinsicUtils.h b/clang/include/clang/Support/RISCVVIntrinsicUtils.h index 0e9fe97..8d34caf 100644 --- a/clang/include/clang/Support/RISCVVIntrinsicUtils.h +++ b/clang/include/clang/Support/RISCVVIntrinsicUtils.h @@ -209,8 +209,8 @@ public: } bool isValid() const { return Valid; } - bool isScalar() const { return Scale.hasValue() && Scale.getValue() == 0; } - bool isVector() const { return Scale.hasValue() && Scale.getValue() != 0; } + bool isScalar() const { return Scale && *Scale == 0; } + bool isVector() const { return Scale && *Scale != 0; } bool isVector(unsigned Width) const { return isVector() && ElementBitwidth == Width; } diff --git a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h index e0d16df..b3882c2 100644 --- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h +++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h @@ -94,9 +94,9 @@ public: assert(!isDirectory() && "not a file"); assert(Contents && "contents not initialized"); if (auto *Directives = Contents->DepDirectives.load()) { - if (Directives->hasValue()) + if (Directives->has_value()) return ArrayRef<dependency_directives_scan::Directive>( - Directives->getValue()); + Directives->value()); } return None; } diff --git a/clang/lib/AST/AttrImpl.cpp b/clang/lib/AST/AttrImpl.cpp index 7b8acfc..deb28be 100644 --- a/clang/lib/AST/AttrImpl.cpp +++ b/clang/lib/AST/AttrImpl.cpp @@ -168,24 +168,24 @@ OMPDeclareTargetDeclAttr::getActiveAttr(const ValueDecl *VD) { llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(const ValueDecl *VD) { llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD); - if (ActiveAttr.hasValue()) - return ActiveAttr.getValue()->getMapType(); + if (ActiveAttr) + return ActiveAttr.value()->getMapType(); return llvm::None; } llvm::Optional<OMPDeclareTargetDeclAttr::DevTypeTy> OMPDeclareTargetDeclAttr::getDeviceType(const ValueDecl *VD) { llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD); - if (ActiveAttr.hasValue()) - return ActiveAttr.getValue()->getDevType(); + if (ActiveAttr) + return ActiveAttr.value()->getDevType(); return llvm::None; } llvm::Optional<SourceLocation> OMPDeclareTargetDeclAttr::getLocation(const ValueDecl *VD) { llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = getActiveAttr(VD); - if (ActiveAttr.hasValue()) - return ActiveAttr.getValue()->getRange().getBegin(); + if (ActiveAttr) + return ActiveAttr.value()->getRange().getBegin(); return llvm::None; } diff --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp b/clang/lib/ASTMatchers/Dynamic/Parser.cpp index ec14f7a..6470df2 100644 --- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp +++ b/clang/lib/ASTMatchers/Dynamic/Parser.cpp @@ -397,9 +397,9 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue *Value) { assert(NamedValue.isMatcher()); llvm::Optional<DynTypedMatcher> Result = NamedValue.getMatcher().getSingleMatcher(); - if (Result.hasValue()) { + if (Result) { llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID); - if (Bound.hasValue()) { + if (Bound) { *Value = VariantMatcher::SingleMatcher(*Bound); return true; } diff --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp b/clang/lib/ASTMatchers/Dynamic/Registry.cpp index 72629d0..42193e6 100644 --- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp +++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp @@ -797,9 +797,9 @@ VariantMatcher Registry::constructBoundMatcher(MatcherCtor Ctor, if (Out.isNull()) return Out; llvm::Optional<DynTypedMatcher> Result = Out.getSingleMatcher(); - if (Result.hasValue()) { + if (Result) { llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID); - if (Bound.hasValue()) { + if (Bound) { return VariantMatcher::SingleMatcher(*Bound); } } diff --git a/clang/lib/Analysis/BodyFarm.cpp b/clang/lib/Analysis/BodyFarm.cpp index 3587cf4..f182506 100644 --- a/clang/lib/Analysis/BodyFarm.cpp +++ b/clang/lib/Analysis/BodyFarm.cpp @@ -697,8 +697,8 @@ static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D) Stmt *BodyFarm::getBody(const FunctionDecl *D) { Optional<Stmt *> &Val = Bodies[D]; - if (Val.hasValue()) - return Val.getValue(); + if (Val) + return *Val; Val = nullptr; @@ -872,8 +872,8 @@ Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) { return nullptr; Optional<Stmt *> &Val = Bodies[D]; - if (Val.hasValue()) - return Val.getValue(); + if (Val) + return *Val; Val = nullptr; // For now, we only synthesize getters. diff --git a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp index c0b8119..3a362d49 100644 --- a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp +++ b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp @@ -31,13 +31,10 @@ buildStmtToBasicBlockMap(const CFG &Cfg) { if (Block == nullptr) continue; - for (const CFGElement &Element : *Block) { - auto Stmt = Element.getAs<CFGStmt>(); - if (!Stmt.hasValue()) - continue; + for (const CFGElement &Element : *Block) + if (auto Stmt = Element.getAs<CFGStmt>()) + StmtToBlock[Stmt->getStmt()] = Block; - StmtToBlock[Stmt.getValue().getStmt()] = Block; - } if (const Stmt *TerminatorStmt = Block->getTerminatorStmt()) StmtToBlock[TerminatorStmt] = Block; } diff --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp index 68e897e..0de4bca 100644 --- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp +++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp @@ -50,8 +50,8 @@ public: auto BlockIT = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S)); assert(BlockIT != CFCtx.getStmtToBlock().end()); const auto &State = BlockToState[BlockIT->getSecond()->getBlockID()]; - assert(State.hasValue()); - return &State.getValue().Env; + assert(State); + return &State->Env; } private: @@ -209,10 +209,10 @@ static TypeErasedDataflowAnalysisState computeBlockInputState( // loop back edge to `Block`. const llvm::Optional<TypeErasedDataflowAnalysisState> &MaybePredState = BlockStates[Pred->getBlockID()]; - if (!MaybePredState.hasValue()) + if (!MaybePredState) continue; - TypeErasedDataflowAnalysisState PredState = MaybePredState.getValue(); + TypeErasedDataflowAnalysisState PredState = *MaybePredState; if (ApplyBuiltinTransfer) { if (const Stmt *PredTerminatorStmt = Pred->getTerminatorStmt()) { const StmtToEnvMapImpl StmtToEnv(CFCtx, BlockStates); @@ -222,14 +222,14 @@ static TypeErasedDataflowAnalysisState computeBlockInputState( } } - if (MaybeState.hasValue()) { + if (MaybeState) { Analysis.joinTypeErased(MaybeState->Lattice, PredState.Lattice); MaybeState->Env.join(PredState.Env, Analysis); } else { MaybeState = std::move(PredState); } } - if (!MaybeState.hasValue()) { + if (!MaybeState) { // FIXME: Consider passing `Block` to `Analysis.typeErasedInitialElement()` // to enable building analyses like computation of dominators that // initialize the state of each basic block differently. @@ -367,8 +367,8 @@ runTypeErasedDataflowAnalysis(const ControlFlowContext &CFCtx, TypeErasedDataflowAnalysisState NewBlockState = transferBlock(CFCtx, BlockStates, *Block, InitEnv, Analysis); - if (OldBlockState.hasValue() && - Analysis.isEqualTypeErased(OldBlockState.getValue().Lattice, + if (OldBlockState && + Analysis.isEqualTypeErased(OldBlockState->Lattice, NewBlockState.Lattice) && OldBlockState->Env.equivalentTo(NewBlockState.Env, Analysis)) { // The state of `Block` didn't change after transfer so there's no need to diff --git a/clang/lib/Analysis/PathDiagnostic.cpp b/clang/lib/Analysis/PathDiagnostic.cpp index 90c4624..b5be645 100644 --- a/clang/lib/Analysis/PathDiagnostic.cpp +++ b/clang/lib/Analysis/PathDiagnostic.cpp @@ -319,8 +319,8 @@ static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y) { for ( ; X_I != X_end && Y_I != Y_end; ++X_I, ++Y_I) { Optional<bool> b = comparePiece(**X_I, **Y_I); - if (b.hasValue()) - return b.getValue(); + if (b) + return *b; } return None; @@ -396,8 +396,8 @@ static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) { return (*XI) < (*YI); } Optional<bool> b = comparePath(X.path, Y.path); - assert(b.hasValue()); - return b.getValue(); + assert(b); + return *b; } void PathDiagnosticConsumer::FlushDiagnostics( diff --git a/clang/lib/Analysis/UninitializedValues.cpp b/clang/lib/Analysis/UninitializedValues.cpp index 811146e..f1be392 100644 --- a/clang/lib/Analysis/UninitializedValues.cpp +++ b/clang/lib/Analysis/UninitializedValues.cpp @@ -148,8 +148,8 @@ public: Value getValue(const CFGBlock *block, const CFGBlock *dstBlock, const VarDecl *vd) { const Optional<unsigned> &idx = declToIndex.getValueIndex(vd); - assert(idx.hasValue()); - return getValueVector(block)[idx.getValue()]; + assert(idx); + return getValueVector(block)[*idx]; } }; @@ -209,8 +209,8 @@ void CFGBlockValues::resetScratch() { ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) { const Optional<unsigned> &idx = declToIndex.getValueIndex(vd); - assert(idx.hasValue()); - return scratch[idx.getValue()]; + assert(idx); + return scratch[*idx]; } //------------------------------------------------------------------------====// diff --git a/clang/lib/Basic/Targets/RISCV.cpp b/clang/lib/Basic/Targets/RISCV.cpp index 098bf21..722a605 100644 --- a/clang/lib/Basic/Targets/RISCV.cpp +++ b/clang/lib/Basic/Targets/RISCV.cpp @@ -251,8 +251,8 @@ bool RISCVTargetInfo::hasFeature(StringRef Feature) const { .Case("riscv64", Is64Bit) .Case("64bit", Is64Bit) .Default(None); - if (Result.hasValue()) - return Result.getValue(); + if (Result) + return *Result; if (ISAInfo->isSupportedExtensionFeature(Feature)) return ISAInfo->hasExtension(Feature); diff --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp index 153f299..ec9e325 100644 --- a/clang/lib/CodeGen/CGClass.cpp +++ b/clang/lib/CodeGen/CGClass.cpp @@ -1782,15 +1782,15 @@ namespace { if (!StartIndex) StartIndex = FieldIndex; } else if (StartIndex) { - EHStack.pushCleanup<SanitizeDtorFieldRange>( - NormalAndEHCleanup, DD, StartIndex.getValue(), FieldIndex); + EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD, + *StartIndex, FieldIndex); StartIndex = None; } } void End() { if (StartIndex) EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD, - StartIndex.getValue(), -1); + *StartIndex, -1); } }; } // end anonymous namespace diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 17b8e6b..34d8b3a 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -2826,12 +2826,12 @@ bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn, CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); // First, check the function name. Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind); - if (V.hasValue()) + if (V) return *V; // Next, check the source location. if (Loc.isValid()) { Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind); - if (V.hasValue()) + if (V) return *V; } // If location is unknown, this may be a compiler-generated function. Assume diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp index d831422..721c8f8 100644 --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -3325,8 +3325,8 @@ class OffloadingActionBuilder final { A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A, AssociatedOffloadKind); - if (CompileDeviceOnly && CurPhase == FinalPhase && - BundleOutput.hasValue() && BundleOutput.getValue()) { + if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput && + *BundleOutput) { for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { OffloadAction::DeviceDependences DDep; DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], diff --git a/clang/lib/Driver/ToolChains/AVR.cpp b/clang/lib/Driver/ToolChains/AVR.cpp index 2547d13..0b68a32 100644 --- a/clang/lib/Driver/ToolChains/AVR.cpp +++ b/clang/lib/Driver/ToolChains/AVR.cpp @@ -475,9 +475,9 @@ void AVR::Linker::ConstructJob(Compilation &C, const JobAction &JA, D.Diag(diag::warn_drv_avr_stdlib_not_linked); } - if (SectionAddressData.hasValue()) { - std::string DataSectionArg = std::string("-Tdata=0x") + - llvm::utohexstr(SectionAddressData.getValue()); + if (SectionAddressData) { + std::string DataSectionArg = + std::string("-Tdata=0x") + llvm::utohexstr(*SectionAddressData); CmdArgs.push_back(Args.MakeArgString(DataSectionArg)); } else { // We do not have an entry for this CPU in the address mapping table yet. diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 5142b72..286d414 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -2340,8 +2340,8 @@ void Clang::AddHexagonTargetArgs(const ArgList &Args, if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) { CmdArgs.push_back("-mllvm"); - CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" + - Twine(G.getValue()))); + CmdArgs.push_back( + Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G))); } if (!Args.hasArg(options::OPT_fno_short_enums)) diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp b/clang/lib/Driver/ToolChains/Gnu.cpp index dc99010..d813def 100644 --- a/clang/lib/Driver/ToolChains/Gnu.cpp +++ b/clang/lib/Driver/ToolChains/Gnu.cpp @@ -2086,8 +2086,8 @@ void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const { } bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const { - if (BiarchSibling.hasValue()) { - M = BiarchSibling.getValue(); + if (BiarchSibling) { + M = *BiarchSibling; return true; } return false; diff --git a/clang/lib/Driver/ToolChains/Hexagon.cpp b/clang/lib/Driver/ToolChains/Hexagon.cpp index 9142dba..e129e30 100644 --- a/clang/lib/Driver/ToolChains/Hexagon.cpp +++ b/clang/lib/Driver/ToolChains/Hexagon.cpp @@ -340,8 +340,8 @@ constructHexagonLinkArgs(Compilation &C, const JobAction &JA, CmdArgs.push_back("-pie"); if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) { - CmdArgs.push_back(Args.MakeArgString("-G" + Twine(G.getValue()))); - UseG0 = G.getValue() == 0; + CmdArgs.push_back(Args.MakeArgString("-G" + Twine(*G))); + UseG0 = *G == 0; } CmdArgs.push_back("-o"); diff --git a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp index 589bf8d..1ca041f 100644 --- a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp +++ b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp @@ -725,11 +725,11 @@ static bool getLiteralInfo(SourceRange literalRange, break; } - if (!UpperU.hasValue() && !UpperL.hasValue()) + if (!UpperU && !UpperL) UpperU = UpperL = true; - else if (UpperU.hasValue() && !UpperL.hasValue()) + else if (UpperU && !UpperL) UpperL = UpperU; - else if (UpperL.hasValue() && !UpperU.hasValue()) + else if (UpperL && !UpperU) UpperU = UpperL; Info.U = *UpperU ? "U" : "u"; diff --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp index c4797ce..b1450b2 100644 --- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp +++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp @@ -31,14 +31,14 @@ namespace { /// at position \p Key. void serializeObject(Object &Paren, StringRef Key, Optional<Object> Obj) { if (Obj) - Paren[Key] = std::move(Obj.getValue()); + Paren[Key] = std::move(*Obj); } /// Helper function to inject a JSON array \p Array into object \p Paren at /// position \p Key. void serializeArray(Object &Paren, StringRef Key, Optional<Array> Array) { if (Array) - Paren[Key] = std::move(Array.getValue()); + Paren[Key] = std::move(*Array); } /// Serialize a \c VersionTuple \p V with the Symbol Graph semantic version diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp index b982ca7..95e5b04 100644 --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -115,9 +115,9 @@ bool CompilerInstance::createTarget() { auto TO = std::make_shared<TargetOptions>(); TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple); if (getFrontendOpts().AuxTargetCPU) - TO->CPU = getFrontendOpts().AuxTargetCPU.getValue(); + TO->CPU = *getFrontendOpts().AuxTargetCPU; if (getFrontendOpts().AuxTargetFeatures) - TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.getValue(); + TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures; TO->HostTriple = getTarget().getTriple().str(); setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO)); } diff --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp index c0eed3a..4b53d6d 100644 --- a/clang/lib/Frontend/CompilerInvocation.cpp +++ b/clang/lib/Frontend/CompilerInvocation.cpp @@ -1951,8 +1951,8 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, << "-fdiagnostics-hotness-threshold="; } else { Opts.DiagnosticsHotnessThreshold = *ResultOrErr; - if ((!Opts.DiagnosticsHotnessThreshold.hasValue() || - Opts.DiagnosticsHotnessThreshold.getValue() > 0) && + if ((!Opts.DiagnosticsHotnessThreshold || + *Opts.DiagnosticsHotnessThreshold > 0) && !UsingProfile) Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) << "-fdiagnostics-hotness-threshold="; @@ -1968,8 +1968,8 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, << "-fdiagnostics-misexpect-tolerance="; } else { Opts.DiagnosticsMisExpectTolerance = *ResultOrErr; - if ((!Opts.DiagnosticsMisExpectTolerance.hasValue() || - Opts.DiagnosticsMisExpectTolerance.getValue() > 0) && + if ((!Opts.DiagnosticsMisExpectTolerance || + *Opts.DiagnosticsMisExpectTolerance > 0) && !UsingProfile) Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo) << "-fdiagnostics-misexpect-tolerance="; @@ -2578,10 +2578,10 @@ static void GenerateFrontendArgs(const FrontendOptions &Opts, for (const auto &ModuleFile : Opts.ModuleFiles) GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA); - if (Opts.AuxTargetCPU.hasValue()) + if (Opts.AuxTargetCPU) GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA); - if (Opts.AuxTargetFeatures.hasValue()) + if (Opts.AuxTargetFeatures) for (const auto &Feature : *Opts.AuxTargetFeatures) GenerateArg(Args, OPT_aux_target_feature, Feature, SA); diff --git a/clang/lib/Frontend/InitPreprocessor.cpp b/clang/lib/Frontend/InitPreprocessor.cpp index 1032cb2..033f332 100644 --- a/clang/lib/Frontend/InitPreprocessor.cpp +++ b/clang/lib/Frontend/InitPreprocessor.cpp @@ -831,12 +831,12 @@ static void InitializePredefinedMacros(const TargetInfo &TI, VersionTuple tuple = LangOpts.ObjCRuntime.getVersion(); unsigned minor = 0; - if (tuple.getMinor().hasValue()) - minor = tuple.getMinor().getValue(); + if (tuple.getMinor()) + minor = *tuple.getMinor(); unsigned subminor = 0; - if (tuple.getSubminor().hasValue()) - subminor = tuple.getSubminor().getValue(); + if (tuple.getSubminor()) + subminor = *tuple.getSubminor(); Builder.defineMacro("__OBJFW_RUNTIME_ABI__", Twine(tuple.getMajor() * 10000 + minor * 100 + diff --git a/clang/lib/Lex/DependencyDirectivesScanner.cpp b/clang/lib/Lex/DependencyDirectivesScanner.cpp index d858384..d7c40e2 100644 --- a/clang/lib/Lex/DependencyDirectivesScanner.cpp +++ b/clang/lib/Lex/DependencyDirectivesScanner.cpp @@ -549,8 +549,8 @@ Scanner::tryLexIdentifierOrSkipLine(const char *&First, const char *const End) { StringRef Scanner::lexIdentifier(const char *&First, const char *const End) { Optional<StringRef> Id = tryLexIdentifierOrSkipLine(First, End); - assert(Id.hasValue() && "expected identifier token"); - return Id.getValue(); + assert(Id && "expected identifier token"); + return *Id; } bool Scanner::isNextIdentifierOrSkipLine(StringRef Id, const char *&First, diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp index 4a8127d..54445d9 100644 --- a/clang/lib/Lex/MacroInfo.cpp +++ b/clang/lib/Lex/MacroInfo.cpp @@ -209,12 +209,11 @@ MacroDirective::DefInfo MacroDirective::getDefinition() { } VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD); - if (!isPublic.hasValue()) + if (!isPublic) isPublic = VisMD->isPublic(); } - return DefInfo(nullptr, UndefLoc, - !isPublic.hasValue() || isPublic.getValue()); + return DefInfo(nullptr, UndefLoc, !isPublic || *isPublic); } const MacroDirective::DefInfo diff --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp index c791e3e..57e3446 100644 --- a/clang/lib/Lex/ModuleMap.cpp +++ b/clang/lib/Lex/ModuleMap.cpp @@ -1219,8 +1219,8 @@ void ModuleMap::resolveHeaderDirectives( Module *Mod, llvm::Optional<const FileEntry *> File) const { bool NeedsFramework = false; SmallVector<Module::UnresolvedHeaderDirective, 1> NewHeaders; - const auto Size = File ? File.getValue()->getSize() : 0; - const auto ModTime = File ? File.getValue()->getModificationTime() : 0; + const auto Size = File ? File.value()->getSize() : 0; + const auto ModTime = File ? File.value()->getModificationTime() : 0; for (auto &Header : Mod->UnresolvedHeaders) { if (File && ((Header.ModTime && Header.ModTime != ModTime) || diff --git a/clang/lib/Lex/PPMacroExpansion.cpp b/clang/lib/Lex/PPMacroExpansion.cpp index 49e1473..fb0d67d 100644 --- a/clang/lib/Lex/PPMacroExpansion.cpp +++ b/clang/lib/Lex/PPMacroExpansion.cpp @@ -1325,11 +1325,11 @@ already_lexed: // The last ')' has been reached; return the value if one found or // a diagnostic and a dummy value. - if (Result.hasValue()) { - OS << Result.getValue(); + if (Result) { + OS << *Result; // For strict conformance to __has_cpp_attribute rules, use 'L' // suffix for dated literals. - if (Result.getValue() > 1) + if (*Result > 1) OS << 'L'; } else { OS << 0; diff --git a/clang/lib/Lex/PreprocessingRecord.cpp b/clang/lib/Lex/PreprocessingRecord.cpp index 432068b..66610c4 100644 --- a/clang/lib/Lex/PreprocessingRecord.cpp +++ b/clang/lib/Lex/PreprocessingRecord.cpp @@ -114,8 +114,8 @@ bool PreprocessingRecord::isEntityInFileID(iterator PPEI, FileID FID) { // deserializing it. Optional<bool> IsInFile = ExternalSource->isPreprocessedEntityInFileID(LoadedIndex, FID); - if (IsInFile.hasValue()) - return IsInFile.getValue(); + if (IsInFile) + return *IsInFile; // The external source did not provide a definite answer, go and deserialize // the entity to check it. diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp index 1fa82a19..d508d2d 100644 --- a/clang/lib/Parse/ParseOpenMP.cpp +++ b/clang/lib/Parse/ParseOpenMP.cpp @@ -1873,14 +1873,13 @@ void Parser::ParseOMPDeclareTargetClauses( if (IsDeviceTypeClause) { Optional<SimpleClauseData> DevTypeData = parseOpenMPSimpleClause(*this, OMPC_device_type); - if (DevTypeData.hasValue()) { + if (DevTypeData) { if (DeviceTypeLoc.isValid()) { // We already saw another device_type clause, diagnose it. - Diag(DevTypeData.getValue().Loc, - diag::warn_omp_more_one_device_type_clause); + Diag(DevTypeData->Loc, diag::warn_omp_more_one_device_type_clause); break; } - switch (static_cast<OpenMPDeviceType>(DevTypeData.getValue().Type)) { + switch (static_cast<OpenMPDeviceType>(DevTypeData->Type)) { case OMPC_DEVICE_TYPE_any: DTCI.DT = OMPDeclareTargetDeclAttr::DT_Any; break; @@ -2313,9 +2312,9 @@ Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl( Sema::DeclareTargetContextInfo DTCI(DKind, DTLoc); if (HasClauses) ParseOMPDeclareTargetClauses(DTCI); - bool HasImplicitMappings = - DKind == OMPD_begin_declare_target || !HasClauses || - (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect.hasValue()); + bool HasImplicitMappings = DKind == OMPD_begin_declare_target || + !HasClauses || + (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect); // Skip the last annot_pragma_openmp_end. ConsumeAnyToken(); @@ -3620,20 +3619,18 @@ OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind, if (!Val || ParseOnly) return nullptr; if (getLangOpts().OpenMP < 51 && Kind == OMPC_default && - (static_cast<DefaultKind>(Val.getValue().Type) == OMP_DEFAULT_private || - static_cast<DefaultKind>(Val.getValue().Type) == - OMP_DEFAULT_firstprivate)) { - Diag(Val.getValue().LOpen, diag::err_omp_invalid_dsa) - << getOpenMPClauseName(static_cast<DefaultKind>(Val.getValue().Type) == + (static_cast<DefaultKind>(Val->Type) == OMP_DEFAULT_private || + static_cast<DefaultKind>(Val->Type) == OMP_DEFAULT_firstprivate)) { + Diag(Val->LOpen, diag::err_omp_invalid_dsa) + << getOpenMPClauseName(static_cast<DefaultKind>(Val->Type) == OMP_DEFAULT_private ? OMPC_private : OMPC_firstprivate) << getOpenMPClauseName(OMPC_default) << "5.1"; return nullptr; } - return Actions.ActOnOpenMPSimpleClause( - Kind, Val.getValue().Type, Val.getValue().TypeLoc, Val.getValue().LOpen, - Val.getValue().Loc, Val.getValue().RLoc); + return Actions.ActOnOpenMPSimpleClause(Kind, Val->Type, Val->TypeLoc, + Val->LOpen, Val->Loc, Val->RLoc); } /// Parsing of OpenMP clauses like 'ordered'. diff --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp index a3b15fe..a0bc1b5 100644 --- a/clang/lib/Sema/SemaCUDA.cpp +++ b/clang/lib/Sema/SemaCUDA.cpp @@ -381,13 +381,12 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, InferredTarget = BaseMethodTarget; } else { bool ResolutionError = resolveCalleeCUDATargetConflict( - InferredTarget.getValue(), BaseMethodTarget, - InferredTarget.getPointer()); + *InferredTarget, BaseMethodTarget, InferredTarget.getPointer()); if (ResolutionError) { if (Diagnose) { Diag(ClassDecl->getLocation(), diag::note_implicit_member_target_infer_collision) - << (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget; + << (unsigned)CSM << *InferredTarget << BaseMethodTarget; } MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context)); return true; @@ -425,14 +424,12 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, InferredTarget = FieldMethodTarget; } else { bool ResolutionError = resolveCalleeCUDATargetConflict( - InferredTarget.getValue(), FieldMethodTarget, - InferredTarget.getPointer()); + *InferredTarget, FieldMethodTarget, InferredTarget.getPointer()); if (ResolutionError) { if (Diagnose) { Diag(ClassDecl->getLocation(), diag::note_implicit_member_target_infer_collision) - << (unsigned)CSM << InferredTarget.getValue() - << FieldMethodTarget; + << (unsigned)CSM << *InferredTarget << FieldMethodTarget; } MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context)); return true; @@ -444,10 +441,10 @@ bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, // If no target was inferred, mark this member as __host__ __device__; // it's the least restrictive option that can be invoked from any target. bool NeedsH = true, NeedsD = true; - if (InferredTarget.hasValue()) { - if (InferredTarget.getValue() == CFT_Device) + if (InferredTarget) { + if (*InferredTarget == CFT_Device) NeedsH = false; - else if (InferredTarget.getValue() == CFT_Host) + else if (*InferredTarget == CFT_Host) NeedsD = false; } diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 28cfdfc..c83f648 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -1873,9 +1873,9 @@ static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { return 2; return llvm::Optional<unsigned>{}; }(); - if (DiagSelect.hasValue()) { + if (DiagSelect) { S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) - << DiagSelect.getValue() << TheCall->getSourceRange(); + << *DiagSelect << TheCall->getSourceRange(); return ExprError(); } diff --git a/clang/lib/Sema/SemaCodeComplete.cpp b/clang/lib/Sema/SemaCodeComplete.cpp index 8c9ed53..86bad73 100644 --- a/clang/lib/Sema/SemaCodeComplete.cpp +++ b/clang/lib/Sema/SemaCodeComplete.cpp @@ -5362,8 +5362,8 @@ private: // Overwrite existing if the new member has more info. // The preference of . vs :: vs -> is fairly arbitrary. if (/*Inserted*/ R.second || - std::make_tuple(M.ArgTypes.hasValue(), M.ResultType != nullptr, - M.Operator) > std::make_tuple(O.ArgTypes.hasValue(), + std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr, + M.Operator) > std::make_tuple(O.ArgTypes.has_value(), O.ResultType != nullptr, O.Operator)) O = std::move(M); diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 2e06207..c9c32f9 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -15444,9 +15444,9 @@ void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( // (3.1) If the allocation function takes an argument of type // std​::​align_Âval_Ât, the storage will have the alignment // specified by the value of this argument. - if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { + if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) { FD->addAttr(AllocAlignAttr::CreateImplicit( - Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); + Context, ParamIdx(*AlignmentParam, FD), FD->getLocation())); } // FIXME: @@ -19102,12 +19102,12 @@ Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, // #pragma omp declare target to(*) device_type(*). // Therefore DevTy having no value does not imply host. The emission status // will be checked again at the end of compilation unit with Final = true. - if (DevTy.hasValue()) + if (DevTy) if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) return FunctionEmissionStatus::OMPDiscarded; // If we have an explicit value for the device type, or we are in a target // declare context, we need to emit all extern and used symbols. - if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) + if (isInOpenMPDeclareTargetContext() || DevTy) if (IsEmittedForExternalSymbol()) return FunctionEmissionStatus::Emitted; // Device mode only emits what it must, if it wasn't tagged yet and needed, diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp index 73a4be5..942e7f1 100644 --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -2673,19 +2673,19 @@ static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { if (IOSToWatchOSMapping) { if (auto MappedVersion = IOSToWatchOSMapping->map( Version, MinimumWatchOSVersion, None)) { - return MappedVersion.getValue(); + return *MappedVersion; } } auto Major = Version.getMajor(); auto NewMajor = Major >= 9 ? Major - 7 : 0; if (NewMajor >= 2) { - if (Version.getMinor().hasValue()) { - if (Version.getSubminor().hasValue()) - return VersionTuple(NewMajor, Version.getMinor().getValue(), - Version.getSubminor().getValue()); + if (Version.getMinor()) { + if (Version.getSubminor()) + return VersionTuple(NewMajor, *Version.getMinor(), + *Version.getSubminor()); else - return VersionTuple(NewMajor, Version.getMinor().getValue()); + return VersionTuple(NewMajor, *Version.getMinor()); } return VersionTuple(NewMajor); } diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp index bb1cf4b..1e7975e 100644 --- a/clang/lib/Sema/SemaExprCXX.cpp +++ b/clang/lib/Sema/SemaExprCXX.cpp @@ -2274,10 +2274,10 @@ Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, // How many bytes do we want to allocate here? llvm::Optional<llvm::APInt> AllocationSize; - if (!ArraySize.hasValue() && !AllocType->isDependentType()) { + if (!ArraySize && !AllocType->isDependentType()) { // For non-array operator new, we only want to allocate one element. AllocationSize = SingleEltSize; - } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) { + } else if (KnownArraySize && !AllocType->isDependentType()) { // For array operator new, only deal with static array size case. bool Overflow; AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp index 7395e67..fbea99d 100644 --- a/clang/lib/Sema/SemaOpenMP.cpp +++ b/clang/lib/Sema/SemaOpenMP.cpp @@ -822,29 +822,29 @@ public: /// false - otherwise. bool isOrderedRegion() const { if (const SharingMapTy *Top = getTopOfStackOrNull()) - return Top->OrderedRegion.hasValue(); + return Top->OrderedRegion.has_value(); return false; } /// Returns optional parameter for the ordered region. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { if (const SharingMapTy *Top = getTopOfStackOrNull()) - if (Top->OrderedRegion.hasValue()) - return Top->OrderedRegion.getValue(); + if (Top->OrderedRegion) + return *Top->OrderedRegion; return std::make_pair(nullptr, nullptr); } /// Returns true, if parent region is ordered (has associated /// 'ordered' clause), false - otherwise. bool isParentOrderedRegion() const { if (const SharingMapTy *Parent = getSecondOnStackOrNull()) - return Parent->OrderedRegion.hasValue(); + return Parent->OrderedRegion.has_value(); return false; } /// Returns optional parameter for the ordered region. std::pair<const Expr *, OMPOrderedClause *> getParentOrderedRegionParam() const { if (const SharingMapTy *Parent = getSecondOnStackOrNull()) - if (Parent->OrderedRegion.hasValue()) - return Parent->OrderedRegion.getValue(); + if (Parent->OrderedRegion) + return *Parent->OrderedRegion; return std::make_pair(nullptr, nullptr); } /// Marks current region as nowait (it has a 'nowait' clause). @@ -7653,9 +7653,9 @@ public: /// Return true if any expression is dependent. bool dependent() const; /// Returns true if the initializer forms non-rectangular loop. - bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } + bool doesInitDependOnLC() const { return InitDependOnLC.has_value(); } /// Returns true if the condition forms non-rectangular loop. - bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } + bool doesCondDependOnLC() const { return CondDependOnLC.has_value(); } /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. unsigned getLoopDependentIdx() const { return InitDependOnLC.value_or(CondDependOnLC.value_or(0)); @@ -7761,21 +7761,20 @@ bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { bool IsConstZero = Result && !Result->getBoolValue(); // != with increment is treated as <; != with decrement is treated as > - if (!TestIsLessOp.hasValue()) + if (!TestIsLessOp) TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); - if (UB && - (IsConstZero || (TestIsLessOp.getValue() - ? (IsConstNeg || (IsUnsigned && Subtract)) - : (IsConstPos || (IsUnsigned && !Subtract))))) { + if (UB && (IsConstZero || + (*TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) + : (IsConstPos || (IsUnsigned && !Subtract))))) { SemaRef.Diag(NewStep->getExprLoc(), diag::err_omp_loop_incr_not_compatible) - << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); + << LCDecl << *TestIsLessOp << NewStep->getSourceRange(); SemaRef.Diag(ConditionLoc, diag::note_omp_loop_cond_requres_compatible_incr) - << TestIsLessOp.getValue() << ConditionSrcRange; + << *TestIsLessOp << ConditionSrcRange; return true; } - if (TestIsLessOp.getValue() == Subtract) { + if (*TestIsLessOp == Subtract) { NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) .get(); @@ -8530,8 +8529,8 @@ Expr *OpenMPIterationSpaceChecker::buildNumIterations( UBVal = MinUB.get(); } } - Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; - Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; + Expr *UBExpr = *TestIsLessOp ? UBVal : LBVal; + Expr *LBExpr = *TestIsLessOp ? LBVal : UBVal; Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); if (!Upper || !Lower) @@ -8594,12 +8593,12 @@ std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( // init value. Expr *MinExpr = nullptr; Expr *MaxExpr = nullptr; - Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; - Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; - bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() - : CondDependOnLC.hasValue(); - bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() - : InitDependOnLC.hasValue(); + Expr *LBExpr = *TestIsLessOp ? LB : UB; + Expr *UBExpr = *TestIsLessOp ? UB : LB; + bool LBNonRect = + *TestIsLessOp ? InitDependOnLC.has_value() : CondDependOnLC.has_value(); + bool UBNonRect = + *TestIsLessOp ? CondDependOnLC.has_value() : InitDependOnLC.has_value(); Expr *Lower = LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); Expr *Upper = @@ -8721,11 +8720,11 @@ Expr *OpenMPIterationSpaceChecker::buildPreCond( if (!NewLB.isUsable() || !NewUB.isUsable()) return nullptr; - ExprResult CondExpr = SemaRef.BuildBinOp( - S, DefaultLoc, - TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE) - : (TestIsStrictOp ? BO_GT : BO_GE), - NewLB.get(), NewUB.get()); + ExprResult CondExpr = + SemaRef.BuildBinOp(S, DefaultLoc, + *TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) + : (TestIsStrictOp ? BO_GT : BO_GE), + NewLB.get(), NewUB.get()); if (CondExpr.isUsable()) { if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), SemaRef.Context.BoolTy)) @@ -8800,12 +8799,10 @@ Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( !SemaRef.getLangOpts().CPlusPlus) return nullptr; // Upper - Lower - Expr *Upper = TestIsLessOp.getValue() - ? Cnt - : tryBuildCapture(SemaRef, LB, Captures).get(); - Expr *Lower = TestIsLessOp.getValue() - ? tryBuildCapture(SemaRef, LB, Captures).get() - : Cnt; + Expr *Upper = + *TestIsLessOp ? Cnt : tryBuildCapture(SemaRef, LB, Captures).get(); + Expr *Lower = + *TestIsLessOp ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt; if (!Upper || !Lower) return nullptr; @@ -22180,27 +22177,27 @@ void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, auto *VD = cast<ValueDecl>(ND); llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = OMPDeclareTargetDeclAttr::getActiveAttr(VD); - if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT && - ActiveAttr.getValue()->getLevel() == Level) { + if (ActiveAttr && (*ActiveAttr)->getDevType() != DTCI.DT && + (*ActiveAttr)->getLevel() == Level) { Diag(Loc, diag::err_omp_device_type_mismatch) << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT) << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr( - ActiveAttr.getValue()->getDevType()); + ActiveAttr.value()->getDevType()); return; } - if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT && - ActiveAttr.getValue()->getLevel() == Level) { + if (ActiveAttr && (*ActiveAttr)->getMapType() != MT && + (*ActiveAttr)->getLevel() == Level) { Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; return; } - if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level) + if (ActiveAttr && (*ActiveAttr)->getLevel() == Level) return; Expr *IndirectE = nullptr; bool IsIndirect = false; - if (DTCI.Indirect.hasValue()) { - IndirectE = DTCI.Indirect.getValue(); + if (DTCI.Indirect) { + IndirectE = *DTCI.Indirect; if (!IndirectE) IsIndirect = true; } @@ -22294,13 +22291,13 @@ void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = OMPDeclareTargetDeclAttr::getActiveAttr(VD); unsigned Level = DeclareTargetNesting.size(); - if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level) + if (ActiveAttr && (*ActiveAttr)->getLevel() >= Level) return; DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back(); Expr *IndirectE = nullptr; bool IsIndirect = false; - if (DTCI.Indirect.hasValue()) { - IndirectE = DTCI.Indirect.getValue(); + if (DTCI.Indirect) { + IndirectE = *DTCI.Indirect; if (!IndirectE) IsIndirect = true; } diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp index d755801..4352e7ec 100644 --- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp +++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp @@ -469,8 +469,8 @@ static void instantiateOMPDeclareVariantAttr( if (!DeclVarData) return; - E = DeclVarData.getValue().second; - FD = DeclVarData.getValue().first; + E = DeclVarData->second; + FD = DeclVarData->first; if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) { if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) { diff --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp index 1787909..f58f166 100644 --- a/clang/lib/Serialization/ASTWriter.cpp +++ b/clang/lib/Serialization/ASTWriter.cpp @@ -1888,8 +1888,8 @@ void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) { // without this file existing on disk. if (!U.Size || (!U.ModTime && IncludeTimestamps)) { PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header) - << WritingModule->getFullModuleName() << U.Size.hasValue() - << U.FileName; + << WritingModule->getFullModuleName() << U.Size.has_value() + << U.FileName; continue; } diff --git a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp index 970bfd2..16e0b8a 100644 --- a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp @@ -766,10 +766,10 @@ void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg, continue; // Generate only one error node to use for all bug reports. - if (!errorNode.hasValue()) + if (!errorNode) errorNode = C.generateNonFatalErrorNode(); - if (!errorNode.getValue()) + if (!*errorNode) continue; SmallString<128> sbuf; @@ -786,8 +786,8 @@ void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg, ArgTy.print(os, C.getLangOpts()); os << "'"; - auto R = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), - errorNode.getValue()); + auto R = + std::make_unique<PathSensitiveBugReport>(*BT, os.str(), *errorNode); R->addRange(msg.getArgSourceRange(I)); C.emitReport(std::move(R)); } diff --git a/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp index 0e27377..dbfdff4 100644 --- a/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp @@ -272,12 +272,12 @@ ProgramStateRef GTestChecker::assumeValuesEqual(SVal Val1, SVal Val2, CheckerContext &C) { auto DVal1 = Val1.getAs<DefinedOrUnknownSVal>(); auto DVal2 = Val2.getAs<DefinedOrUnknownSVal>(); - if (!DVal1.hasValue() || !DVal2.hasValue()) + if (!DVal1 || !DVal2) return State; auto ValuesEqual = C.getSValBuilder().evalEQ(State, *DVal1, *DVal2).getAs<DefinedSVal>(); - if (!ValuesEqual.hasValue()) + if (!ValuesEqual) return State; State = C.getConstraintManager().assume(State, *ValuesEqual, true); diff --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp index 552d042..2aeb32d 100644 --- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -1190,8 +1190,8 @@ MallocChecker::performKernelMalloc(const CallEvent &Call, CheckerContext &C, NonLoc Flags = V.castAs<NonLoc>(); NonLoc ZeroFlag = C.getSValBuilder() - .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType()) - .castAs<NonLoc>(); + .makeIntVal(*KernelZeroFlagVal, FlagsEx->getType()) + .castAs<NonLoc>(); SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And, Flags, ZeroFlag, FlagsEx->getType()); @@ -1238,8 +1238,8 @@ void MallocChecker::checkKernelMalloc(const CallEvent &Call, ProgramStateRef State = C.getState(); llvm::Optional<ProgramStateRef> MaybeState = performKernelMalloc(Call, C, State); - if (MaybeState.hasValue()) - State = MaybeState.getValue(); + if (MaybeState) + State = *MaybeState; else State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State, AF_Malloc); @@ -3571,13 +3571,13 @@ void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State, const RefState *RefS = State->get<RegionState>(I.getKey()); AllocationFamily Family = RefS->getAllocationFamily(); Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); - if (!CheckKind.hasValue()) - CheckKind = getCheckIfTracked(Family, true); + if (!CheckKind) + CheckKind = getCheckIfTracked(Family, true); I.getKey()->dumpToStream(Out); Out << " : "; I.getData().dump(Out); - if (CheckKind.hasValue()) + if (CheckKind) Out << " (" << CheckNames[*CheckKind].getName() << ")"; Out << NL; } diff --git a/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp index 3481936..fd47e19 100644 --- a/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp @@ -136,10 +136,10 @@ void NonNullParamChecker::checkPreCall(const CallEvent &Call, if (!DV) continue; - assert(!HasRefTypeParam || isa<Loc>(DV.getValue())); + assert(!HasRefTypeParam || isa<Loc>(*DV)); // Process the case when the argument is not a location. - if (ExpectedToBeNonNull && !isa<Loc>(DV.getValue())) { + if (ExpectedToBeNonNull && !isa<Loc>(*DV)) { // If the argument is a union type, we want to handle a potential // transparent_union GCC extension. if (!ArgE) diff --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp index 9da44d5..19b63a1 100644 --- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp @@ -234,7 +234,8 @@ void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C, } NonLoc oflags = V.castAs<NonLoc>(); NonLoc ocreateFlag = C.getSValBuilder() - .makeIntVal(Val_O_CREAT.getValue(), oflagsEx->getType()).castAs<NonLoc>(); + .makeIntVal(*Val_O_CREAT, oflagsEx->getType()) + .castAs<NonLoc>(); SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And, oflags, ocreateFlag, oflagsEx->getType()); diff --git a/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp b/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp index de94cb7..3b01ec6 100644 --- a/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ b/clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -77,8 +77,8 @@ AnalyzerOptions::getExplorationStrategy() const { .Case("bfs_block_dfs_contents", ExplorationStrategyKind::BFSBlockDFSContents) .Default(None); - assert(K.hasValue() && "User mode is invalid."); - return K.getValue(); + assert(K && "User mode is invalid."); + return *K; } CTUPhase1InliningKind AnalyzerOptions::getCTUPhase1Inlining() const { @@ -88,8 +88,8 @@ CTUPhase1InliningKind AnalyzerOptions::getCTUPhase1Inlining() const { .Case("small", CTUPhase1InliningKind::Small) .Case("all", CTUPhase1InliningKind::All) .Default(None); - assert(K.hasValue() && "CTU inlining mode is invalid."); - return K.getValue(); + assert(K && "CTU inlining mode is invalid."); + return *K; } IPAKind AnalyzerOptions::getIPAMode() const { @@ -100,9 +100,9 @@ IPAKind AnalyzerOptions::getIPAMode() const { .Case("dynamic", IPAK_DynamicDispatch) .Case("dynamic-bifurcate", IPAK_DynamicDispatchBifurcate) .Default(None); - assert(K.hasValue() && "IPA Mode is invalid."); + assert(K && "IPA Mode is invalid."); - return K.getValue(); + return *K; } bool diff --git a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp index a2efe14..4d6b82e 100644 --- a/clang/lib/StaticAnalyzer/Core/BugReporter.cpp +++ b/clang/lib/StaticAnalyzer/Core/BugReporter.cpp @@ -2363,15 +2363,15 @@ PathSensitiveBugReport::getInterestingnessKind(const MemRegion *R) const { } bool PathSensitiveBugReport::isInteresting(SVal V) const { - return getInterestingnessKind(V).hasValue(); + return getInterestingnessKind(V).has_value(); } bool PathSensitiveBugReport::isInteresting(SymbolRef sym) const { - return getInterestingnessKind(sym).hasValue(); + return getInterestingnessKind(sym).has_value(); } bool PathSensitiveBugReport::isInteresting(const MemRegion *R) const { - return getInterestingnessKind(R).hasValue(); + return getInterestingnessKind(R).has_value(); } bool PathSensitiveBugReport::isInteresting(const LocationContext *LC) const { diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp index 339a675..9d89069 100644 --- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp +++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp @@ -2949,8 +2949,8 @@ PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest( PathDiagnosticLocation Loc(Cond, SM, LCtx); auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message); - if (shouldPrune.hasValue()) - event->setPrunable(shouldPrune.getValue()); + if (shouldPrune) + event->setPrunable(*shouldPrune); return event; } @@ -3084,9 +3084,9 @@ bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out, Out << (TookTrue ? "not equal to 0" : "0"); } else { if (Ty->isBooleanType()) - Out << (IntValue.getValue()->getBoolValue() ? "true" : "false"); + Out << (IntValue.value()->getBoolValue() ? "true" : "false"); else - Out << *IntValue.getValue(); + Out << *IntValue.value(); } return true; @@ -3279,10 +3279,10 @@ void FalsePositiveRefutationBRVisitor::finalizeVisitor( // And check for satisfiability Optional<bool> IsSAT = RefutationSolver->check(); - if (!IsSAT.hasValue()) + if (!IsSAT) return; - if (!IsSAT.getValue()) + if (!*IsSAT) BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext()); } diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp index 326a3b1..b03af13 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp @@ -1015,8 +1015,8 @@ bool ExprEngine::shouldInlineCall(const CallEvent &Call, const Decl *D, // Check if this function has been marked as non-inlinable. Optional<bool> MayInline = Engine.FunctionSummaries->mayInline(D); - if (MayInline.hasValue()) { - if (!MayInline.getValue()) + if (MayInline) { + if (!*MayInline) return false; } else { diff --git a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp index 93c19a6..56f441e 100644 --- a/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp +++ b/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp @@ -407,11 +407,11 @@ void PlistPrinter::ReportMacroExpansions(raw_ostream &o, unsigned indent) { // Output the macro name. Indent(o, indent) << "<key>name</key>"; - EmitString(o, MacroName.getValue()) << '\n'; + EmitString(o, *MacroName) << '\n'; // Output what it expands into. Indent(o, indent) << "<key>expansion</key>"; - EmitString(o, ExpansionText.getValue()) << '\n'; + EmitString(o, *ExpansionText) << '\n'; // Finish up. --indent; diff --git a/clang/lib/Support/RISCVVIntrinsicUtils.cpp b/clang/lib/Support/RISCVVIntrinsicUtils.cpp index ebfe1a1..3f7c131 100644 --- a/clang/lib/Support/RISCVVIntrinsicUtils.cpp +++ b/clang/lib/Support/RISCVVIntrinsicUtils.cpp @@ -114,11 +114,11 @@ bool RVVType::verifyType() const { return false; if (isScalar()) return true; - if (!Scale.hasValue()) + if (!Scale) return false; if (isFloat() && ElementBitwidth == 8) return false; - unsigned V = Scale.getValue(); + unsigned V = *Scale; switch (ElementBitwidth) { case 1: case 8: @@ -799,10 +799,10 @@ RVVType::computeTypes(BasicType BT, int Log2LMUL, unsigned NF, RVVTypes Types; for (const PrototypeDescriptor &Proto : Prototype) { auto T = computeType(BT, Log2LMUL, Proto); - if (!T.hasValue()) + if (!T) return llvm::None; // Record legal type index - Types.push_back(T.getValue()); + Types.push_back(*T); } return Types; } diff --git a/clang/lib/Tooling/Core/Replacement.cpp b/clang/lib/Tooling/Core/Replacement.cpp index 30e1923..aca2afce 100644 --- a/clang/lib/Tooling/Core/Replacement.cpp +++ b/clang/lib/Tooling/Core/Replacement.cpp @@ -179,9 +179,9 @@ static std::string getReplacementErrString(replacement_error Err) { std::string ReplacementError::message() const { std::string Message = getReplacementErrString(Err); - if (NewReplacement.hasValue()) + if (NewReplacement) Message += "\nNew replacement: " + NewReplacement->toString(); - if (ExistingReplacement.hasValue()) + if (ExistingReplacement) Message += "\nExisting replacement: " + ExistingReplacement->toString(); return Message; } diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp index fa1f09b..7231297 100644 --- a/clang/tools/driver/driver.cpp +++ b/clang/tools/driver/driver.cpp @@ -406,18 +406,18 @@ int clang_main(int Argc, char **Argv) { if (ClangCLMode) { // Arguments in "CL" are prepended. llvm::Optional<std::string> OptCL = llvm::sys::Process::GetEnv("CL"); - if (OptCL.hasValue()) { + if (OptCL) { SmallVector<const char *, 8> PrependedOpts; - getCLEnvVarOptions(OptCL.getValue(), Saver, PrependedOpts); + getCLEnvVarOptions(*OptCL, Saver, PrependedOpts); // Insert right after the program name to prepend to the argument list. Args.insert(Args.begin() + 1, PrependedOpts.begin(), PrependedOpts.end()); } // Arguments in "_CL_" are appended. llvm::Optional<std::string> Opt_CL_ = llvm::sys::Process::GetEnv("_CL_"); - if (Opt_CL_.hasValue()) { + if (Opt_CL_) { SmallVector<const char *, 8> AppendedOpts; - getCLEnvVarOptions(Opt_CL_.getValue(), Saver, AppendedOpts); + getCLEnvVarOptions(*Opt_CL_, Saver, AppendedOpts); // Insert at the end of the argument list to append. Args.append(AppendedOpts.begin(), AppendedOpts.end()); diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp index cba265b..8d6c16e 100644 --- a/clang/tools/libclang/CIndex.cpp +++ b/clang/tools/libclang/CIndex.cpp @@ -536,9 +536,9 @@ bool CursorVisitor::VisitChildren(CXCursor Cursor) { TLEnd = CXXUnit->top_level_end(); TL != TLEnd; ++TL) { const Optional<bool> V = handleDeclForVisitation(*TL); - if (!V.hasValue()) + if (!V) continue; - return V.getValue(); + return *V; } } else if (VisitDeclContext( CXXUnit->getASTContext().getTranslationUnitDecl())) @@ -641,9 +641,9 @@ bool CursorVisitor::VisitDeclContext(DeclContext *DC) { if (OMD->isSynthesizedAccessorStub()) continue; const Optional<bool> V = handleDeclForVisitation(D); - if (!V.hasValue()) + if (!V) continue; - return V.getValue(); + return *V; } return false; } @@ -675,9 +675,9 @@ Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) { } const Optional<bool> V = shouldVisitCursor(Cursor); - if (!V.hasValue()) + if (!V) return None; - if (!V.getValue()) + if (!*V) return false; if (Visit(Cursor, true)) return true; @@ -1074,9 +1074,9 @@ bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { I != E; ++I) { CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); const Optional<bool> &V = shouldVisitCursor(Cursor); - if (!V.hasValue()) + if (!V) continue; - if (!V.getValue()) + if (!*V) return false; if (Visit(Cursor, true)) return true; @@ -8178,13 +8178,13 @@ static CXVersion convertVersion(VersionTuple In) { Out.Major = In.getMajor(); Optional<unsigned> Minor = In.getMinor(); - if (Minor.hasValue()) + if (Minor) Out.Minor = *Minor; else return Out; Optional<unsigned> Subminor = In.getSubminor(); - if (Subminor.hasValue()) + if (Subminor) Out.Subminor = *Subminor; return Out; diff --git a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp index eaba6b7..312b9af 100644 --- a/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp +++ b/clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp @@ -449,27 +449,27 @@ TEST(ParserTest, ParseMultiline) { ) )matcher"; Diagnostics Error; - EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue()); + EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error)); } { Code = R"matcher(decl(decl() , decl()))matcher"; Diagnostics Error; - EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue()); + EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).has_value()); } { Code = R"matcher(decl(decl(), decl()))matcher"; Diagnostics Error; - EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue()); + EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).has_value()); } { Code = "namedDecl(hasName(\"n\"\n))"; Diagnostics Error; - EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).hasValue()); + EXPECT_TRUE(Parser::parseMatcherExpression(Code, &Error).has_value()); } { diff --git a/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp b/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp index 4c5efa7..7c50453 100644 --- a/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp +++ b/clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp @@ -40,9 +40,8 @@ isAnnotationDirectlyAfterStatement(const Stmt *Stmt, unsigned AnnotationBegin, auto NextToken = Lexer::findNextToken(Stmt->getEndLoc(), SourceManager, LangOptions); - while (NextToken.hasValue() && - SourceManager.getFileOffset(NextToken->getLocation()) < - AnnotationBegin) { + while (NextToken && SourceManager.getFileOffset(NextToken->getLocation()) < + AnnotationBegin) { if (NextToken->isNot(tok::semi)) return false; diff --git a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp index 594764b..27b7671 100644 --- a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp @@ -82,8 +82,8 @@ TEST(DataflowAnalysisTest, NoopAnalysis) { return NoopAnalysis(C, false); })); EXPECT_EQ(BlockStates.size(), 2u); - EXPECT_TRUE(BlockStates[0].hasValue()); - EXPECT_TRUE(BlockStates[1].hasValue()); + EXPECT_TRUE(BlockStates[0].has_value()); + EXPECT_TRUE(BlockStates[1].has_value()); } struct NonConvergingLattice { diff --git a/clang/unittests/Analysis/MacroExpansionContextTest.cpp b/clang/unittests/Analysis/MacroExpansionContextTest.cpp index 7cee64c..8864230 100644 --- a/clang/unittests/Analysis/MacroExpansionContextTest.cpp +++ b/clang/unittests/Analysis/MacroExpansionContextTest.cpp @@ -121,14 +121,14 @@ TEST_F(MacroExpansionContextTest, IgnoresPragmas) { EXPECT_EQ("\n=============== ExpansionRanges ===============\n", dumpExpansionRanges(*Ctx)); - EXPECT_FALSE(Ctx->getExpandedText(at(2, 1)).hasValue()); - EXPECT_FALSE(Ctx->getOriginalText(at(2, 1)).hasValue()); + EXPECT_FALSE(Ctx->getExpandedText(at(2, 1)).has_value()); + EXPECT_FALSE(Ctx->getOriginalText(at(2, 1)).has_value()); - EXPECT_FALSE(Ctx->getExpandedText(at(2, 3)).hasValue()); - EXPECT_FALSE(Ctx->getOriginalText(at(2, 3)).hasValue()); + EXPECT_FALSE(Ctx->getExpandedText(at(2, 3)).has_value()); + EXPECT_FALSE(Ctx->getOriginalText(at(2, 3)).has_value()); - EXPECT_FALSE(Ctx->getExpandedText(at(3, 3)).hasValue()); - EXPECT_FALSE(Ctx->getOriginalText(at(3, 3)).hasValue()); + EXPECT_FALSE(Ctx->getExpandedText(at(3, 3)).has_value()); + EXPECT_FALSE(Ctx->getOriginalText(at(3, 3)).has_value()); } TEST_F(MacroExpansionContextTest, NoneForNonExpansionLocations) { @@ -142,33 +142,33 @@ EMPTY zz // zz // That's the beginning of the definition of EMPTY. - EXPECT_FALSE(Ctx->getExpandedText(at(2, 11)).hasValue()); - EXPECT_FALSE(Ctx->getOriginalText(at(2, 11)).hasValue()); + EXPECT_FALSE(Ctx->getExpandedText(at(2, 11)).has_value()); + EXPECT_FALSE(Ctx->getOriginalText(at(2, 11)).has_value()); // The space before the first expansion of EMPTY. - EXPECT_FALSE(Ctx->getExpandedText(at(3, 9)).hasValue()); - EXPECT_FALSE(Ctx->getOriginalText(at(3, 9)).hasValue()); + EXPECT_FALSE(Ctx->getExpandedText(at(3, 9)).has_value()); + EXPECT_FALSE(Ctx->getOriginalText(at(3, 9)).has_value()); // The beginning of the first expansion of EMPTY. - EXPECT_TRUE(Ctx->getExpandedText(at(3, 10)).hasValue()); - EXPECT_TRUE(Ctx->getOriginalText(at(3, 10)).hasValue()); + EXPECT_TRUE(Ctx->getExpandedText(at(3, 10)).has_value()); + EXPECT_TRUE(Ctx->getOriginalText(at(3, 10)).has_value()); // Pointing inside of the token EMPTY, but not at the beginning. // FIXME: We only deal with begin locations. - EXPECT_FALSE(Ctx->getExpandedText(at(3, 11)).hasValue()); - EXPECT_FALSE(Ctx->getOriginalText(at(3, 11)).hasValue()); + EXPECT_FALSE(Ctx->getExpandedText(at(3, 11)).has_value()); + EXPECT_FALSE(Ctx->getOriginalText(at(3, 11)).has_value()); // Same here. - EXPECT_FALSE(Ctx->getExpandedText(at(3, 12)).hasValue()); - EXPECT_FALSE(Ctx->getOriginalText(at(3, 12)).hasValue()); + EXPECT_FALSE(Ctx->getExpandedText(at(3, 12)).has_value()); + EXPECT_FALSE(Ctx->getOriginalText(at(3, 12)).has_value()); // The beginning of the last expansion of EMPTY. - EXPECT_TRUE(Ctx->getExpandedText(at(4, 1)).hasValue()); - EXPECT_TRUE(Ctx->getOriginalText(at(4, 1)).hasValue()); + EXPECT_TRUE(Ctx->getExpandedText(at(4, 1)).has_value()); + EXPECT_TRUE(Ctx->getOriginalText(at(4, 1)).has_value()); // Same as for the 3:11 case. - EXPECT_FALSE(Ctx->getExpandedText(at(4, 2)).hasValue()); - EXPECT_FALSE(Ctx->getOriginalText(at(4, 2)).hasValue()); + EXPECT_FALSE(Ctx->getExpandedText(at(4, 2)).has_value()); + EXPECT_FALSE(Ctx->getOriginalText(at(4, 2)).has_value()); } TEST_F(MacroExpansionContextTest, EmptyExpansions) { @@ -181,14 +181,14 @@ EMPTY zz // A b cd ef gh // zz - EXPECT_EQ("", Ctx->getExpandedText(at(3, 10)).getValue()); - EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(3, 10)).getValue()); + EXPECT_EQ("", *Ctx->getExpandedText(at(3, 10))); + EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(3, 10))); - EXPECT_EQ("", Ctx->getExpandedText(at(3, 19)).getValue()); - EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(3, 19)).getValue()); + EXPECT_EQ("", *Ctx->getExpandedText(at(3, 19))); + EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(3, 19))); - EXPECT_EQ("", Ctx->getExpandedText(at(4, 1)).getValue()); - EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 1)).getValue()); + EXPECT_EQ("", *Ctx->getExpandedText(at(4, 1))); + EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(4, 1))); } TEST_F(MacroExpansionContextTest, TransitiveExpansions) { @@ -200,10 +200,10 @@ TEST_F(MacroExpansionContextTest, TransitiveExpansions) { // After preprocessing: // A b cd ) 1 ef gh - EXPECT_EQ("WOOF", Ctx->getOriginalText(at(4, 10)).getValue()); + EXPECT_EQ("WOOF", *Ctx->getOriginalText(at(4, 10))); - EXPECT_EQ("", Ctx->getExpandedText(at(4, 18)).getValue()); - EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 18)).getValue()); + EXPECT_EQ("", *Ctx->getExpandedText(at(4, 18))); + EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(4, 18))); } TEST_F(MacroExpansionContextTest, MacroFunctions) { @@ -219,17 +219,17 @@ TEST_F(MacroExpansionContextTest, MacroFunctions) { // WOOF( ) ) ) 1 // bar barr( ) ) ) 1( ) ) ) 1),,),') - EXPECT_EQ("$$ ef ()))1", Ctx->getExpandedText(at(4, 10)).getValue()); - EXPECT_EQ("WOOF($$ ef)", Ctx->getOriginalText(at(4, 10)).getValue()); + EXPECT_EQ("$$ ef ()))1", *Ctx->getExpandedText(at(4, 10))); + EXPECT_EQ("WOOF($$ ef)", *Ctx->getOriginalText(at(4, 10))); - EXPECT_EQ("", Ctx->getExpandedText(at(4, 22)).getValue()); - EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 22)).getValue()); + EXPECT_EQ("", Ctx->getExpandedText(at(4, 22)).value()); + EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 22)).value()); - EXPECT_EQ("WOOF ()))1", Ctx->getExpandedText(at(5, 3)).getValue()); - EXPECT_EQ("WOOF(WOOF)", Ctx->getOriginalText(at(5, 3)).getValue()); + EXPECT_EQ("WOOF ()))1", Ctx->getExpandedText(at(5, 3)).value()); + EXPECT_EQ("WOOF(WOOF)", Ctx->getOriginalText(at(5, 3)).value()); - EXPECT_EQ("bar barr ()))1()))1", Ctx->getExpandedText(at(6, 3)).getValue()); - EXPECT_EQ("WOOF(WOOF(bar barr))", Ctx->getOriginalText(at(6, 3)).getValue()); + EXPECT_EQ("bar barr ()))1()))1", Ctx->getExpandedText(at(6, 3)).value()); + EXPECT_EQ("WOOF(WOOF(bar barr))", Ctx->getOriginalText(at(6, 3)).value()); } TEST_F(MacroExpansionContextTest, VariadicMacros) { @@ -251,24 +251,23 @@ TEST_F(MacroExpansionContextTest, VariadicMacros) { // fprintf (stderr, "success!\n" ); EXPECT_EQ(R"(fprintf (stderr ,"success!\n",))", - Ctx->getExpandedText(at(3, 3)).getValue()); + Ctx->getExpandedText(at(3, 3)).value()); EXPECT_EQ(R"(eprintf("success!\n", ))", - Ctx->getOriginalText(at(3, 3)).getValue()); + Ctx->getOriginalText(at(3, 3)).value()); EXPECT_EQ(R"(fprintf (stderr ,"success!\n",))", - Ctx->getExpandedText(at(4, 3)).getValue()); - EXPECT_EQ(R"(eprintf("success!\n"))", - Ctx->getOriginalText(at(4, 3)).getValue()); + Ctx->getExpandedText(at(4, 3)).value()); + EXPECT_EQ(R"(eprintf("success!\n"))", Ctx->getOriginalText(at(4, 3)).value()); EXPECT_EQ(R"(fprintf (stderr ,"success!\n"))", - Ctx->getExpandedText(at(8, 3)).getValue()); + Ctx->getExpandedText(at(8, 3)).value()); EXPECT_EQ(R"(eprintf2("success!\n", ))", - Ctx->getOriginalText(at(8, 3)).getValue()); + Ctx->getOriginalText(at(8, 3)).value()); EXPECT_EQ(R"(fprintf (stderr ,"success!\n"))", - Ctx->getExpandedText(at(9, 3)).getValue()); + Ctx->getExpandedText(at(9, 3)).value()); EXPECT_EQ(R"(eprintf2("success!\n"))", - Ctx->getOriginalText(at(9, 3)).getValue()); + Ctx->getOriginalText(at(9, 3)).value()); } TEST_F(MacroExpansionContextTest, ConcatenationMacros) { @@ -286,12 +285,12 @@ TEST_F(MacroExpansionContextTest, ConcatenationMacros) { // }; EXPECT_EQ(R"({"quit",quit_command })", - Ctx->getExpandedText(at(4, 5)).getValue()); - EXPECT_EQ("COMMAND(quit)", Ctx->getOriginalText(at(4, 5)).getValue()); + Ctx->getExpandedText(at(4, 5)).value()); + EXPECT_EQ("COMMAND(quit)", Ctx->getOriginalText(at(4, 5)).value()); EXPECT_EQ(R"({"help",help_command })", - Ctx->getExpandedText(at(5, 5)).getValue()); - EXPECT_EQ("COMMAND(help)", Ctx->getOriginalText(at(5, 5)).getValue()); + Ctx->getExpandedText(at(5, 5)).value()); + EXPECT_EQ("COMMAND(help)", Ctx->getOriginalText(at(5, 5)).value()); } TEST_F(MacroExpansionContextTest, StringizingMacros) { @@ -316,14 +315,14 @@ TEST_F(MacroExpansionContextTest, StringizingMacros) { EXPECT_EQ( R"(do {if (x ==0)fprintf (stderr ,"Warning: ""x == 0""\n");}while (0))", - Ctx->getExpandedText(at(6, 3)).getValue()); - EXPECT_EQ("WARN_IF (x == 0)", Ctx->getOriginalText(at(6, 3)).getValue()); + Ctx->getExpandedText(at(6, 3)).value()); + EXPECT_EQ("WARN_IF (x == 0)", Ctx->getOriginalText(at(6, 3)).value()); - EXPECT_EQ(R"("foo")", Ctx->getExpandedText(at(11, 3)).getValue()); - EXPECT_EQ("str (foo)", Ctx->getOriginalText(at(11, 3)).getValue()); + EXPECT_EQ(R"("foo")", Ctx->getExpandedText(at(11, 3)).value()); + EXPECT_EQ("str (foo)", Ctx->getOriginalText(at(11, 3)).value()); - EXPECT_EQ(R"("4")", Ctx->getExpandedText(at(12, 3)).getValue()); - EXPECT_EQ("xstr (foo)", Ctx->getOriginalText(at(12, 3)).getValue()); + EXPECT_EQ(R"("4")", Ctx->getExpandedText(at(12, 3)).value()); + EXPECT_EQ("xstr (foo)", Ctx->getOriginalText(at(12, 3)).value()); } TEST_F(MacroExpansionContextTest, StringizingVariadicMacros) { @@ -352,18 +351,18 @@ TEST_F(MacroExpansionContextTest, StringizingVariadicMacros) { EXPECT_EQ("zz !apple !x *apple !x !**y (apple )zz !apple !x *apple !x !**y " "(appleapple ))))", - Ctx->getExpandedText(at(11, 3)).getValue()); - EXPECT_EQ("q(g)", Ctx->getOriginalText(at(11, 3)).getValue()); + Ctx->getExpandedText(at(11, 3)).value()); + EXPECT_EQ("q(g)", Ctx->getOriginalText(at(11, 3)).value()); EXPECT_EQ(R"res("apple"(apple )"apple"(appleapple )))))res", - Ctx->getExpandedText(at(12, 3)).getValue()); - EXPECT_EQ("q(xstr)", Ctx->getOriginalText(at(12, 3)).getValue()); + Ctx->getExpandedText(at(12, 3)).value()); + EXPECT_EQ("q(xstr)", Ctx->getOriginalText(at(12, 3)).value()); - EXPECT_EQ("zz !*)!x )!**y ", Ctx->getExpandedText(at(13, 3)).getValue()); - EXPECT_EQ("g(RParen2x)", Ctx->getOriginalText(at(13, 3)).getValue()); + EXPECT_EQ("zz !*)!x )!**y ", Ctx->getExpandedText(at(13, 3)).value()); + EXPECT_EQ("g(RParen2x)", Ctx->getOriginalText(at(13, 3)).value()); - EXPECT_EQ("!))*))", Ctx->getExpandedText(at(14, 3)).getValue()); - EXPECT_EQ("f( RParen2x )", Ctx->getOriginalText(at(14, 3)).getValue()); + EXPECT_EQ("!))*))", Ctx->getExpandedText(at(14, 3)).value()); + EXPECT_EQ("f( RParen2x )", Ctx->getOriginalText(at(14, 3)).value()); } TEST_F(MacroExpansionContextTest, RedefUndef) { @@ -381,15 +380,15 @@ TEST_F(MacroExpansionContextTest, RedefUndef) { // Hi(Hi) // FIXME: Extra space follows every identifier. - EXPECT_EQ("Welcome Adam ", Ctx->getExpandedText(at(3, 3)).getValue()); - EXPECT_EQ("Hi(Adam)", Ctx->getOriginalText(at(3, 3)).getValue()); + EXPECT_EQ("Welcome Adam ", Ctx->getExpandedText(at(3, 3)).value()); + EXPECT_EQ("Hi(Adam)", Ctx->getOriginalText(at(3, 3)).value()); - EXPECT_EQ("Willkommen ", Ctx->getExpandedText(at(5, 3)).getValue()); - EXPECT_EQ("Hi", Ctx->getOriginalText(at(5, 3)).getValue()); + EXPECT_EQ("Willkommen ", Ctx->getExpandedText(at(5, 3)).value()); + EXPECT_EQ("Hi", Ctx->getOriginalText(at(5, 3)).value()); // There was no macro expansion at 7:3, we should expect None. - EXPECT_FALSE(Ctx->getExpandedText(at(7, 3)).hasValue()); - EXPECT_FALSE(Ctx->getOriginalText(at(7, 3)).hasValue()); + EXPECT_FALSE(Ctx->getExpandedText(at(7, 3)).has_value()); + EXPECT_FALSE(Ctx->getOriginalText(at(7, 3)).has_value()); } TEST_F(MacroExpansionContextTest, UnbalacedParenthesis) { @@ -411,12 +410,11 @@ TEST_F(MacroExpansionContextTest, UnbalacedParenthesis) { // fun(); // int x = ((1, fun(), 1, fun(), 1 )); - EXPECT_EQ("fun ()", Ctx->getExpandedText(at(8, 3)).getValue()); - EXPECT_EQ("applyInt )", Ctx->getOriginalText(at(8, 3)).getValue()); + EXPECT_EQ("fun ()", Ctx->getExpandedText(at(8, 3)).value()); + EXPECT_EQ("applyInt )", Ctx->getOriginalText(at(8, 3)).value()); - EXPECT_EQ("((1,fun (),1,fun (),1", - Ctx->getExpandedText(at(13, 12)).getValue()); - EXPECT_EQ("f(f(1))", Ctx->getOriginalText(at(13, 12)).getValue()); + EXPECT_EQ("((1,fun (),1,fun (),1", Ctx->getExpandedText(at(13, 12)).value()); + EXPECT_EQ("f(f(1))", Ctx->getOriginalText(at(13, 12)).value()); } } // namespace diff --git a/clang/unittests/Basic/DarwinSDKInfoTest.cpp b/clang/unittests/Basic/DarwinSDKInfoTest.cpp index 8d720c2..d56e13d 100644 --- a/clang/unittests/Basic/DarwinSDKInfoTest.cpp +++ b/clang/unittests/Basic/DarwinSDKInfoTest.cpp @@ -64,14 +64,14 @@ TEST(DarwinSDKInfo, VersionMappingParseEmpty) { llvm::json::Object Obj({}); EXPECT_FALSE( DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, VersionTuple()) - .hasValue()); + .has_value()); } TEST(DarwinSDKInfo, VersionMappingParseError) { llvm::json::Object Obj({{"test", "1.2"}}); EXPECT_FALSE( DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, VersionTuple()) - .hasValue()); + .has_value()); } TEST(DarwinSDKInfoTest, ParseAndTestMappingMacCatalyst) { diff --git a/clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp b/clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp index 5b76480..d9c1245 100644 --- a/clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp +++ b/clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp @@ -258,12 +258,12 @@ void checkEventualResultWithTimeout(VerifyingConsumer &TestConsumer) { std::future_status::ready) << "The expected result state wasn't reached before the time-out."; std::unique_lock<std::mutex> L(TestConsumer.Mtx); - EXPECT_TRUE(TestConsumer.result().hasValue()); - if (TestConsumer.result().hasValue()) { + EXPECT_TRUE(TestConsumer.result().has_value()); + if (TestConsumer.result()) { EXPECT_TRUE(*TestConsumer.result()); } - if ((TestConsumer.result().hasValue() && !TestConsumer.result().getValue()) || - !TestConsumer.result().hasValue()) + if ((TestConsumer.result() && !*TestConsumer.result()) || + !TestConsumer.result()) TestConsumer.printUnmetExpectations(llvm::outs()); } } // namespace diff --git a/clang/unittests/Lex/HeaderSearchTest.cpp b/clang/unittests/Lex/HeaderSearchTest.cpp index 87d1c01..bd9d31d 100644 --- a/clang/unittests/Lex/HeaderSearchTest.cpp +++ b/clang/unittests/Lex/HeaderSearchTest.cpp @@ -200,9 +200,9 @@ TEST_F(HeaderSearchTest, HeaderFrameworkLookup) { /*RelativePath=*/nullptr, /*RequestingModule=*/nullptr, /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr, &IsFrameworkFound); - EXPECT_TRUE(FoundFile.hasValue()); + EXPECT_TRUE(FoundFile.has_value()); EXPECT_TRUE(IsFrameworkFound); - auto &FE = FoundFile.getValue(); + auto &FE = *FoundFile; auto FI = Search.getExistingFileInfo(FE); EXPECT_TRUE(FI); EXPECT_TRUE(FI->IsValid); @@ -269,9 +269,9 @@ TEST_F(HeaderSearchTest, HeaderMapFrameworkLookup) { /*SuggestedModule=*/nullptr, &IsMapped, /*IsFrameworkFound=*/nullptr); - EXPECT_TRUE(FoundFile.hasValue()); + EXPECT_TRUE(FoundFile.has_value()); EXPECT_TRUE(IsMapped); - auto &FE = FoundFile.getValue(); + auto &FE = *FoundFile; auto FI = Search.getExistingFileInfo(FE); EXPECT_TRUE(FI); EXPECT_TRUE(FI->IsValid); diff --git a/clang/unittests/StaticAnalyzer/SValTest.cpp b/clang/unittests/StaticAnalyzer/SValTest.cpp index 1a41faf..c41a501 100644 --- a/clang/unittests/StaticAnalyzer/SValTest.cpp +++ b/clang/unittests/StaticAnalyzer/SValTest.cpp @@ -305,13 +305,13 @@ void foo(int x) { EXPECT_EQ("TestUnion", CRecordType->getDecl()->getName()); auto D = getByName("d").getAs<nonloc::CompoundVal>(); - ASSERT_TRUE(D.hasValue()); + ASSERT_TRUE(D.has_value()); auto Begin = D->begin(); ASSERT_NE(D->end(), Begin); ++Begin; ASSERT_EQ(D->end(), Begin); auto LD = D->begin()->getAs<nonloc::LazyCompoundVal>(); - ASSERT_TRUE(LD.hasValue()); + ASSERT_TRUE(LD.has_value()); auto LDT = LD->getType(Context); ASSERT_FALSE(LDT.isNull()); const auto *DRecordType = dyn_cast<RecordType>(LDT); diff --git a/clang/unittests/Tooling/RefactoringTest.cpp b/clang/unittests/Tooling/RefactoringTest.cpp index c71a724..f0edff6 100644 --- a/clang/unittests/Tooling/RefactoringTest.cpp +++ b/clang/unittests/Tooling/RefactoringTest.cpp @@ -118,18 +118,18 @@ static bool checkReplacementError(llvm::Error &&Error, OS << "Unexpected error code: " << int(RE.get()) << "\n"; if (ExpectedExisting != RE.getExistingReplacement()) { OS << "Expected Existing != Actual Existing.\n"; - if (ExpectedExisting.hasValue()) + if (ExpectedExisting) OS << "Expected existing replacement: " << ExpectedExisting->toString() << "\n"; - if (RE.getExistingReplacement().hasValue()) + if (RE.getExistingReplacement()) OS << "Actual existing replacement: " << RE.getExistingReplacement()->toString() << "\n"; } if (ExpectedNew != RE.getNewReplacement()) { OS << "Expected New != Actual New.\n"; - if (ExpectedNew.hasValue()) + if (ExpectedNew) OS << "Expected new replacement: " << ExpectedNew->toString() << "\n"; - if (RE.getNewReplacement().hasValue()) + if (RE.getNewReplacement()) OS << "Actual new replacement: " << RE.getNewReplacement()->toString() << "\n"; } diff --git a/clang/utils/TableGen/RISCVVEmitter.cpp b/clang/utils/TableGen/RISCVVEmitter.cpp index 7987d89..f6678cc 100644 --- a/clang/utils/TableGen/RISCVVEmitter.cpp +++ b/clang/utils/TableGen/RISCVVEmitter.cpp @@ -217,22 +217,22 @@ void RVVEmitter::createHeader(raw_ostream &OS) { for (int Log2LMUL : Log2LMULs) { auto T = RVVType::computeType(BasicType::Int8, Log2LMUL, PrototypeDescriptor::Mask); - if (T.hasValue()) - printType(T.getValue()); + if (T) + printType(*T); } // Print RVV int/float types. for (char I : StringRef("csil")) { BasicType BT = ParseBasicType(I); for (int Log2LMUL : Log2LMULs) { auto T = RVVType::computeType(BT, Log2LMUL, PrototypeDescriptor::Vector); - if (T.hasValue()) { - printType(T.getValue()); + if (T) { + printType(*T); auto UT = RVVType::computeType( BT, Log2LMUL, PrototypeDescriptor(BaseTypeModifier::Vector, VectorTypeModifier::NoModifier, TypeModifier::UnsignedInteger)); - printType(UT.getValue()); + printType(*UT); } } } @@ -240,8 +240,8 @@ void RVVEmitter::createHeader(raw_ostream &OS) { for (int Log2LMUL : Log2LMULs) { auto T = RVVType::computeType(BasicType::Float16, Log2LMUL, PrototypeDescriptor::Vector); - if (T.hasValue()) - printType(T.getValue()); + if (T) + printType(*T); } OS << "#endif\n"; @@ -249,8 +249,8 @@ void RVVEmitter::createHeader(raw_ostream &OS) { for (int Log2LMUL : Log2LMULs) { auto T = RVVType::computeType(BasicType::Float32, Log2LMUL, PrototypeDescriptor::Vector); - if (T.hasValue()) - printType(T.getValue()); + if (T) + printType(*T); } OS << "#endif\n"; @@ -258,8 +258,8 @@ void RVVEmitter::createHeader(raw_ostream &OS) { for (int Log2LMUL : Log2LMULs) { auto T = RVVType::computeType(BasicType::Float64, Log2LMUL, PrototypeDescriptor::Vector); - if (T.hasValue()) - printType(T.getValue()); + if (T) + printType(*T); } OS << "#endif\n\n"; diff --git a/flang/include/flang/Lower/IterationSpace.h b/flang/include/flang/Lower/IterationSpace.h index 055882c..ed906e9 100644 --- a/flang/include/flang/Lower/IterationSpace.h +++ b/flang/include/flang/Lower/IterationSpace.h @@ -446,7 +446,9 @@ public: /// `load` must be a LHS array_load. Returns `llvm::None` on error. llvm::Optional<size_t> findArgPosition(fir::ArrayLoadOp load); - bool isLHS(fir::ArrayLoadOp load) { return findArgPosition(load).hasValue(); } + bool isLHS(fir::ArrayLoadOp load) { + return findArgPosition(load).has_value(); + } /// `load` must be a LHS array_load. Determine the threaded inner argument /// corresponding to this load. @@ -465,15 +467,15 @@ public: llvm::Optional<fir::ArrayLoadOp> getLhsLoad(size_t i) { assert(i < lhsBases.size()); - if (lhsBases[counter].hasValue()) - return findBinding(lhsBases[counter].getValue()); + if (lhsBases[counter]) + return findBinding(*lhsBases[counter]); return llvm::None; } /// Return the outermost loop in this FORALL nest. fir::DoLoopOp getOuterLoop() { - assert(outerLoop.hasValue()); - return outerLoop.getValue(); + assert(outerLoop); + return *outerLoop; } /// Return the statement context for the entire, outermost FORALL construct. diff --git a/flang/lib/Lower/Bridge.cpp b/flang/lib/Lower/Bridge.cpp index b7d180e..745a7d4 100644 --- a/flang/lib/Lower/Bridge.cpp +++ b/flang/lib/Lower/Bridge.cpp @@ -2227,10 +2227,10 @@ private: llvm_unreachable("unknown category"); } if (lhsIsWholeAllocatable) - fir::factory::finalizeRealloc( - *builder, loc, lhsMutableBox.getValue(), - /*lbounds=*/llvm::None, /*takeLboundsIfRealloc=*/false, - lhsRealloc.getValue()); + fir::factory::finalizeRealloc(*builder, loc, *lhsMutableBox, + /*lbounds=*/llvm::None, + /*takeLboundsIfRealloc=*/false, + *lhsRealloc); }, // [2] User defined assignment. If the context is a scalar diff --git a/flang/lib/Lower/ConvertExpr.cpp b/flang/lib/Lower/ConvertExpr.cpp index 07eceb7..0558a10 100644 --- a/flang/lib/Lower/ConvertExpr.cpp +++ b/flang/lib/Lower/ConvertExpr.cpp @@ -2607,9 +2607,9 @@ public: funcSymbolAttr, operands); if (caller.mustSaveResult()) - builder.create<fir::SaveResultOp>( - loc, call.getResult(0), fir::getBase(allocatedResult.getValue()), - arrayResultShape, resultLengths); + builder.create<fir::SaveResultOp>(loc, call.getResult(0), + fir::getBase(*allocatedResult), + arrayResultShape, resultLengths); if (allocatedResult) { allocatedResult->match( @@ -4110,10 +4110,10 @@ private: mlir::Value{}); } } else if (isBoundsRemap()) { - auto lbs = lbounds.getValue(); + auto lbs = *lbounds; if (lbs.size() > 0) { // Rebox the value with user-specified shift and shape. - auto shapeShiftArgs = flatZip(lbs, ubounds.getValue()); + auto shapeShiftArgs = flatZip(lbs, *ubounds); auto shapeTy = fir::ShapeShiftType::get(eleTy.getContext(), lbs.size()); mlir::Value shapeShift = builder.create<fir::ShapeShiftOp>(loc, shapeTy, shapeShiftArgs); @@ -4185,8 +4185,8 @@ private: auto [iterSpace, insPt] = genIterSpace(resultTy); auto exv = f(iterSpace); iterSpace.setElement(std::move(exv)); - auto lambda = ccStoreToDest.hasValue() - ? ccStoreToDest.getValue() + auto lambda = ccStoreToDest + ? *ccStoreToDest : defaultStoreToDestination(/*substring=*/nullptr); mlir::Value updVal = fir::getBase(lambda(iterSpace)); finalizeElementCtx(); @@ -4522,8 +4522,8 @@ private: } // Generate the lazy mask allocation, if one was given. - if (ccPrelude.hasValue()) - ccPrelude.getValue()(shape); + if (ccPrelude) + ccPrelude.value()(shape); // Now handle the implicit loops. mlir::Value inner = explicitSpaceIsActive() @@ -4582,8 +4582,8 @@ private: fir::ArrayLoadOp createAndLoadSomeArrayTemp(mlir::Type type, llvm::ArrayRef<mlir::Value> shape) { - if (ccLoadDest.hasValue()) - return ccLoadDest.getValue()(shape); + if (ccLoadDest) + return ccLoadDest.value()(shape); auto seqTy = type.dyn_cast<fir::SequenceType>(); assert(seqTy && "must be an array"); mlir::Location loc = getLoc(); @@ -5810,8 +5810,8 @@ private: // always loaded at the beginning of the statement and merged at the // end. destination = arrLoad; - auto lambda = ccStoreToDest.hasValue() - ? ccStoreToDest.getValue() + auto lambda = ccStoreToDest + ? ccStoreToDest.value() : defaultStoreToDestination(components.substring); return [=](IterSpace iters) -> ExtValue { return lambda(iters); }; } @@ -6464,8 +6464,8 @@ private: // Return the continuation. if (fir::isa_char(seqTy.getEleTy())) { - if (charLen.hasValue()) { - auto len = builder.create<fir::LoadOp>(loc, charLen.getValue()); + if (charLen) { + auto len = builder.create<fir::LoadOp>(loc, charLen.value()); return genarr(fir::CharArrayBoxValue{mem, len, extents}); } return genarr(fir::CharArrayBoxValue{mem, zero, extents}); @@ -7181,14 +7181,14 @@ private: void setUnordered(bool b) { unordered = b; } - inline bool isPointerAssignment() const { return lbounds.hasValue(); } + inline bool isPointerAssignment() const { return lbounds.has_value(); } inline bool isBoundsSpec() const { - return isPointerAssignment() && !ubounds.hasValue(); + return isPointerAssignment() && !ubounds.has_value(); } inline bool isBoundsRemap() const { - return isPointerAssignment() && ubounds.hasValue(); + return isPointerAssignment() && ubounds.has_value(); } void setPointerAssignmentBounds( @@ -7515,8 +7515,8 @@ void Fortran::lower::createArrayLoads( auto genLoad = [&](const auto *x) -> fir::ArrayLoadOp { return genArrayLoad(loc, converter, builder, x, symMap, stmtCtx); }; - if (esp.lhsBases[counter].hasValue()) { - auto &base = esp.lhsBases[counter].getValue(); + if (esp.lhsBases[counter]) { + auto &base = *esp.lhsBases[counter]; auto load = std::visit(genLoad, base); esp.initialArgs.push_back(load); esp.resetInnerArgs(); @@ -7535,13 +7535,13 @@ void Fortran::lower::createArrayMergeStores( // Gen the fir.array_merge_store ops for all LHS arrays. for (auto i : llvm::enumerate(esp.getOuterLoop().getResults())) if (llvm::Optional<fir::ArrayLoadOp> ldOpt = esp.getLhsLoad(i.index())) { - fir::ArrayLoadOp load = ldOpt.getValue(); + fir::ArrayLoadOp load = *ldOpt; builder.create<fir::ArrayMergeStoreOp>(loc, load, i.value(), load.getMemref(), load.getSlice(), load.getTypeparams()); } - if (esp.loopCleanup.hasValue()) { - esp.loopCleanup.getValue()(builder); + if (esp.loopCleanup) { + esp.loopCleanup.value()(builder); esp.loopCleanup = llvm::None; } esp.initialArgs.clear(); diff --git a/flang/lib/Lower/CustomIntrinsicCall.cpp b/flang/lib/Lower/CustomIntrinsicCall.cpp index 1127e28..9548045 100644 --- a/flang/lib/Lower/CustomIntrinsicCall.cpp +++ b/flang/lib/Lower/CustomIntrinsicCall.cpp @@ -195,12 +195,12 @@ lowerIshftc(fir::FirOpBuilder &builder, mlir::Location loc, isPresentCheck(2) && "only ISHFTC SIZE arg is expected to be dynamically optional here"); assert(retTy && "ISFHTC must have a return type"); - mlir::Type resultType = retTy.getValue(); + mlir::Type resultType = *retTy; llvm::SmallVector<fir::ExtendedValue> args; args.push_back(getOperand(0)); args.push_back(getOperand(1)); args.push_back(builder - .genIfOp(loc, {resultType}, isPresentCheck(2).getValue(), + .genIfOp(loc, {resultType}, *isPresentCheck(2), /*withElseRegion=*/true) .genThen([&]() { fir::ExtendedValue sizeExv = getOperand(2); diff --git a/flang/lib/Lower/IterationSpace.cpp b/flang/lib/Lower/IterationSpace.cpp index 4d7a7f8..4458086 100644 --- a/flang/lib/Lower/IterationSpace.cpp +++ b/flang/lib/Lower/IterationSpace.cpp @@ -862,12 +862,12 @@ void Fortran::lower::ExplicitIterSpace::conditionalCleanup() { llvm::Optional<size_t> Fortran::lower::ExplicitIterSpace::findArgPosition(fir::ArrayLoadOp load) { - if (lhsBases[counter].hasValue()) { - auto ld = loadBindings.find(lhsBases[counter].getValue()); + if (lhsBases[counter]) { + auto ld = loadBindings.find(*lhsBases[counter]); llvm::Optional<size_t> optPos; if (ld != loadBindings.end() && ld->second == load) optPos = static_cast<size_t>(0u); - assert(optPos.hasValue() && "load does not correspond to lhs"); + assert(optPos && "load does not correspond to lhs"); return optPos; } return llvm::None; @@ -919,8 +919,8 @@ Fortran::lower::operator<<(llvm::raw_ostream &s, s << "LHS bases:\n"; for (const llvm::Optional<Fortran::lower::ExplicitIterSpace::ArrayBases> &u : e.lhsBases) - if (u.hasValue()) - dump(u.getValue()); + if (u) + dump(*u); s << "RHS bases:\n"; for (const llvm::SmallVector<Fortran::lower::ExplicitIterSpace::ArrayBases> &bases : e.rhsBases) { diff --git a/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp b/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp index e652ca7..4cb1cf8 100644 --- a/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp +++ b/flang/lib/Optimizer/CodeGen/BoxedProcedure.cpp @@ -252,11 +252,11 @@ public: auto toTy = typeConverter.convertType(unwrapRefType(ty)); bool isPinned = mem.getPinned(); llvm::StringRef uniqName; - if (mem.getUniqName().hasValue()) - uniqName = mem.getUniqName().getValue(); + if (mem.getUniqName()) + uniqName = mem.getUniqName().value(); llvm::StringRef bindcName; - if (mem.getBindcName().hasValue()) - bindcName = mem.getBindcName().getValue(); + if (mem.getBindcName()) + bindcName = mem.getBindcName().value(); rewriter.replaceOpWithNewOp<AllocaOp>( mem, toTy, uniqName, bindcName, isPinned, mem.getTypeparams(), mem.getShape()); @@ -267,11 +267,11 @@ public: rewriter.setInsertionPoint(mem); auto toTy = typeConverter.convertType(unwrapRefType(ty)); llvm::StringRef uniqName; - if (mem.getUniqName().hasValue()) - uniqName = mem.getUniqName().getValue(); + if (mem.getUniqName()) + uniqName = mem.getUniqName().value(); llvm::StringRef bindcName; - if (mem.getBindcName().hasValue()) - bindcName = mem.getBindcName().getValue(); + if (mem.getBindcName()) + bindcName = mem.getBindcName().value(); rewriter.replaceOpWithNewOp<AllocMemOp>( mem, toTy, uniqName, bindcName, mem.getTypeparams(), mem.getShape()); diff --git a/flang/lib/Optimizer/CodeGen/CodeGen.cpp b/flang/lib/Optimizer/CodeGen/CodeGen.cpp index ad59bd7..5fc2e17 100644 --- a/flang/lib/Optimizer/CodeGen/CodeGen.cpp +++ b/flang/lib/Optimizer/CodeGen/CodeGen.cpp @@ -2636,9 +2636,9 @@ struct GlobalOpConversion : public FIROpConversion<fir::GlobalOp> { auto loc = global.getLoc(); mlir::Attribute initAttr; if (global.getInitVal()) - initAttr = global.getInitVal().getValue(); + initAttr = *global.getInitVal(); auto linkage = convertLinkage(global.getLinkName()); - auto isConst = global.getConstant().hasValue(); + auto isConst = global.getConstant().has_value(); auto g = rewriter.create<mlir::LLVM::GlobalOp>( loc, tyAttr, isConst, linkage, global.getSymName(), initAttr); auto &gr = g.getInitializerRegion(); @@ -2692,8 +2692,8 @@ struct GlobalOpConversion : public FIROpConversion<fir::GlobalOp> { // enumeration. mlir::LLVM::Linkage convertLinkage(llvm::Optional<llvm::StringRef> optLinkage) const { - if (optLinkage.hasValue()) { - auto name = optLinkage.getValue(); + if (optLinkage) { + auto name = *optLinkage; if (name == "internal") return mlir::LLVM::Linkage::Internal; if (name == "linkonce") @@ -2749,9 +2749,9 @@ static void genCondBrOp(mlir::Location loc, mlir::Value cmp, mlir::Block *dest, llvm::Optional<mlir::ValueRange> destOps, mlir::ConversionPatternRewriter &rewriter, mlir::Block *newBlock) { - if (destOps.hasValue()) - rewriter.create<mlir::LLVM::CondBrOp>(loc, cmp, dest, destOps.getValue(), - newBlock, mlir::ValueRange()); + if (destOps) + rewriter.create<mlir::LLVM::CondBrOp>(loc, cmp, dest, *destOps, newBlock, + mlir::ValueRange()); else rewriter.create<mlir::LLVM::CondBrOp>(loc, cmp, dest, newBlock); } @@ -2759,9 +2759,8 @@ static void genCondBrOp(mlir::Location loc, mlir::Value cmp, mlir::Block *dest, template <typename A, typename B> static void genBrOp(A caseOp, mlir::Block *dest, llvm::Optional<B> destOps, mlir::ConversionPatternRewriter &rewriter) { - if (destOps.hasValue()) - rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(caseOp, destOps.getValue(), - dest); + if (destOps) + rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(caseOp, *destOps, dest); else rewriter.replaceOpWithNewOp<mlir::LLVM::BrOp>(caseOp, llvm::None, dest); } @@ -2884,15 +2883,14 @@ static void selectMatchAndRewrite(fir::LLVMTypeConverter &lowering, OP select, const mlir::Attribute &attr = cases[t]; if (auto intAttr = attr.template dyn_cast<mlir::IntegerAttr>()) { destinations.push_back(dest); - destinationsOperands.push_back(destOps.hasValue() ? *destOps - : mlir::ValueRange{}); + destinationsOperands.push_back(destOps ? *destOps : mlir::ValueRange{}); caseValues.push_back(intAttr.getInt()); continue; } assert(attr.template dyn_cast_or_null<mlir::UnitAttr>()); assert((t + 1 == conds) && "unit must be last"); defaultDestination = dest; - defaultOperands = destOps.hasValue() ? *destOps : mlir::ValueRange{}; + defaultOperands = destOps ? *destOps : mlir::ValueRange{}; } // LLVM::SwitchOp takes a i32 type for the selector. diff --git a/flang/lib/Optimizer/CodeGen/TargetRewrite.cpp b/flang/lib/Optimizer/CodeGen/TargetRewrite.cpp index f1e58d4..9b744fe 100644 --- a/flang/lib/Optimizer/CodeGen/TargetRewrite.cpp +++ b/flang/lib/Optimizer/CodeGen/TargetRewrite.cpp @@ -316,9 +316,9 @@ public: newOpers.insert(newOpers.end(), trailingOpers.begin(), trailingOpers.end()); if constexpr (std::is_same_v<std::decay_t<A>, fir::CallOp>) { fir::CallOp newCall; - if (callOp.getCallee().hasValue()) { - newCall = rewriter->create<A>(loc, callOp.getCallee().getValue(), - newResTys, newOpers); + if (callOp.getCallee()) { + newCall = + rewriter->create<A>(loc, *callOp.getCallee(), newResTys, newOpers); } else { // Force new type on the input operand. newOpers[0].setType(mlir::FunctionType::get( diff --git a/flang/lib/Optimizer/Dialect/FIROps.cpp b/flang/lib/Optimizer/Dialect/FIROps.cpp index 6443d5c..7a6da50 100644 --- a/flang/lib/Optimizer/Dialect/FIROps.cpp +++ b/flang/lib/Optimizer/Dialect/FIROps.cpp @@ -616,10 +616,10 @@ mlir::FunctionType fir::CallOp::getFunctionType() { } void fir::CallOp::print(mlir::OpAsmPrinter &p) { - bool isDirect = getCallee().hasValue(); + bool isDirect = getCallee().has_value(); p << ' '; if (isDirect) - p << getCallee().getValue(); + p << *getCallee(); else p << getOperand(0); p << '(' << (*this)->getOperands().drop_front(isDirect ? 0 : 1) << ')'; @@ -700,9 +700,8 @@ static void printCmpOp(mlir::OpAsmPrinter &p, OPTY op) { op->template getAttrOfType<mlir::IntegerAttr>( OPTY::getPredicateAttrName()) .getInt()); - assert(predSym.hasValue() && "invalid symbol value for predicate"); - p << '"' << mlir::arith::stringifyCmpFPredicate(predSym.getValue()) << '"' - << ", "; + assert(predSym && "invalid symbol value for predicate"); + p << '"' << mlir::arith::stringifyCmpFPredicate(*predSym) << '"' << ", "; p.printOperand(op.getLhs()); p << ", "; p.printOperand(op.getRhs()); @@ -777,8 +776,8 @@ void fir::buildCmpCOp(mlir::OpBuilder &builder, mlir::OperationState &result, mlir::arith::CmpFPredicate fir::CmpcOp::getPredicateByName(llvm::StringRef name) { auto pred = mlir::arith::symbolizeCmpFPredicate(name); - assert(pred.hasValue() && "invalid predicate name"); - return pred.getValue(); + assert(pred && "invalid predicate name"); + return *pred; } void fir::CmpcOp::print(mlir::OpAsmPrinter &p) { printCmpOp(p, *this); } @@ -1074,7 +1073,7 @@ mlir::ParseResult fir::DispatchTableOp::parse(mlir::OpAsmParser &parser, // Parse the optional table body. mlir::Region *body = result.addRegion(); mlir::OptionalParseResult parseResult = parser.parseOptionalRegion(*body); - if (parseResult.hasValue() && failed(*parseResult)) + if (parseResult.has_value() && failed(*parseResult)) return mlir::failure(); fir::DispatchTableOp::ensureTerminator(*body, parser.getBuilder(), @@ -1256,15 +1255,15 @@ mlir::ParseResult fir::GlobalOp::parse(mlir::OpAsmParser &parser, // Parse the optional initializer body. auto parseResult = parser.parseOptionalRegion(*result.addRegion(), /*arguments=*/{}); - if (parseResult.hasValue() && mlir::failed(*parseResult)) + if (parseResult.has_value() && mlir::failed(*parseResult)) return mlir::failure(); } return mlir::success(); } void fir::GlobalOp::print(mlir::OpAsmPrinter &p) { - if (getLinkName().hasValue()) - p << ' ' << getLinkName().getValue(); + if (getLinkName()) + p << ' ' << *getLinkName(); p << ' '; p.printAttributeWithoutType(getSymrefAttr()); if (auto val = getValueOrNull()) diff --git a/flang/lib/Optimizer/Dialect/FIRType.cpp b/flang/lib/Optimizer/Dialect/FIRType.cpp index 3293cad..5347d85 100644 --- a/flang/lib/Optimizer/Dialect/FIRType.cpp +++ b/flang/lib/Optimizer/Dialect/FIRType.cpp @@ -120,7 +120,7 @@ mlir::Type fir::parseFirType(FIROpsDialect *dialect, return {}; mlir::Type genType; auto parseResult = generatedTypeParser(parser, typeTag, genType); - if (parseResult.hasValue()) + if (parseResult.has_value()) return genType; parser.emitError(parser.getNameLoc(), "unknown fir type: ") << typeTag; return {}; diff --git a/flang/lib/Optimizer/Support/InternalNames.cpp b/flang/lib/Optimizer/Support/InternalNames.cpp index 8e37df2..19a2740 100644 --- a/flang/lib/Optimizer/Support/InternalNames.cpp +++ b/flang/lib/Optimizer/Support/InternalNames.cpp @@ -51,8 +51,8 @@ convertToStringRef(llvm::ArrayRef<std::string> from) { inline llvm::Optional<llvm::StringRef> convertToStringRef(const llvm::Optional<std::string> &from) { llvm::Optional<llvm::StringRef> to; - if (from.hasValue()) - to = from.getValue(); + if (from) + to = *from; return to; } diff --git a/flang/lib/Optimizer/Transforms/AbstractResult.cpp b/flang/lib/Optimizer/Transforms/AbstractResult.cpp index 7dd8214..68f3247 100644 --- a/flang/lib/Optimizer/Transforms/AbstractResult.cpp +++ b/flang/lib/Optimizer/Transforms/AbstractResult.cpp @@ -101,7 +101,7 @@ public: llvm::SmallVector<mlir::Value> newOperands = {arg}; newOperands.append(callOp.getOperands().begin(), callOp.getOperands().end()); - rewriter.create<fir::CallOp>(loc, callOp.getCallee().getValue(), + rewriter.create<fir::CallOp>(loc, callOp.getCallee().value(), newResultTypes, newOperands); } else { // Indirect calls. diff --git a/flang/lib/Optimizer/Transforms/AffinePromotion.cpp b/flang/lib/Optimizer/Transforms/AffinePromotion.cpp index 3890721..dd7b259 100644 --- a/flang/lib/Optimizer/Transforms/AffinePromotion.cpp +++ b/flang/lib/Optimizer/Transforms/AffinePromotion.cpp @@ -171,11 +171,11 @@ struct AffineIfCondition { fromCmpIOp(condDef); } - bool hasIntegerSet() const { return integerSet.hasValue(); } + bool hasIntegerSet() const { return integerSet.has_value(); } mlir::IntegerSet getIntegerSet() const { assert(hasIntegerSet() && "integer set is missing"); - return integerSet.getValue(); + return *integerSet; } mlir::ValueRange getAffineArgs() const { return affineArgs; } @@ -188,8 +188,8 @@ private: MaybeAffineExpr affineBinaryOp(mlir::AffineExprKind kind, MaybeAffineExpr lhs, MaybeAffineExpr rhs) { - if (lhs.hasValue() && rhs.hasValue()) - return mlir::getAffineBinaryOpExpr(kind, lhs.getValue(), rhs.getValue()); + if (lhs && rhs) + return mlir::getAffineBinaryOpExpr(kind, *lhs, *rhs); return {}; } @@ -233,15 +233,14 @@ private: void fromCmpIOp(mlir::arith::CmpIOp cmpOp) { auto lhsAffine = toAffineExpr(cmpOp.getLhs()); auto rhsAffine = toAffineExpr(cmpOp.getRhs()); - if (!lhsAffine.hasValue() || !rhsAffine.hasValue()) + if (!lhsAffine || !rhsAffine) return; - auto constraintPair = constraint( - cmpOp.getPredicate(), rhsAffine.getValue() - lhsAffine.getValue()); + auto constraintPair = + constraint(cmpOp.getPredicate(), *rhsAffine - *lhsAffine); if (!constraintPair) return; - integerSet = mlir::IntegerSet::get(dimCount, symCount, - {constraintPair.getValue().first}, - {constraintPair.getValue().second}); + integerSet = mlir::IntegerSet::get( + dimCount, symCount, {constraintPair->first}, {constraintPair->second}); return; } @@ -484,8 +483,8 @@ private: std::pair<mlir::AffineForOp, mlir::Value> createAffineFor(fir::DoLoopOp op, mlir::PatternRewriter &rewriter) const { if (auto constantStep = constantIntegerLike(op.getStep())) - if (constantStep.getValue() > 0) - return positiveConstantStep(op, constantStep.getValue(), rewriter); + if (*constantStep > 0) + return positiveConstantStep(op, *constantStep, rewriter); return genericBounds(op, rewriter); } diff --git a/flang/lib/Optimizer/Transforms/ExternalNameConversion.cpp b/flang/lib/Optimizer/Transforms/ExternalNameConversion.cpp index 6170556..42260ad 100644 --- a/flang/lib/Optimizer/Transforms/ExternalNameConversion.cpp +++ b/flang/lib/Optimizer/Transforms/ExternalNameConversion.cpp @@ -49,9 +49,9 @@ public: mlir::PatternRewriter &rewriter) const override { rewriter.startRootUpdate(op); auto callee = op.getCallee(); - if (callee.hasValue()) { - auto result = fir::NameUniquer::deconstruct( - callee.getValue().getRootReference().getValue()); + if (callee) { + auto result = + fir::NameUniquer::deconstruct(callee->getRootReference().getValue()); if (fir::NameUniquer::isExternalFacingUniquedName(result)) op.setCalleeAttr( SymbolRefAttr::get(op.getContext(), mangleExternalName(result))); @@ -137,9 +137,9 @@ void ExternalNameConversionPass::runOnOperation() { acc::OpenACCDialect, omp::OpenMPDialect>(); target.addDynamicallyLegalOp<fir::CallOp>([](fir::CallOp op) { - if (op.getCallee().hasValue()) + if (op.getCallee()) return !fir::NameUniquer::needExternalNameMangling( - op.getCallee().getValue().getRootReference().getValue()); + op.getCallee()->getRootReference().getValue()); return true; }); diff --git a/flang/unittests/Optimizer/Builder/FIRBuilderTest.cpp b/flang/unittests/Optimizer/Builder/FIRBuilderTest.cpp index 3997d8f..3172844 100644 --- a/flang/unittests/Optimizer/Builder/FIRBuilderTest.cpp +++ b/flang/unittests/Optimizer/Builder/FIRBuilderTest.cpp @@ -189,12 +189,12 @@ TEST_F(FIRBuilderTest, createGlobal1) { loc, i64Type, "global1", builder.createInternalLinkage(), {}, true); EXPECT_TRUE(mlir::isa<fir::GlobalOp>(global)); EXPECT_EQ("global1", global.getSymName()); - EXPECT_TRUE(global.getConstant().hasValue()); + EXPECT_TRUE(global.getConstant().has_value()); EXPECT_EQ(i64Type, global.getType()); - EXPECT_TRUE(global.getLinkName().hasValue()); - EXPECT_EQ(builder.createInternalLinkage().getValue(), - global.getLinkName().getValue()); - EXPECT_FALSE(global.getInitVal().hasValue()); + EXPECT_TRUE(global.getLinkName().has_value()); + EXPECT_EQ( + builder.createInternalLinkage().getValue(), global.getLinkName().value()); + EXPECT_FALSE(global.getInitVal().has_value()); auto g1 = builder.getNamedGlobal("global1"); EXPECT_EQ(global, g1); @@ -213,15 +213,14 @@ TEST_F(FIRBuilderTest, createGlobal2) { loc, i32Type, "global2", builder.createLinkOnceLinkage(), attr, false); EXPECT_TRUE(mlir::isa<fir::GlobalOp>(global)); EXPECT_EQ("global2", global.getSymName()); - EXPECT_FALSE(global.getConstant().hasValue()); + EXPECT_FALSE(global.getConstant().has_value()); EXPECT_EQ(i32Type, global.getType()); - EXPECT_TRUE(global.getInitVal().hasValue()); - EXPECT_TRUE(global.getInitVal().getValue().isa<mlir::IntegerAttr>()); + EXPECT_TRUE(global.getInitVal().has_value()); + EXPECT_TRUE(global.getInitVal()->isa<mlir::IntegerAttr>()); + EXPECT_EQ(16, global.getInitVal()->cast<mlir::IntegerAttr>().getValue()); + EXPECT_TRUE(global.getLinkName().has_value()); EXPECT_EQ( - 16, global.getInitVal().getValue().cast<mlir::IntegerAttr>().getValue()); - EXPECT_TRUE(global.getLinkName().hasValue()); - EXPECT_EQ(builder.createLinkOnceLinkage().getValue(), - global.getLinkName().getValue()); + builder.createLinkOnceLinkage().getValue(), global.getLinkName().value()); } TEST_F(FIRBuilderTest, uniqueCFIdent) { @@ -310,8 +309,8 @@ TEST_F(FIRBuilderTest, createStringLiteral) { auto addrOp = dyn_cast<fir::AddrOfOp>(addr.getDefiningOp()); auto symbol = addrOp.getSymbol().getRootReference().getValue(); auto global = builder.getNamedGlobal(symbol); - EXPECT_EQ(builder.createLinkOnceLinkage().getValue(), - global.getLinkName().getValue()); + EXPECT_EQ( + builder.createLinkOnceLinkage().getValue(), global.getLinkName().value()); EXPECT_EQ(fir::CharacterType::get(builder.getContext(), 1, strValue.size()), global.getType()); @@ -333,9 +332,9 @@ TEST_F(FIRBuilderTest, allocateLocal) { EXPECT_TRUE(mlir::isa<fir::AllocaOp>(var.getDefiningOp())); auto allocaOp = dyn_cast<fir::AllocaOp>(var.getDefiningOp()); EXPECT_EQ(builder.getI64Type(), allocaOp.getInType()); - EXPECT_TRUE(allocaOp.getBindcName().hasValue()); - EXPECT_EQ(varName, allocaOp.getBindcName().getValue()); - EXPECT_FALSE(allocaOp.getUniqName().hasValue()); + EXPECT_TRUE(allocaOp.getBindcName().has_value()); + EXPECT_EQ(varName, allocaOp.getBindcName().value()); + EXPECT_FALSE(allocaOp.getUniqName().has_value()); EXPECT_FALSE(allocaOp.getPinned()); EXPECT_EQ(0u, allocaOp.getTypeparams().size()); EXPECT_EQ(0u, allocaOp.getShape().size()); diff --git a/flang/unittests/Optimizer/Builder/Runtime/RuntimeCallTestBase.h b/flang/unittests/Optimizer/Builder/Runtime/RuntimeCallTestBase.h index 8d549c5..4b7c9f1 100644 --- a/flang/unittests/Optimizer/Builder/Runtime/RuntimeCallTestBase.h +++ b/flang/unittests/Optimizer/Builder/Runtime/RuntimeCallTestBase.h @@ -87,7 +87,7 @@ static inline void checkCallOp(mlir::Operation *op, llvm::StringRef fctName, unsigned nbArgs, bool addLocArgs = true) { EXPECT_TRUE(mlir::isa<fir::CallOp>(*op)); auto callOp = mlir::dyn_cast<fir::CallOp>(*op); - EXPECT_TRUE(callOp.getCallee().hasValue()); + EXPECT_TRUE(callOp.getCallee().has_value()); mlir::SymbolRefAttr callee = *callOp.getCallee(); EXPECT_EQ(fctName, callee.getRootReference().getValue()); // sourceFile and sourceLine are added arguments. diff --git a/lld/ELF/InputFiles.cpp b/lld/ELF/InputFiles.cpp index 926400d0..a9b00b7 100644 --- a/lld/ELF/InputFiles.cpp +++ b/lld/ELF/InputFiles.cpp @@ -744,9 +744,9 @@ static void updateARMVFPArgs(const ARMAttributeParser &attributes, static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) { Optional<unsigned> attr = attributes.getAttributeValue(ARMBuildAttrs::CPU_arch); - if (!attr.hasValue()) + if (!attr) return; - auto arch = attr.getValue(); + auto arch = *attr; switch (arch) { case ARMBuildAttrs::Pre_v4: case ARMBuildAttrs::v4: diff --git a/lld/MachO/SectionPriorities.cpp b/lld/MachO/SectionPriorities.cpp index cdabd3e..0794217 100644 --- a/lld/MachO/SectionPriorities.cpp +++ b/lld/MachO/SectionPriorities.cpp @@ -367,10 +367,10 @@ macho::PriorityBuilder::buildInputSectionPriorities() { auto addSym = [&](const Defined *sym) { Optional<size_t> symbolPriority = getSymbolPriority(sym); - if (!symbolPriority.hasValue()) + if (!symbolPriority) return; size_t &priority = sectionPriorities[sym->isec]; - priority = std::max(priority, symbolPriority.getValue()); + priority = std::max(priority, *symbolPriority); }; // TODO: Make sure this handles weak symbols correctly. diff --git a/lld/wasm/InputChunks.h b/lld/wasm/InputChunks.h index f962616..066ca623 100644 --- a/lld/wasm/InputChunks.h +++ b/lld/wasm/InputChunks.h @@ -249,9 +249,9 @@ class InputFunction : public InputChunk { public: InputFunction(const WasmSignature &s, const WasmFunction *func, ObjFile *f) : InputChunk(f, InputChunk::Function, func->SymbolName), signature(s), - function(func), exportName(func && func->ExportName.hasValue() - ? (*func->ExportName).str() - : llvm::Optional<std::string>()) { + function(func), + exportName(func && func->ExportName ? (*func->ExportName).str() + : llvm::Optional<std::string>()) { inputSectionOffset = function->CodeSectionOffset; rawData = file->codeSection->Content.slice(inputSectionOffset, function->Size); @@ -268,17 +268,17 @@ public: } llvm::Optional<StringRef> getExportName() const { - return exportName.hasValue() ? llvm::Optional<StringRef>(*exportName) - : llvm::Optional<StringRef>(); + return exportName ? llvm::Optional<StringRef>(*exportName) + : llvm::Optional<StringRef>(); } void setExportName(std::string exportName) { this->exportName = exportName; } uint32_t getFunctionInputOffset() const { return getInputSectionOffset(); } uint32_t getFunctionCodeOffset() const { return function->CodeOffset; } - uint32_t getFunctionIndex() const { return functionIndex.getValue(); } - bool hasFunctionIndex() const { return functionIndex.hasValue(); } + uint32_t getFunctionIndex() const { return *functionIndex; } + bool hasFunctionIndex() const { return functionIndex.has_value(); } void setFunctionIndex(uint32_t index); - uint32_t getTableIndex() const { return tableIndex.getValue(); } - bool hasTableIndex() const { return tableIndex.hasValue(); } + uint32_t getTableIndex() const { return *tableIndex; } + bool hasTableIndex() const { return tableIndex.has_value(); } void setTableIndex(uint32_t index); void writeCompressed(uint8_t *buf) const; diff --git a/lld/wasm/InputElement.h b/lld/wasm/InputElement.h index 9bea90b..0d4e9b3 100644 --- a/lld/wasm/InputElement.h +++ b/lld/wasm/InputElement.h @@ -27,8 +27,8 @@ protected: public: StringRef getName() const { return name; } - uint32_t getAssignedIndex() const { return assignedIndex.getValue(); } - bool hasAssignedIndex() const { return assignedIndex.hasValue(); } + uint32_t getAssignedIndex() const { return *assignedIndex; } + bool hasAssignedIndex() const { return assignedIndex.has_value(); } void assignIndex(uint32_t index) { assert(!hasAssignedIndex()); assignedIndex = index; diff --git a/lld/wasm/Writer.cpp b/lld/wasm/Writer.cpp index fa9802d..2de43ab 100644 --- a/lld/wasm/Writer.cpp +++ b/lld/wasm/Writer.cpp @@ -446,10 +446,10 @@ void Writer::populateTargetFeatures() { } // Only infer used features if user did not specify features - bool inferFeatures = !config->features.hasValue(); + bool inferFeatures = !config->features.has_value(); if (!inferFeatures) { - auto &explicitFeatures = config->features.getValue(); + auto &explicitFeatures = config->features.value(); allowed.insert(explicitFeatures.begin(), explicitFeatures.end()); if (!config->checkFeatures) goto done; diff --git a/lldb/include/lldb/Target/MemoryRegionInfo.h b/lldb/include/lldb/Target/MemoryRegionInfo.h index acca66e..8df7904 100644 --- a/lldb/include/lldb/Target/MemoryRegionInfo.h +++ b/lldb/include/lldb/Target/MemoryRegionInfo.h @@ -124,8 +124,8 @@ public: void SetPageSize(int pagesize) { m_pagesize = pagesize; } void SetDirtyPageList(std::vector<lldb::addr_t> pagelist) { - if (m_dirty_pages.hasValue()) - m_dirty_pages.getValue().clear(); + if (m_dirty_pages) + m_dirty_pages->clear(); m_dirty_pages = std::move(pagelist); } diff --git a/lldb/source/API/SBMemoryRegionInfo.cpp b/lldb/source/API/SBMemoryRegionInfo.cpp index d0f7437..f4d78cf 100644 --- a/lldb/source/API/SBMemoryRegionInfo.cpp +++ b/lldb/source/API/SBMemoryRegionInfo.cpp @@ -135,8 +135,8 @@ uint32_t SBMemoryRegionInfo::GetNumDirtyPages() { uint32_t num_dirty_pages = 0; const llvm::Optional<std::vector<addr_t>> &dirty_page_list = m_opaque_up->GetDirtyPageList(); - if (dirty_page_list.hasValue()) - num_dirty_pages = dirty_page_list.getValue().size(); + if (dirty_page_list) + num_dirty_pages = dirty_page_list->size(); return num_dirty_pages; } @@ -147,8 +147,8 @@ addr_t SBMemoryRegionInfo::GetDirtyPageAddressAtIndex(uint32_t idx) { addr_t dirty_page_addr = LLDB_INVALID_ADDRESS; const llvm::Optional<std::vector<addr_t>> &dirty_page_list = m_opaque_up->GetDirtyPageList(); - if (dirty_page_list.hasValue() && idx < dirty_page_list.getValue().size()) - dirty_page_addr = dirty_page_list.getValue()[idx]; + if (dirty_page_list && idx < dirty_page_list->size()) + dirty_page_addr = dirty_page_list.value()[idx]; return dirty_page_addr; } diff --git a/lldb/source/Breakpoint/BreakpointIDList.cpp b/lldb/source/Breakpoint/BreakpointIDList.cpp index b434056..20f75662 100644 --- a/lldb/source/Breakpoint/BreakpointIDList.cpp +++ b/lldb/source/Breakpoint/BreakpointIDList.cpp @@ -192,16 +192,14 @@ void BreakpointIDList::FindAndReplaceIDRanges(Args &old_args, Target *target, auto start_bp = BreakpointID::ParseCanonicalReference(range_from); auto end_bp = BreakpointID::ParseCanonicalReference(range_to); - if (!start_bp.hasValue() || - !target->GetBreakpointByID(start_bp->GetBreakpointID())) { + if (!start_bp || !target->GetBreakpointByID(start_bp->GetBreakpointID())) { new_args.Clear(); result.AppendErrorWithFormat("'%s' is not a valid breakpoint ID.\n", range_from.str().c_str()); return; } - if (!end_bp.hasValue() || - !target->GetBreakpointByID(end_bp->GetBreakpointID())) { + if (!end_bp || !target->GetBreakpointByID(end_bp->GetBreakpointID())) { new_args.Clear(); result.AppendErrorWithFormat("'%s' is not a valid breakpoint ID.\n", range_to.str().c_str()); diff --git a/lldb/source/Commands/CommandObjectFrame.cpp b/lldb/source/Commands/CommandObjectFrame.cpp index 4081e87..dfe1e14 100644 --- a/lldb/source/Commands/CommandObjectFrame.cpp +++ b/lldb/source/Commands/CommandObjectFrame.cpp @@ -137,16 +137,16 @@ protected: ValueObjectSP valobj_sp; - if (m_options.address.hasValue()) { - if (m_options.reg.hasValue() || m_options.offset.hasValue()) { + if (m_options.address) { + if (m_options.reg || m_options.offset) { result.AppendError( "`frame diagnose --address` is incompatible with other arguments."); return false; } - valobj_sp = frame_sp->GuessValueForAddress(m_options.address.getValue()); - } else if (m_options.reg.hasValue()) { + valobj_sp = frame_sp->GuessValueForAddress(*m_options.address); + } else if (m_options.reg) { valobj_sp = frame_sp->GuessValueForRegisterAndOffset( - m_options.reg.getValue(), m_options.offset.value_or(0)); + m_options.reg.value(), m_options.offset.value_or(0)); } else { StopInfoSP stop_info_sp = thread->GetStopInfo(); if (!stop_info_sp) { diff --git a/lldb/source/Commands/CommandObjectMemory.cpp b/lldb/source/Commands/CommandObjectMemory.cpp index 117b5f4..be887f1 100644 --- a/lldb/source/Commands/CommandObjectMemory.cpp +++ b/lldb/source/Commands/CommandObjectMemory.cpp @@ -1737,8 +1737,8 @@ protected: const llvm::Optional<std::vector<addr_t>> &dirty_page_list = range_info.GetDirtyPageList(); - if (dirty_page_list.hasValue()) { - const size_t page_count = dirty_page_list.getValue().size(); + if (dirty_page_list) { + const size_t page_count = dirty_page_list->size(); result.AppendMessageWithFormat( "Modified memory (dirty) page list provided, %zu entries.\n", page_count); diff --git a/lldb/source/Core/DataFileCache.cpp b/lldb/source/Core/DataFileCache.cpp index 5f8568f..b38adfd 100644 --- a/lldb/source/Core/DataFileCache.cpp +++ b/lldb/source/Core/DataFileCache.cpp @@ -203,17 +203,17 @@ bool CacheSignature::Encode(DataEncoder &encoder) const { if (!IsValid()) return false; // Invalid signature, return false! - if (m_uuid.hasValue()) { + if (m_uuid) { llvm::ArrayRef<uint8_t> uuid_bytes = m_uuid->GetBytes(); encoder.AppendU8(eSignatureUUID); encoder.AppendU8(uuid_bytes.size()); encoder.AppendData(uuid_bytes); } - if (m_mod_time.hasValue()) { + if (m_mod_time) { encoder.AppendU8(eSignatureModTime); encoder.AppendU32(*m_mod_time); } - if (m_obj_mod_time.hasValue()) { + if (m_obj_mod_time) { encoder.AppendU8(eSignatureObjectModTime); encoder.AppendU32(*m_obj_mod_time); } diff --git a/lldb/source/Core/DumpDataExtractor.cpp b/lldb/source/Core/DumpDataExtractor.cpp index 211e16a..f96c232 100644 --- a/lldb/source/Core/DumpDataExtractor.cpp +++ b/lldb/source/Core/DumpDataExtractor.cpp @@ -118,8 +118,8 @@ static lldb::offset_t DumpAPInt(Stream *s, const DataExtractor &data, lldb::offset_t offset, lldb::offset_t byte_size, bool is_signed, unsigned radix) { llvm::Optional<llvm::APInt> apint = GetAPInt(data, &offset, byte_size); - if (apint.hasValue()) { - std::string apint_str = toString(apint.getValue(), radix, is_signed); + if (apint) { + std::string apint_str = toString(*apint, radix, is_signed); switch (radix) { case 2: s->Write("0b", 2); @@ -670,8 +670,8 @@ lldb::offset_t lldb_private::DumpDataExtractor( (llvm::APFloat::getSizeInBits(semantics) + 7) / 8; llvm::Optional<llvm::APInt> apint = GetAPInt(DE, &offset, semantics_byte_size); - if (apint.hasValue()) { - llvm::APFloat apfloat(semantics, apint.getValue()); + if (apint) { + llvm::APFloat apfloat(semantics, *apint); apfloat.toString(sv, format_precision, format_max_padding); if (!sv.empty()) { s->Printf("%*.*s", (int)sv.size(), (int)sv.size(), sv.data()); diff --git a/lldb/source/Core/ValueObjectChild.cpp b/lldb/source/Core/ValueObjectChild.cpp index a2beeb0..f0c91e4 100644 --- a/lldb/source/Core/ValueObjectChild.cpp +++ b/lldb/source/Core/ValueObjectChild.cpp @@ -82,8 +82,8 @@ ConstString ValueObjectChild::GetDisplayTypeName() { } LazyBool ValueObjectChild::CanUpdateWithInvalidExecutionContext() { - if (m_can_update_with_invalid_exe_ctx.hasValue()) - return m_can_update_with_invalid_exe_ctx.getValue(); + if (m_can_update_with_invalid_exe_ctx) + return *m_can_update_with_invalid_exe_ctx; if (m_parent) { ValueObject *opinionated_parent = m_parent->FollowParentChain([](ValueObject *valobj) -> bool { @@ -93,11 +93,11 @@ LazyBool ValueObjectChild::CanUpdateWithInvalidExecutionContext() { if (opinionated_parent) return (m_can_update_with_invalid_exe_ctx = opinionated_parent->CanUpdateWithInvalidExecutionContext()) - .getValue(); + .value(); } return (m_can_update_with_invalid_exe_ctx = this->ValueObject::CanUpdateWithInvalidExecutionContext()) - .getValue(); + .value(); } bool ValueObjectChild::UpdateValue() { diff --git a/lldb/source/Host/common/File.cpp b/lldb/source/Host/common/File.cpp index 760fb98..476ab23 100644 --- a/lldb/source/Host/common/File.cpp +++ b/lldb/source/Host/common/File.cpp @@ -833,22 +833,19 @@ SerialPort::Create(int fd, OpenOptions options, Options serial_options, if (llvm::Error error = term.SetRaw()) return std::move(error); if (serial_options.BaudRate) { - if (llvm::Error error = - term.SetBaudRate(serial_options.BaudRate.getValue())) + if (llvm::Error error = term.SetBaudRate(*serial_options.BaudRate)) return std::move(error); } if (serial_options.Parity) { - if (llvm::Error error = term.SetParity(serial_options.Parity.getValue())) + if (llvm::Error error = term.SetParity(*serial_options.Parity)) return std::move(error); } if (serial_options.ParityCheck) { - if (llvm::Error error = - term.SetParityCheck(serial_options.ParityCheck.getValue())) + if (llvm::Error error = term.SetParityCheck(*serial_options.ParityCheck)) return std::move(error); } if (serial_options.StopBits) { - if (llvm::Error error = - term.SetStopBits(serial_options.StopBits.getValue())) + if (llvm::Error error = term.SetStopBits(*serial_options.StopBits)) return std::move(error); } diff --git a/lldb/source/Host/common/Terminal.cpp b/lldb/source/Host/common/Terminal.cpp index 831e9df..6eb7332 100644 --- a/lldb/source/Host/common/Terminal.cpp +++ b/lldb/source/Host/common/Terminal.cpp @@ -281,11 +281,11 @@ llvm::Error Terminal::SetBaudRate(unsigned int baud_rate) { return llvm::createStringError(llvm::inconvertibleErrorCode(), "baud rate %d unsupported by the platform", baud_rate); - if (::cfsetispeed(&fd_termios, val.getValue()) != 0) + if (::cfsetispeed(&fd_termios, *val) != 0) return llvm::createStringError( std::error_code(errno, std::generic_category()), "setting input baud rate failed"); - if (::cfsetospeed(&fd_termios, val.getValue()) != 0) + if (::cfsetospeed(&fd_termios, *val) != 0) return llvm::createStringError( std::error_code(errno, std::generic_category()), "setting output baud rate failed"); diff --git a/lldb/source/Plugins/ABI/X86/ABIX86.cpp b/lldb/source/Plugins/ABI/X86/ABIX86.cpp index 2cd653f..64c5d5a 100644 --- a/lldb/source/Plugins/ABI/X86/ABIX86.cpp +++ b/lldb/source/Plugins/ABI/X86/ABIX86.cpp @@ -100,8 +100,8 @@ addCombinedRegisters(std::vector<DynamicRegisterInfo::Register> ®s, if (regdata1->subreg_name != regdata2->subreg_name) continue; - uint32_t base_index1 = regdata1->base_index.getValue(); - uint32_t base_index2 = regdata2->base_index.getValue(); + uint32_t base_index1 = *regdata1->base_index; + uint32_t base_index2 = *regdata2->base_index; if (regs[base_index1].byte_size != base_size || regs[base_index2].byte_size != base_size) continue; diff --git a/lldb/source/Plugins/Disassembler/LLVMC/DisassemblerLLVMC.cpp b/lldb/source/Plugins/Disassembler/LLVMC/DisassemblerLLVMC.cpp index e4c7e8f..1f5addc 100644 --- a/lldb/source/Plugins/Disassembler/LLVMC/DisassemblerLLVMC.cpp +++ b/lldb/source/Plugins/Disassembler/LLVMC/DisassemblerLLVMC.cpp @@ -1382,14 +1382,14 @@ const char *DisassemblerLLVMC::SymbolLookup(uint64_t value, uint64_t *type_ptr, // the ADRP's register and this ADD's register are the same, // then this is a pc-relative address calculation. if (*type_ptr == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri && - m_adrp_insn.hasValue() && m_adrp_address == pc - 4 && - (m_adrp_insn.getValue() & 0x1f) == ((value >> 5) & 0x1f)) { + m_adrp_insn && m_adrp_address == pc - 4 && + (*m_adrp_insn & 0x1f) == ((value >> 5) & 0x1f)) { uint32_t addxri_inst; uint64_t adrp_imm, addxri_imm; // Get immlo and immhi bits, OR them together to get the ADRP imm // value. - adrp_imm = ((m_adrp_insn.getValue() & 0x00ffffe0) >> 3) | - ((m_adrp_insn.getValue() >> 29) & 0x3); + adrp_imm = + ((*m_adrp_insn & 0x00ffffe0) >> 3) | ((*m_adrp_insn >> 29) & 0x3); // if high bit of immhi after right-shifting set, sign extend if (adrp_imm & (1ULL << 20)) adrp_imm |= ~((1ULL << 21) - 1); diff --git a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp index 82f8258..4f23ff4 100644 --- a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp +++ b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp @@ -218,10 +218,10 @@ void CPlusPlusLanguage::MethodName::Parse() { } else { CPlusPlusNameParser parser(m_full.GetStringRef()); if (auto function = parser.ParseAsFunctionDefinition()) { - m_basename = function.getValue().name.basename; - m_context = function.getValue().name.context; - m_arguments = function.getValue().arguments; - m_qualifiers = function.getValue().qualifiers; + m_basename = function->name.basename; + m_context = function->name.context; + m_arguments = function->arguments; + m_qualifiers = function->qualifiers; m_parse_error = false; } else { m_parse_error = true; @@ -329,8 +329,8 @@ bool CPlusPlusLanguage::ExtractContextAndIdentifier( CPlusPlusNameParser parser(name); if (auto full_name = parser.ParseAsFullName()) { - identifier = full_name.getValue().basename; - context = full_name.getValue().context; + identifier = full_name->basename; + context = full_name->context; return true; } return false; diff --git a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp index eca36ff..3a1fde2 100644 --- a/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp +++ b/lldb/source/Plugins/Language/CPlusPlus/CPlusPlusNameParser.cpp @@ -55,8 +55,8 @@ Optional<ParsedName> CPlusPlusNameParser::ParseAsFullName() { if (HasMoreTokens()) return None; ParsedName result; - result.basename = GetTextForRange(name_ranges.getValue().basename_range); - result.context = GetTextForRange(name_ranges.getValue().context_range); + result.basename = GetTextForRange(name_ranges->basename_range); + result.context = GetTextForRange(name_ranges->context_range); return result; } @@ -125,8 +125,8 @@ CPlusPlusNameParser::ParseFunctionImpl(bool expect_return_type) { size_t end_position = GetCurrentPosition(); ParsedFunction result; - result.name.basename = GetTextForRange(maybe_name.getValue().basename_range); - result.name.context = GetTextForRange(maybe_name.getValue().context_range); + result.name.basename = GetTextForRange(maybe_name->basename_range); + result.name.context = GetTextForRange(maybe_name->context_range); result.arguments = GetTextForRange(Range(argument_start, qualifiers_start)); result.qualifiers = GetTextForRange(Range(qualifiers_start, end_position)); start_position.Remove(); @@ -616,10 +616,10 @@ CPlusPlusNameParser::ParseFullNameImpl() { state == State::AfterTemplate) { ParsedNameRanges result; if (last_coloncolon_position) { - result.context_range = Range(start_position.GetSavedPosition(), - last_coloncolon_position.getValue()); + result.context_range = + Range(start_position.GetSavedPosition(), *last_coloncolon_position); result.basename_range = - Range(last_coloncolon_position.getValue() + 1, GetCurrentPosition()); + Range(*last_coloncolon_position + 1, GetCurrentPosition()); } else { result.basename_range = Range(start_position.GetSavedPosition(), GetCurrentPosition()); diff --git a/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp b/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp index fdebfcd3..045bdd4 100644 --- a/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp +++ b/lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp @@ -6516,8 +6516,8 @@ bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp, addr_t pagesize = range_info.GetPageSize(); const llvm::Optional<std::vector<addr_t>> &dirty_page_list = range_info.GetDirtyPageList(); - if (dirty_pages_only && dirty_page_list.hasValue()) { - for (addr_t dirtypage : dirty_page_list.getValue()) { + if (dirty_pages_only && dirty_page_list) { + for (addr_t dirtypage : *dirty_page_list) { page_object obj; obj.addr = dirtypage; obj.size = pagesize; diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp index 9f159f6..c44ace9 100644 --- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp +++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp @@ -2722,12 +2722,12 @@ bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid, return true; llvm::Optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g'); - if (ret.hasValue()) { + if (ret) { if (ret->pid != LLDB_INVALID_PROCESS_ID) m_curr_pid = ret->pid; m_curr_tid = ret->tid; } - return ret.hasValue(); + return ret.has_value(); } bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid, @@ -2737,12 +2737,12 @@ bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid, return true; llvm::Optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c'); - if (ret.hasValue()) { + if (ret) { if (ret->pid != LLDB_INVALID_PROCESS_ID) m_curr_pid_run = ret->pid; m_curr_tid_run = ret->tid; } - return ret.hasValue(); + return ret.has_value(); } bool GDBRemoteCommunicationClient::GetStopReply( diff --git a/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp b/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp index 11175a4..b5615c3 100644 --- a/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp +++ b/lldb/source/Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.cpp @@ -674,9 +674,9 @@ SymbolFileBreakpad::ParseCFIUnwindPlan(const Bookmark &bookmark, plan_sp->AppendRow(row_sp); for (++It; It != End; ++It) { llvm::Optional<StackCFIRecord> record = StackCFIRecord::parse(*It); - if (!record.hasValue()) + if (!record) return nullptr; - if (record->Size.hasValue()) + if (record->Size) break; row_sp = std::make_shared<UnwindPlan::Row>(*row_sp); diff --git a/lldb/source/Target/Thread.cpp b/lldb/source/Target/Thread.cpp index 3803748..247913c 100644 --- a/lldb/source/Target/Thread.cpp +++ b/lldb/source/Target/Thread.cpp @@ -2022,7 +2022,8 @@ lldb::ValueObjectSP Thread::GetSiginfoValue() { llvm::Optional<uint64_t> type_size = type.GetByteSize(nullptr); assert(type_size); - llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data = GetSiginfo(type_size.getValue()); + llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data = + GetSiginfo(*type_size); if (!data) return ValueObjectConstResult::Create(&target, Status(data.takeError())); diff --git a/lldb/source/Target/UnixSignals.cpp b/lldb/source/Target/UnixSignals.cpp index de1fdb8..a92138a 100644 --- a/lldb/source/Target/UnixSignals.cpp +++ b/lldb/source/Target/UnixSignals.cpp @@ -300,14 +300,13 @@ UnixSignals::GetFilteredSignals(llvm::Optional<bool> should_suppress, // If any of filtering conditions are not met, we move on to the next // signal. - if (should_suppress.hasValue() && - signal_suppress != should_suppress.getValue()) + if (should_suppress && signal_suppress != *should_suppress) continue; - if (should_stop.hasValue() && signal_stop != should_stop.getValue()) + if (should_stop && signal_stop != *should_stop) continue; - if (should_notify.hasValue() && signal_notify != should_notify.getValue()) + if (should_notify && signal_notify != *should_notify) continue; result.push_back(signo); diff --git a/lldb/source/Utility/SelectHelper.cpp b/lldb/source/Utility/SelectHelper.cpp index eee6895..69b2abf 100644 --- a/lldb/source/Utility/SelectHelper.cpp +++ b/lldb/source/Utility/SelectHelper.cpp @@ -161,15 +161,15 @@ lldb_private::Status SelectHelper::Select() { fd_set write_fdset; fd_set error_fdset; - if (max_read_fd.hasValue()) { + if (max_read_fd) { FD_ZERO(&read_fdset); read_fdset_ptr = &read_fdset; } - if (max_write_fd.hasValue()) { + if (max_write_fd) { FD_ZERO(&write_fdset); write_fdset_ptr = &write_fdset; } - if (max_error_fd.hasValue()) { + if (max_error_fd) { FD_ZERO(&error_fdset); error_fdset_ptr = &error_fdset; } @@ -195,10 +195,10 @@ lldb_private::Status SelectHelper::Select() { while (true) { using namespace std::chrono; // Setup out relative timeout based on the end time if we have one - if (m_end_time.hasValue()) { + if (m_end_time) { tv_ptr = &tv; - const auto remaining_dur = duration_cast<microseconds>( - m_end_time.getValue() - steady_clock::now()); + const auto remaining_dur = + duration_cast<microseconds>(*m_end_time - steady_clock::now()); if (remaining_dur.count() > 0) { // Wait for a specific amount of time const auto dur_secs = duration_cast<seconds>(remaining_dur); diff --git a/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp b/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp index eb4b824..14a0d17 100644 --- a/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp +++ b/lldb/unittests/Host/ConnectionFileDescriptorTest.cpp @@ -28,7 +28,7 @@ public: std::string uri(connection_file_descriptor.GetURI()); EXPECT_EQ((URI{"connect", ip, socket->GetRemotePortNumber(), "/"}), - URI::Parse(uri).getValue()); + *URI::Parse(uri)); } }; diff --git a/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp b/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp index d15b852..b80c44d 100644 --- a/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp +++ b/lldb/unittests/Process/gdb-remote/GDBRemoteCommunicationClientTest.cpp @@ -190,14 +190,14 @@ TEST_F(GDBRemoteCommunicationClientTest, GetModulesInfo) { R"("file_path":"/foo/bar.so","file_offset":0,"file_size":1234}]])"); auto result = async_result.get(); - ASSERT_TRUE(result.hasValue()); + ASSERT_TRUE(result.has_value()); ASSERT_EQ(1u, result->size()); - EXPECT_EQ("/foo/bar.so", result.getValue()[0].GetFileSpec().GetPath()); - EXPECT_EQ(triple, result.getValue()[0].GetArchitecture().GetTriple()); + EXPECT_EQ("/foo/bar.so", result.value()[0].GetFileSpec().GetPath()); + EXPECT_EQ(triple, result.value()[0].GetArchitecture().GetTriple()); EXPECT_EQ(UUID::fromData("@ABCDEFGHIJKLMNO", 16), - result.getValue()[0].GetUUID()); - EXPECT_EQ(0u, result.getValue()[0].GetObjectOffset()); - EXPECT_EQ(1234u, result.getValue()[0].GetObjectSize()); + result.value()[0].GetUUID()); + EXPECT_EQ(0u, result.value()[0].GetObjectOffset()); + EXPECT_EQ(1234u, result.value()[0].GetObjectSize()); } TEST_F(GDBRemoteCommunicationClientTest, GetModulesInfo_UUID20) { @@ -215,14 +215,14 @@ TEST_F(GDBRemoteCommunicationClientTest, GetModulesInfo_UUID20) { R"("file_path":"/foo/bar.so","file_offset":0,"file_size":1234}]])"); auto result = async_result.get(); - ASSERT_TRUE(result.hasValue()); + ASSERT_TRUE(result.has_value()); ASSERT_EQ(1u, result->size()); - EXPECT_EQ("/foo/bar.so", result.getValue()[0].GetFileSpec().GetPath()); - EXPECT_EQ(triple, result.getValue()[0].GetArchitecture().GetTriple()); + EXPECT_EQ("/foo/bar.so", result.value()[0].GetFileSpec().GetPath()); + EXPECT_EQ(triple, result.value()[0].GetArchitecture().GetTriple()); EXPECT_EQ(UUID::fromData("@ABCDEFGHIJKLMNOPQRS", 20), - result.getValue()[0].GetUUID()); - EXPECT_EQ(0u, result.getValue()[0].GetObjectOffset()); - EXPECT_EQ(1234u, result.getValue()[0].GetObjectSize()); + result.value()[0].GetUUID()); + EXPECT_EQ(0u, result.value()[0].GetObjectOffset()); + EXPECT_EQ(1234u, result.value()[0].GetObjectSize()); } TEST_F(GDBRemoteCommunicationClientTest, GetModulesInfoInvalidResponse) { diff --git a/lldb/unittests/Process/minidump/MinidumpParserTest.cpp b/lldb/unittests/Process/minidump/MinidumpParserTest.cpp index 95e2cf3..85a15b8 100644 --- a/lldb/unittests/Process/minidump/MinidumpParserTest.cpp +++ b/lldb/unittests/Process/minidump/MinidumpParserTest.cpp @@ -183,7 +183,7 @@ Streams: )"), llvm::Succeeded()); llvm::Optional<LinuxProcStatus> proc_status = parser->GetLinuxProcStatus(); - ASSERT_TRUE(proc_status.hasValue()); + ASSERT_TRUE(proc_status.has_value()); lldb::pid_t pid = proc_status->GetPid(); ASSERT_EQ(16001UL, pid); } @@ -218,8 +218,8 @@ Streams: )"), llvm::Succeeded()); llvm::Optional<lldb::pid_t> pid = parser->GetPid(); - ASSERT_TRUE(pid.hasValue()); - ASSERT_EQ(16001UL, pid.getValue()); + ASSERT_TRUE(pid.has_value()); + ASSERT_EQ(16001UL, *pid); } TEST_F(MinidumpParserTest, GetFilteredModuleList) { @@ -260,7 +260,7 @@ TEST_F(MinidumpParserTest, GetExceptionStream) { void check_mem_range_exists(MinidumpParser &parser, const uint64_t range_start, const uint64_t range_size) { llvm::Optional<minidump::Range> range = parser.FindMemoryRange(range_start); - ASSERT_TRUE(range.hasValue()) << "There is no range containing this address"; + ASSERT_TRUE(range.has_value()) << "There is no range containing this address"; EXPECT_EQ(range_start, range->start); EXPECT_EQ(range_start + range_size, range->start + range->range_ref.size()); } @@ -321,14 +321,14 @@ TEST_F(MinidumpParserTest, FindMemoryRangeWithFullMemoryMinidump) { SetUpData("fizzbuzz_wow64.dmp"); // There are a lot of ranges in the file, just testing with some of them - EXPECT_FALSE(parser->FindMemoryRange(0x00).hasValue()); - EXPECT_FALSE(parser->FindMemoryRange(0x2a).hasValue()); + EXPECT_FALSE(parser->FindMemoryRange(0x00).has_value()); + EXPECT_FALSE(parser->FindMemoryRange(0x2a).has_value()); check_mem_range_exists(*parser, 0x10000, 65536); // first range check_mem_range_exists(*parser, 0x40000, 4096); - EXPECT_FALSE(parser->FindMemoryRange(0x40000 + 4096).hasValue()); + EXPECT_FALSE(parser->FindMemoryRange(0x40000 + 4096).has_value()); check_mem_range_exists(*parser, 0x77c12000, 8192); check_mem_range_exists(*parser, 0x7ffe0000, 4096); // last range - EXPECT_FALSE(parser->FindMemoryRange(0x7ffe0000 + 4096).hasValue()); + EXPECT_FALSE(parser->FindMemoryRange(0x7ffe0000 + 4096).has_value()); } constexpr auto yes = MemoryRegionInfo::eYes; @@ -544,23 +544,23 @@ TEST_F(MinidumpParserTest, GetMiscInfoWindows) { const MinidumpMiscInfo *misc_info = parser->GetMiscInfo(); ASSERT_NE(nullptr, misc_info); llvm::Optional<lldb::pid_t> pid = misc_info->GetPid(); - ASSERT_TRUE(pid.hasValue()); - ASSERT_EQ(4440UL, pid.getValue()); + ASSERT_TRUE(pid.has_value()); + ASSERT_EQ(4440UL, *pid); } TEST_F(MinidumpParserTest, GetPidWindows) { SetUpData("fizzbuzz_no_heap.dmp"); llvm::Optional<lldb::pid_t> pid = parser->GetPid(); - ASSERT_TRUE(pid.hasValue()); - ASSERT_EQ(4440UL, pid.getValue()); + ASSERT_TRUE(pid.has_value()); + ASSERT_EQ(4440UL, *pid); } // wow64 TEST_F(MinidumpParserTest, GetPidWow64) { SetUpData("fizzbuzz_wow64.dmp"); llvm::Optional<lldb::pid_t> pid = parser->GetPid(); - ASSERT_TRUE(pid.hasValue()); - ASSERT_EQ(7836UL, pid.getValue()); + ASSERT_TRUE(pid.has_value()); + ASSERT_EQ(7836UL, *pid); } // Register tests diff --git a/lldb/unittests/Target/FindFileTest.cpp b/lldb/unittests/Target/FindFileTest.cpp index 77d374d..6715c34 100644 --- a/lldb/unittests/Target/FindFileTest.cpp +++ b/lldb/unittests/Target/FindFileTest.cpp @@ -56,7 +56,7 @@ static void TestFileFindings(const PathMappingList &map, llvm::Optional<FileSpec> remapped; EXPECT_TRUE(bool(remapped = map.FindFile(match.original))); - EXPECT_TRUE(FileSpec(remapped.getValue()).GetPath() == + EXPECT_TRUE(FileSpec(*remapped).GetPath() == ConstString(match.remapped).GetStringRef()); } } diff --git a/lldb/unittests/Utility/StringExtractorGDBRemoteTest.cpp b/lldb/unittests/Utility/StringExtractorGDBRemoteTest.cpp index 88362c0..922167c 100644 --- a/lldb/unittests/Utility/StringExtractorGDBRemoteTest.cpp +++ b/lldb/unittests/Utility/StringExtractorGDBRemoteTest.cpp @@ -109,77 +109,77 @@ TEST(StringExtractorGDBRemoteTest, GetPidTid) { // pure thread id ex.Reset("-1"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(100, StringExtractorGDBRemote::AllThreads)); ex.Reset("1234"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), ::testing::Pair(100, 0x1234ULL)); + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(100, 0x1234ULL)); ex.Reset("123456789ABCDEF0"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(100, 0x123456789ABCDEF0ULL)); // pure process id ex.Reset("p-1"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(StringExtractorGDBRemote::AllProcesses, StringExtractorGDBRemote::AllThreads)); ex.Reset("p1234"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x1234ULL, StringExtractorGDBRemote::AllThreads)); ex.Reset("p123456789ABCDEF0"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x123456789ABCDEF0ULL, StringExtractorGDBRemote::AllThreads)); ex.Reset("pFFFFFFFFFFFFFFFF"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(StringExtractorGDBRemote::AllProcesses, StringExtractorGDBRemote::AllThreads)); // combined thread id + process id ex.Reset("p-1.-1"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(StringExtractorGDBRemote::AllProcesses, StringExtractorGDBRemote::AllThreads)); ex.Reset("p1234.-1"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x1234ULL, StringExtractorGDBRemote::AllThreads)); ex.Reset("p1234.123456789ABCDEF0"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x1234ULL, 0x123456789ABCDEF0ULL)); ex.Reset("p123456789ABCDEF0.-1"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x123456789ABCDEF0ULL, StringExtractorGDBRemote::AllThreads)); ex.Reset("p123456789ABCDEF0.1234"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x123456789ABCDEF0ULL, 0x1234ULL)); ex.Reset("p123456789ABCDEF0.123456789ABCDEF0"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x123456789ABCDEF0ULL, 0x123456789ABCDEF0ULL)); ex.Reset("p123456789ABCDEF0.123456789ABCDEF0"); - EXPECT_THAT(ex.GetPidTid(100).getValue(), + EXPECT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x123456789ABCDEF0ULL, 0x123456789ABCDEF0ULL)); } TEST(StringExtractorGDBRemoteTest, GetPidTidMultipleValues) { StringExtractorGDBRemote ex("1234;p12;p1234.-1"); - ASSERT_THAT(ex.GetPidTid(100).getValue(), ::testing::Pair(100, 0x1234ULL)); + ASSERT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(100, 0x1234ULL)); ASSERT_EQ(ex.GetChar(), ';'); - ASSERT_THAT(ex.GetPidTid(100).getValue(), + ASSERT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x12ULL, StringExtractorGDBRemote::AllThreads)); ASSERT_EQ(ex.GetChar(), ';'); - ASSERT_THAT(ex.GetPidTid(100).getValue(), + ASSERT_THAT(ex.GetPidTid(100).value(), ::testing::Pair(0x1234ULL, StringExtractorGDBRemote::AllThreads)); } diff --git a/lldb/unittests/tools/lldb-server/tests/TestClient.cpp b/lldb/unittests/tools/lldb-server/tests/TestClient.cpp index 463dd22..f65c33e 100644 --- a/lldb/unittests/tools/lldb-server/tests/TestClient.cpp +++ b/lldb/unittests/tools/lldb-server/tests/TestClient.cpp @@ -251,7 +251,7 @@ Error TestClient::queryProcess() { } Error TestClient::Continue(StringRef message) { - assert(m_process_info.hasValue()); + assert(m_process_info.has_value()); auto StopReplyOr = SendMessage<StopReply>( message, m_process_info->GetEndian(), m_register_infos); diff --git a/llvm/include/llvm/ADT/Optional.h b/llvm/include/llvm/ADT/Optional.h index d1615d9..b2ebd17 100644 --- a/llvm/include/llvm/ADT/Optional.h +++ b/llvm/include/llvm/ADT/Optional.h @@ -92,32 +92,40 @@ public: } constexpr bool has_value() const noexcept { return hasVal; } +#if 0 constexpr bool hasValue() const noexcept { return hasVal; } +#endif T &value() &noexcept { assert(hasVal); return val; } +#if 0 T &getValue() &noexcept { assert(hasVal); return val; } +#endif constexpr T const &value() const &noexcept { assert(hasVal); return val; } +#if 0 constexpr T const &getValue() const &noexcept { assert(hasVal); return val; } +#endif T &&value() &&noexcept { assert(hasVal); return std::move(val); } +#if 0 T &&getValue() &&noexcept { assert(hasVal); return std::move(val); } +#endif template <class... Args> void emplace(Args &&...args) { reset(); @@ -203,32 +211,40 @@ public: } constexpr bool has_value() const noexcept { return hasVal; } +#if 0 constexpr bool hasValue() const noexcept { return hasVal; } +#endif T &value() &noexcept { assert(hasVal); return val; } +#if 0 T &getValue() &noexcept { assert(hasVal); return val; } +#endif constexpr T const &value() const &noexcept { assert(hasVal); return val; } +#if 0 constexpr T const &getValue() const &noexcept { assert(hasVal); return val; } +#endif T &&value() &&noexcept { assert(hasVal); return std::move(val); } +#if 0 T &&getValue() &&noexcept { assert(hasVal); return std::move(val); } +#endif template <class... Args> void emplace(Args &&...args) { reset(); @@ -303,13 +319,19 @@ public: constexpr const T *getPointer() const { return &Storage.value(); } T *getPointer() { return &Storage.value(); } constexpr const T &value() const & { return Storage.value(); } +#if 0 constexpr const T &getValue() const & { return Storage.value(); } +#endif T &value() & { return Storage.value(); } +#if 0 T &getValue() & { return Storage.value(); } +#endif constexpr explicit operator bool() const { return has_value(); } constexpr bool has_value() const { return Storage.has_value(); } +#if 0 constexpr bool hasValue() const { return Storage.has_value(); } +#endif constexpr const T *operator->() const { return getPointer(); } T *operator->() { return getPointer(); } constexpr const T &operator*() const & { return value(); } @@ -331,7 +353,9 @@ public: } T &&value() && { return std::move(Storage.value()); } +#if 0 T &&getValue() && { return std::move(Storage.value()); } +#endif T &&operator*() && { return std::move(Storage.value()); } template <typename U> T value_or(U &&alt) && { diff --git a/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h b/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h index d8e524d7..7208f11 100644 --- a/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h +++ b/llvm/include/llvm/Analysis/BlockFrequencyInfoImpl.h @@ -1277,10 +1277,10 @@ bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &Loop) { continue; } LLVM_DEBUG(dbgs() << getBlockName(HeaderNode) - << " has irr loop header weight " - << HeaderWeight.getValue() << "\n"); + << " has irr loop header weight " << *HeaderWeight + << "\n"); NumHeadersWithWeight++; - uint64_t HeaderWeightValue = HeaderWeight.getValue(); + uint64_t HeaderWeightValue = *HeaderWeight; if (!MinHeaderWeight || HeaderWeightValue < MinHeaderWeight) MinHeaderWeight = HeaderWeightValue; if (HeaderWeightValue) { @@ -1732,10 +1732,10 @@ raw_ostream &BlockFrequencyInfoImpl<BT>::print(raw_ostream &OS) const { if (Optional<uint64_t> ProfileCount = BlockFrequencyInfoImplBase::getBlockProfileCount( F->getFunction(), getNode(&BB))) - OS << ", count = " << ProfileCount.getValue(); + OS << ", count = " << *ProfileCount; if (Optional<uint64_t> IrrLoopHeaderWeight = BB.getIrrLoopHeaderWeight()) - OS << ", irr_loop_header_weight = " << IrrLoopHeaderWeight.getValue(); + OS << ", irr_loop_header_weight = " << *IrrLoopHeaderWeight; OS << "\n"; } diff --git a/llvm/include/llvm/Analysis/VectorUtils.h b/llvm/include/llvm/Analysis/VectorUtils.h index df460cb..6e4c468 100644 --- a/llvm/include/llvm/Analysis/VectorUtils.h +++ b/llvm/include/llvm/Analysis/VectorUtils.h @@ -236,10 +236,10 @@ class VFDatabase { // ensuring that the variant described in the attribute has a // corresponding definition or declaration of the vector // function in the Module M. - if (Shape.hasValue() && (Shape.getValue().ScalarName == ScalarName)) { - assert(CI.getModule()->getFunction(Shape.getValue().VectorName) && + if (Shape && (Shape->ScalarName == ScalarName)) { + assert(CI.getModule()->getFunction(Shape->VectorName) && "Vector function is missing."); - Mappings.push_back(Shape.getValue()); + Mappings.push_back(*Shape); } } } diff --git a/llvm/include/llvm/Bitstream/BitstreamWriter.h b/llvm/include/llvm/Bitstream/BitstreamWriter.h index be6bab5..3660ce5 100644 --- a/llvm/include/llvm/Bitstream/BitstreamWriter.h +++ b/llvm/include/llvm/Bitstream/BitstreamWriter.h @@ -386,12 +386,12 @@ private: const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++); if (Op.isLiteral()) - EmitAbbreviatedLiteral(Op, Code.getValue()); + EmitAbbreviatedLiteral(Op, *Code); else { assert(Op.getEncoding() != BitCodeAbbrevOp::Array && Op.getEncoding() != BitCodeAbbrevOp::Blob && "Expected literal or scalar"); - EmitAbbreviatedField(Op, Code.getValue()); + EmitAbbreviatedField(Op, *Code); } } diff --git a/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h b/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h index fa6f904..9e9fd65 100644 --- a/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h +++ b/llvm/include/llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h @@ -674,8 +674,8 @@ bool InstructionSelector::executeMatchTable( ComplexRendererFns Renderer = (ISel.*ISelInfo.ComplexPredicates[ComplexPredicateID])( State.MIs[InsnID]->getOperand(OpIdx)); - if (Renderer.hasValue()) - State.Renderers[RendererID] = Renderer.getValue(); + if (Renderer) + State.Renderers[RendererID] = *Renderer; else if (handleReject() == RejectAndGiveUp) return false; diff --git a/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h b/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h index a41b2fe..fb48f7f 100644 --- a/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h +++ b/llvm/include/llvm/DebugInfo/GSYM/FunctionInfo.h @@ -198,8 +198,8 @@ inline bool operator<(const FunctionInfo &LHS, const FunctionInfo &RHS) { return LHS.Range < RHS.Range; // Then sort by inline - if (LHS.Inline.hasValue() != RHS.Inline.hasValue()) - return RHS.Inline.hasValue(); + if (LHS.Inline.has_value() != RHS.Inline.has_value()) + return RHS.Inline.has_value(); return LHS.OptLineTable < RHS.OptLineTable; } diff --git a/llvm/include/llvm/IR/IRBuilder.h b/llvm/include/llvm/IR/IRBuilder.h index 2b387db..1747826 100644 --- a/llvm/include/llvm/IR/IRBuilder.h +++ b/llvm/include/llvm/IR/IRBuilder.h @@ -1168,12 +1168,12 @@ private: Value *getConstrainedFPRounding(Optional<RoundingMode> Rounding) { RoundingMode UseRounding = DefaultConstrainedRounding; - if (Rounding.hasValue()) - UseRounding = Rounding.getValue(); + if (Rounding) + UseRounding = *Rounding; Optional<StringRef> RoundingStr = convertRoundingModeToStr(UseRounding); - assert(RoundingStr.hasValue() && "Garbage strict rounding mode!"); - auto *RoundingMDS = MDString::get(Context, RoundingStr.getValue()); + assert(RoundingStr && "Garbage strict rounding mode!"); + auto *RoundingMDS = MDString::get(Context, *RoundingStr); return MetadataAsValue::get(Context, RoundingMDS); } @@ -1181,12 +1181,12 @@ private: Value *getConstrainedFPExcept(Optional<fp::ExceptionBehavior> Except) { fp::ExceptionBehavior UseExcept = DefaultConstrainedExcept; - if (Except.hasValue()) - UseExcept = Except.getValue(); + if (Except) + UseExcept = *Except; Optional<StringRef> ExceptStr = convertExceptionBehaviorToStr(UseExcept); - assert(ExceptStr.hasValue() && "Garbage strict exception behavior!"); - auto *ExceptMDS = MDString::get(Context, ExceptStr.getValue()); + assert(ExceptStr && "Garbage strict exception behavior!"); + auto *ExceptMDS = MDString::get(Context, *ExceptStr); return MetadataAsValue::get(Context, ExceptMDS); } diff --git a/llvm/include/llvm/MC/MCDwarf.h b/llvm/include/llvm/MC/MCDwarf.h index d0eb06e..8b2ae84 100644 --- a/llvm/include/llvm/MC/MCDwarf.h +++ b/llvm/include/llvm/MC/MCDwarf.h @@ -296,8 +296,8 @@ public: RootFile.DirIndex = 0; RootFile.Checksum = Checksum; RootFile.Source = Source; - trackMD5Usage(Checksum.hasValue()); - HasSource = Source.hasValue(); + trackMD5Usage(Checksum.has_value()); + HasSource = Source.has_value(); } void resetFileTable() { @@ -374,8 +374,8 @@ public: Header.RootFile.DirIndex = 0; Header.RootFile.Checksum = Checksum; Header.RootFile.Source = Source; - Header.trackMD5Usage(Checksum.hasValue()); - Header.HasSource = Source.hasValue(); + Header.trackMD5Usage(Checksum.has_value()); + Header.HasSource = Source.has_value(); } void resetFileTable() { Header.resetFileTable(); } diff --git a/llvm/include/llvm/MC/MCSectionXCOFF.h b/llvm/include/llvm/MC/MCSectionXCOFF.h index 77f0b28..1b68d27 100644 --- a/llvm/include/llvm/MC/MCSectionXCOFF.h +++ b/llvm/include/llvm/MC/MCSectionXCOFF.h @@ -111,8 +111,8 @@ public: bool isVirtualSection() const override; StringRef getSymbolTableName() const { return SymbolTableName; } bool isMultiSymbolsAllowed() const { return MultiSymbolsAllowed; } - bool isCsect() const { return CsectProp.hasValue(); } - bool isDwarfSect() const { return DwarfSubtypeFlags.hasValue(); } + bool isCsect() const { return CsectProp.has_value(); } + bool isDwarfSect() const { return DwarfSubtypeFlags.has_value(); } Optional<XCOFF::DwarfSectionSubtypeFlags> getDwarfSubtypeFlags() const { return DwarfSubtypeFlags; } diff --git a/llvm/include/llvm/MC/MCSymbolWasm.h b/llvm/include/llvm/MC/MCSymbolWasm.h index 5a4852e..6d08685 100644 --- a/llvm/include/llvm/MC/MCSymbolWasm.h +++ b/llvm/include/llvm/MC/MCSymbolWasm.h @@ -86,10 +86,10 @@ public: bool omitFromLinkingSection() const { return OmitFromLinkingSection; } void setOmitFromLinkingSection() { OmitFromLinkingSection = true; } - bool hasImportModule() const { return ImportModule.hasValue(); } + bool hasImportModule() const { return ImportModule.has_value(); } StringRef getImportModule() const { - if (ImportModule.hasValue()) - return ImportModule.getValue(); + if (ImportModule) + return *ImportModule; // Use a default module name of "env" for now, for compatibility with // existing tools. // TODO(sbc): Find a way to specify a default value in the object format @@ -98,16 +98,16 @@ public: } void setImportModule(StringRef Name) { ImportModule = Name; } - bool hasImportName() const { return ImportName.hasValue(); } + bool hasImportName() const { return ImportName.has_value(); } StringRef getImportName() const { - if (ImportName.hasValue()) - return ImportName.getValue(); + if (ImportName) + return *ImportName; return getName(); } void setImportName(StringRef Name) { ImportName = Name; } - bool hasExportName() const { return ExportName.hasValue(); } - StringRef getExportName() const { return ExportName.getValue(); } + bool hasExportName() const { return ExportName.has_value(); } + StringRef getExportName() const { return *ExportName; } void setExportName(StringRef Name) { ExportName = Name; } bool isFunctionTable() const { @@ -129,15 +129,15 @@ public: void setSignature(wasm::WasmSignature *Sig) { Signature = Sig; } const wasm::WasmGlobalType &getGlobalType() const { - assert(GlobalType.hasValue()); - return GlobalType.getValue(); + assert(GlobalType.has_value()); + return *GlobalType; } void setGlobalType(wasm::WasmGlobalType GT) { GlobalType = GT; } - bool hasTableType() const { return TableType.hasValue(); } + bool hasTableType() const { return TableType.has_value(); } const wasm::WasmTableType &getTableType() const { assert(hasTableType()); - return TableType.getValue(); + return *TableType; } void setTableType(wasm::WasmTableType TT) { TableType = TT; } void setTableType(wasm::ValType VT) { diff --git a/llvm/include/llvm/MC/MCSymbolXCOFF.h b/llvm/include/llvm/MC/MCSymbolXCOFF.h index 752e1e7..4e21d39 100644 --- a/llvm/include/llvm/MC/MCSymbolXCOFF.h +++ b/llvm/include/llvm/MC/MCSymbolXCOFF.h @@ -39,9 +39,8 @@ public: }; XCOFF::StorageClass getStorageClass() const { - assert(StorageClass.hasValue() && - "StorageClass not set on XCOFF MCSymbol."); - return StorageClass.getValue(); + assert(StorageClass && "StorageClass not set on XCOFF MCSymbol."); + return *StorageClass; } StringRef getUnqualifiedName() const { return getUnqualifiedName(getName()); } diff --git a/llvm/include/llvm/ObjectYAML/ELFYAML.h b/llvm/include/llvm/ObjectYAML/ELFYAML.h index faff482..95bf523 100644 --- a/llvm/include/llvm/ObjectYAML/ELFYAML.h +++ b/llvm/include/llvm/ObjectYAML/ELFYAML.h @@ -433,10 +433,10 @@ struct GnuHashSection : Section { GnuHashSection() : Section(ChunkKind::GnuHash) {} std::vector<std::pair<StringRef, bool>> getEntries() const override { - return {{"Header", Header.hasValue()}, - {"BloomFilter", BloomFilter.hasValue()}, - {"HashBuckets", HashBuckets.hasValue()}, - {"HashValues", HashValues.hasValue()}}; + return {{"Header", Header.has_value()}, + {"BloomFilter", BloomFilter.has_value()}, + {"HashBuckets", HashBuckets.has_value()}, + {"HashValues", HashValues.has_value()}}; }; static bool classof(const Chunk *S) { return S->Kind == ChunkKind::GnuHash; } diff --git a/llvm/include/llvm/Support/Casting.h b/llvm/include/llvm/Support/Casting.h index 21c981a..7037cbf 100644 --- a/llvm/include/llvm/Support/Casting.h +++ b/llvm/include/llvm/Support/Casting.h @@ -637,10 +637,8 @@ template <typename T, typename Enable = void> struct ValueIsPresent { // Optional provides its own way to check if something is present. template <typename T> struct ValueIsPresent<Optional<T>> { using UnwrappedType = T; - static inline bool isPresent(const Optional<T> &t) { return t.hasValue(); } - static inline decltype(auto) unwrapValue(Optional<T> &t) { - return t.getValue(); - } + static inline bool isPresent(const Optional<T> &t) { return t.has_value(); } + static inline decltype(auto) unwrapValue(Optional<T> &t) { return *t; } }; // If something is "nullable" then we just compare it to nullptr to see if it diff --git a/llvm/include/llvm/Support/Error.h b/llvm/include/llvm/Support/Error.h index 80a5212..316e5dc 100644 --- a/llvm/include/llvm/Support/Error.h +++ b/llvm/include/llvm/Support/Error.h @@ -1269,8 +1269,8 @@ public: void log(raw_ostream &OS) const override { assert(Err && "Trying to log after takeError()."); OS << "'" << FileName << "': "; - if (Line.hasValue()) - OS << "line " << Line.getValue() << ": "; + if (Line) + OS << "line " << *Line << ": "; Err->log(OS); } diff --git a/llvm/include/llvm/Support/YAMLTraits.h b/llvm/include/llvm/Support/YAMLTraits.h index dfe9b1b..8ade9b1 100644 --- a/llvm/include/llvm/Support/YAMLTraits.h +++ b/llvm/include/llvm/Support/YAMLTraits.h @@ -1668,14 +1668,13 @@ template <typename T, typename Context> void IO::processKeyWithDefault(const char *Key, Optional<T> &Val, const Optional<T> &DefaultValue, bool Required, Context &Ctx) { - assert(DefaultValue.hasValue() == false && - "Optional<T> shouldn't have a value!"); + assert(!DefaultValue && "Optional<T> shouldn't have a value!"); void *SaveInfo; bool UseDefault = true; - const bool sameAsDefault = outputting() && !Val.hasValue(); - if (!outputting() && !Val.hasValue()) + const bool sameAsDefault = outputting() && !Val; + if (!outputting() && !Val) Val = T(); - if (Val.hasValue() && + if (Val && this->preflightKey(Key, Required, sameAsDefault, UseDefault, SaveInfo)) { // When reading an Optional<X> key from a YAML description, we allow the diff --git a/llvm/include/llvm/Transforms/IPO/Attributor.h b/llvm/include/llvm/Transforms/IPO/Attributor.h index 6aa19b0..17e2969 100644 --- a/llvm/include/llvm/Transforms/IPO/Attributor.h +++ b/llvm/include/llvm/Transforms/IPO/Attributor.h @@ -4884,12 +4884,10 @@ struct AAPointerInfo : public AbstractAttribute { Instruction *getRemoteInst() const { return RemoteI; } /// Return true if the value written is not known yet. - bool isWrittenValueYetUndetermined() const { return !Content.hasValue(); } + bool isWrittenValueYetUndetermined() const { return !Content; } /// Return true if the value written cannot be determined at all. - bool isWrittenValueUnknown() const { - return Content.hasValue() && !*Content; - } + bool isWrittenValueUnknown() const { return Content && !*Content; } /// Return the type associated with the access, if known. Type *getType() const { return Ty; } diff --git a/llvm/lib/Analysis/BranchProbabilityInfo.cpp b/llvm/lib/Analysis/BranchProbabilityInfo.cpp index 1d88042..2bca424 100644 --- a/llvm/lib/Analysis/BranchProbabilityInfo.cpp +++ b/llvm/lib/Analysis/BranchProbabilityInfo.cpp @@ -826,9 +826,8 @@ void BranchProbabilityInfo::computeEestimateBlockWeight( if (auto BBWeight = getInitialEstimatedBlockWeight(BB)) // If we were able to find estimated weight for the block set it to this // block and propagate up the IR. - propagateEstimatedBlockWeight(getLoopBlock(BB), DT, PDT, - BBWeight.getValue(), BlockWorkList, - LoopWorkList); + propagateEstimatedBlockWeight(getLoopBlock(BB), DT, PDT, *BBWeight, + BlockWorkList, LoopWorkList); // BlockWorklist/LoopWorkList contains blocks/loops with at least one // successor/exit having estimated weight. Try to propagate weight to such diff --git a/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp b/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp index 1216d03..602a018 100644 --- a/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp +++ b/llvm/lib/Analysis/CFLAndersAliasAnalysis.cpp @@ -831,14 +831,14 @@ CFLAndersAAResult::ensureCached(const Function &Fn) { scan(Fn); Iter = Cache.find(&Fn); assert(Iter != Cache.end()); - assert(Iter->second.hasValue()); + assert(Iter->second); } return Iter->second; } const AliasSummary *CFLAndersAAResult::getAliasSummary(const Function &Fn) { auto &FunInfo = ensureCached(Fn); - if (FunInfo.hasValue()) + if (FunInfo) return &FunInfo->getAliasSummary(); else return nullptr; diff --git a/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp b/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp index b831a59..f92869c 100644 --- a/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp +++ b/llvm/lib/Analysis/CFLSteensAliasAnalysis.cpp @@ -250,14 +250,14 @@ CFLSteensAAResult::ensureCached(Function *Fn) { scan(Fn); Iter = Cache.find(Fn); assert(Iter != Cache.end()); - assert(Iter->second.hasValue()); + assert(Iter->second); } return Iter->second; } const AliasSummary *CFLSteensAAResult::getAliasSummary(Function &Fn) { auto &FunInfo = ensureCached(&Fn); - if (FunInfo.hasValue()) + if (FunInfo) return &FunInfo->getAliasSummary(); else return nullptr; @@ -293,15 +293,15 @@ AliasResult CFLSteensAAResult::query(const MemoryLocation &LocA, assert(Fn != nullptr); auto &MaybeInfo = ensureCached(Fn); - assert(MaybeInfo.hasValue()); + assert(MaybeInfo); auto &Sets = MaybeInfo->getStratifiedSets(); auto MaybeA = Sets.find(InstantiatedValue{ValA, 0}); - if (!MaybeA.hasValue()) + if (!MaybeA) return AliasResult::MayAlias; auto MaybeB = Sets.find(InstantiatedValue{ValB, 0}); - if (!MaybeB.hasValue()) + if (!MaybeB) return AliasResult::MayAlias; auto SetA = *MaybeA; diff --git a/llvm/lib/Analysis/IRSimilarityIdentifier.cpp b/llvm/lib/Analysis/IRSimilarityIdentifier.cpp index c945050..81aa854 100644 --- a/llvm/lib/Analysis/IRSimilarityIdentifier.cpp +++ b/llvm/lib/Analysis/IRSimilarityIdentifier.cpp @@ -183,9 +183,9 @@ CmpInst::Predicate IRInstructionData::getPredicate() const { assert(isa<CmpInst>(Inst) && "Can only get a predicate from a compare instruction"); - if (RevisedPredicate.hasValue()) - return RevisedPredicate.getValue(); - + if (RevisedPredicate) + return *RevisedPredicate; + return cast<CmpInst>(Inst)->getPredicate(); } diff --git a/llvm/lib/Analysis/InlineCost.cpp b/llvm/lib/Analysis/InlineCost.cpp index 63fe651..f2dcaa8 100644 --- a/llvm/lib/Analysis/InlineCost.cpp +++ b/llvm/lib/Analysis/InlineCost.cpp @@ -703,8 +703,8 @@ class InlineCostCallAnalyzer final : public CallAnalyzer { BlockFrequencyInfo *BFI = &(GetBFI(F)); assert(BFI && "BFI must be available"); auto ProfileCount = BFI->getBlockProfileCount(BB); - assert(ProfileCount.hasValue()); - if (ProfileCount.getValue() == 0) + assert(ProfileCount); + if (*ProfileCount == 0) ColdSize += Cost - CostAtBBStart; } @@ -828,14 +828,14 @@ class InlineCostCallAnalyzer final : public CallAnalyzer { } auto ProfileCount = CalleeBFI->getBlockProfileCount(&BB); - assert(ProfileCount.hasValue()); - CurrentSavings *= ProfileCount.getValue(); + assert(ProfileCount); + CurrentSavings *= *ProfileCount; CycleSavings += CurrentSavings; } // Compute the cycle savings per call. auto EntryProfileCount = F.getEntryCount(); - assert(EntryProfileCount.hasValue() && EntryProfileCount->getCount()); + assert(EntryProfileCount && EntryProfileCount->getCount()); auto EntryCount = EntryProfileCount->getCount(); CycleSavings += EntryCount / 2; CycleSavings = CycleSavings.udiv(EntryCount); @@ -1800,12 +1800,12 @@ void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) { // return min(A, B) if B is valid. auto MinIfValid = [](int A, Optional<int> B) { - return B ? std::min(A, B.getValue()) : A; + return B ? std::min(A, *B) : A; }; // return max(A, B) if B is valid. auto MaxIfValid = [](int A, Optional<int> B) { - return B ? std::max(A, B.getValue()) : A; + return B ? std::max(A, *B) : A; }; // Various bonus percentages. These are multiplied by Threshold to get the diff --git a/llvm/lib/Analysis/InstructionSimplify.cpp b/llvm/lib/Analysis/InstructionSimplify.cpp index 07e3392..a7aec39 100644 --- a/llvm/lib/Analysis/InstructionSimplify.cpp +++ b/llvm/lib/Analysis/InstructionSimplify.cpp @@ -6123,9 +6123,9 @@ static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) { Value *Op1 = Call->getArgOperand(1); Value *Op2 = Call->getArgOperand(2); auto *FPI = cast<ConstrainedFPIntrinsic>(Call); - if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, - FPI->getExceptionBehavior().getValue(), - FPI->getRoundingMode().getValue())) + if (Value *V = + simplifyFPOp({Op0, Op1, Op2}, {}, Q, *FPI->getExceptionBehavior(), + *FPI->getRoundingMode())) return V; return nullptr; } @@ -6189,38 +6189,33 @@ static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) { } case Intrinsic::experimental_constrained_fadd: { auto *FPI = cast<ConstrainedFPIntrinsic>(Call); - return simplifyFAddInst(FPI->getArgOperand(0), FPI->getArgOperand(1), - FPI->getFastMathFlags(), Q, - FPI->getExceptionBehavior().getValue(), - FPI->getRoundingMode().getValue()); + return simplifyFAddInst( + FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(), + Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode()); } case Intrinsic::experimental_constrained_fsub: { auto *FPI = cast<ConstrainedFPIntrinsic>(Call); - return simplifyFSubInst(FPI->getArgOperand(0), FPI->getArgOperand(1), - FPI->getFastMathFlags(), Q, - FPI->getExceptionBehavior().getValue(), - FPI->getRoundingMode().getValue()); + return simplifyFSubInst( + FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(), + Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode()); } case Intrinsic::experimental_constrained_fmul: { auto *FPI = cast<ConstrainedFPIntrinsic>(Call); - return simplifyFMulInst(FPI->getArgOperand(0), FPI->getArgOperand(1), - FPI->getFastMathFlags(), Q, - FPI->getExceptionBehavior().getValue(), - FPI->getRoundingMode().getValue()); + return simplifyFMulInst( + FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(), + Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode()); } case Intrinsic::experimental_constrained_fdiv: { auto *FPI = cast<ConstrainedFPIntrinsic>(Call); - return simplifyFDivInst(FPI->getArgOperand(0), FPI->getArgOperand(1), - FPI->getFastMathFlags(), Q, - FPI->getExceptionBehavior().getValue(), - FPI->getRoundingMode().getValue()); + return simplifyFDivInst( + FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(), + Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode()); } case Intrinsic::experimental_constrained_frem: { auto *FPI = cast<ConstrainedFPIntrinsic>(Call); - return simplifyFRemInst(FPI->getArgOperand(0), FPI->getArgOperand(1), - FPI->getFastMathFlags(), Q, - FPI->getExceptionBehavior().getValue(), - FPI->getRoundingMode().getValue()); + return simplifyFRemInst( + FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(), + Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode()); } default: return nullptr; diff --git a/llvm/lib/Analysis/LazyValueInfo.cpp b/llvm/lib/Analysis/LazyValueInfo.cpp index 5803c3d..e82c3ae 100644 --- a/llvm/lib/Analysis/LazyValueInfo.cpp +++ b/llvm/lib/Analysis/LazyValueInfo.cpp @@ -918,10 +918,10 @@ Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueCast( // transfer rule on the full set since we may be able to locally infer // interesting facts. Optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB); - if (!LHSRes.hasValue()) + if (!LHSRes) // More work to do before applying this transfer rule. return None; - const ConstantRange &LHSRange = LHSRes.getValue(); + const ConstantRange &LHSRange = *LHSRes; const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth(); @@ -946,8 +946,8 @@ Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOpImpl( // More work to do before applying this transfer rule. return None; - const ConstantRange &LHSRange = LHSRes.getValue(); - const ConstantRange &RHSRange = RHSRes.getValue(); + const ConstantRange &LHSRange = *LHSRes; + const ConstantRange &RHSRange = *RHSRes; return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange)); } diff --git a/llvm/lib/Analysis/LoopCacheAnalysis.cpp b/llvm/lib/Analysis/LoopCacheAnalysis.cpp index 002e993..2cbf1f7 100644 --- a/llvm/lib/Analysis/LoopCacheAnalysis.cpp +++ b/llvm/lib/Analysis/LoopCacheAnalysis.cpp @@ -645,8 +645,8 @@ bool CacheCost::populateReferenceGroups(ReferenceGroupsTy &RefGroups) const { Optional<bool> HasSpacialReuse = R->hasSpacialReuse(Representative, CLS, AA); - if ((HasTemporalReuse.hasValue() && *HasTemporalReuse) || - (HasSpacialReuse.hasValue() && *HasSpacialReuse)) { + if ((HasTemporalReuse && *HasTemporalReuse) || + (HasSpacialReuse && *HasSpacialReuse)) { RefGroup.push_back(std::move(R)); Added = true; break; diff --git a/llvm/lib/Analysis/MemoryBuiltins.cpp b/llvm/lib/Analysis/MemoryBuiltins.cpp index 3c0e494..ff303ce 100644 --- a/llvm/lib/Analysis/MemoryBuiltins.cpp +++ b/llvm/lib/Analysis/MemoryBuiltins.cpp @@ -270,54 +270,53 @@ static Optional<AllocFnsTy> getAllocationSize(const Value *V, /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup /// like). bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI) { - return getAllocationData(V, AnyAlloc, TLI).hasValue(); + return getAllocationData(V, AnyAlloc, TLI).has_value(); } bool llvm::isAllocationFn( const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI) { - return getAllocationData(V, AnyAlloc, GetTLI).hasValue(); + return getAllocationData(V, AnyAlloc, GetTLI).has_value(); } /// Tests if a value is a call or invoke to a library function that /// allocates uninitialized memory (such as malloc). static bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) { - return getAllocationData(V, MallocOrOpNewLike, TLI).hasValue(); + return getAllocationData(V, MallocOrOpNewLike, TLI).has_value(); } /// Tests if a value is a call or invoke to a library function that /// allocates uninitialized memory with alignment (such as aligned_alloc). static bool isAlignedAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) { - return getAllocationData(V, AlignedAllocLike, TLI) - .hasValue(); + return getAllocationData(V, AlignedAllocLike, TLI).has_value(); } /// Tests if a value is a call or invoke to a library function that /// allocates zero-filled memory (such as calloc). static bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) { - return getAllocationData(V, CallocLike, TLI).hasValue(); + return getAllocationData(V, CallocLike, TLI).has_value(); } /// Tests if a value is a call or invoke to a library function that /// allocates memory similar to malloc or calloc. bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) { - return getAllocationData(V, MallocOrCallocLike, TLI).hasValue(); + return getAllocationData(V, MallocOrCallocLike, TLI).has_value(); } /// Tests if a value is a call or invoke to a library function that /// allocates memory (either malloc, calloc, or strdup like). bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) { - return getAllocationData(V, AllocLike, TLI).hasValue(); + return getAllocationData(V, AllocLike, TLI).has_value(); } /// Tests if a value is a call or invoke to a library function that /// reallocates memory (e.g., realloc). bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) { - return getAllocationData(V, ReallocLike, TLI).hasValue(); + return getAllocationData(V, ReallocLike, TLI).has_value(); } /// Tests if a functions is a call or invoke to a library function that /// reallocates memory (e.g., realloc). bool llvm::isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI) { - return getAllocationDataForFunction(F, ReallocLike, TLI).hasValue(); + return getAllocationDataForFunction(F, ReallocLike, TLI).has_value(); } bool llvm::isAllocRemovable(const CallBase *CB, const TargetLibraryInfo *TLI) { @@ -501,18 +500,18 @@ Optional<StringRef> llvm::getAllocationFamily(const Value *I, if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn)) return None; const auto AllocData = getAllocationDataForFunction(Callee, AnyAlloc, TLI); - if (AllocData.hasValue()) - return mangledNameForMallocFamily(AllocData.getValue().Family); + if (AllocData) + return mangledNameForMallocFamily(AllocData->Family); const auto FreeData = getFreeFunctionDataForFunction(Callee, TLIFn); - if (FreeData.hasValue()) - return mangledNameForMallocFamily(FreeData.getValue().Family); + if (FreeData) + return mangledNameForMallocFamily(FreeData->Family); return None; } /// isLibFreeFunction - Returns true if the function is a builtin free() bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) { Optional<FreeFnsTy> FnData = getFreeFunctionDataForFunction(F, TLIFn); - if (!FnData.hasValue()) + if (!FnData) return false; // Check free prototype. diff --git a/llvm/lib/Analysis/MemorySSA.cpp b/llvm/lib/Analysis/MemorySSA.cpp index f63898b..76371b8 100644 --- a/llvm/lib/Analysis/MemorySSA.cpp +++ b/llvm/lib/Analysis/MemorySSA.cpp @@ -749,9 +749,9 @@ template <class AliasAnalysisType> class ClobberWalker { } bool operator==(const generic_def_path_iterator &O) const { - if (N.hasValue() != O.N.hasValue()) + if (N.has_value() != O.N.has_value()) return false; - return !N.hasValue() || *N == *O.N; + return !N || *N == *O.N; } private: diff --git a/llvm/lib/Analysis/MustExecute.cpp b/llvm/lib/Analysis/MustExecute.cpp index c785b50..8dbce26 100644 --- a/llvm/lib/Analysis/MustExecute.cpp +++ b/llvm/lib/Analysis/MustExecute.cpp @@ -491,9 +491,9 @@ template <typename K, typename V, typename FnTy, typename... ArgsTy> static V getOrCreateCachedOptional(K Key, DenseMap<K, Optional<V>> &Map, FnTy &&Fn, ArgsTy&&... args) { Optional<V> &OptVal = Map[Key]; - if (!OptVal.hasValue()) + if (!OptVal) OptVal = Fn(std::forward<ArgsTy>(args)...); - return OptVal.getValue(); + return *OptVal; } const BasicBlock * diff --git a/llvm/lib/Analysis/ProfileSummaryInfo.cpp b/llvm/lib/Analysis/ProfileSummaryInfo.cpp index 9d5fa6d..b564dbe 100644 --- a/llvm/lib/Analysis/ProfileSummaryInfo.cpp +++ b/llvm/lib/Analysis/ProfileSummaryInfo.cpp @@ -279,19 +279,19 @@ ProfileSummaryInfo::computeThreshold(int PercentileCutoff) const { } bool ProfileSummaryInfo::hasHugeWorkingSetSize() const { - return HasHugeWorkingSetSize && HasHugeWorkingSetSize.getValue(); + return HasHugeWorkingSetSize && *HasHugeWorkingSetSize; } bool ProfileSummaryInfo::hasLargeWorkingSetSize() const { - return HasLargeWorkingSetSize && HasLargeWorkingSetSize.getValue(); + return HasLargeWorkingSetSize && *HasLargeWorkingSetSize; } bool ProfileSummaryInfo::isHotCount(uint64_t C) const { - return HotCountThreshold && C >= HotCountThreshold.getValue(); + return HotCountThreshold && C >= *HotCountThreshold; } bool ProfileSummaryInfo::isColdCount(uint64_t C) const { - return ColdCountThreshold && C <= ColdCountThreshold.getValue(); + return ColdCountThreshold && C <= *ColdCountThreshold; } template <bool isHot> @@ -299,9 +299,9 @@ bool ProfileSummaryInfo::isHotOrColdCountNthPercentile(int PercentileCutoff, uint64_t C) const { auto CountThreshold = computeThreshold(PercentileCutoff); if (isHot) - return CountThreshold && C >= CountThreshold.getValue(); + return CountThreshold && C >= *CountThreshold; else - return CountThreshold && C <= CountThreshold.getValue(); + return CountThreshold && C <= *CountThreshold; } bool ProfileSummaryInfo::isHotCountNthPercentile(int PercentileCutoff, diff --git a/llvm/lib/Analysis/ScalarEvolution.cpp b/llvm/lib/Analysis/ScalarEvolution.cpp index 5eb5c6b..7951180 100644 --- a/llvm/lib/Analysis/ScalarEvolution.cpp +++ b/llvm/lib/Analysis/ScalarEvolution.cpp @@ -4847,16 +4847,16 @@ public: SelectInst *SI = cast<SelectInst>(I); Optional<const SCEV *> Res = compareWithBackedgeCondition(SI->getCondition()); - if (Res.hasValue()) { - bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); + if (Res) { + bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne(); Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); } break; } default: { Optional<const SCEV *> Res = compareWithBackedgeCondition(I); - if (Res.hasValue()) - Result = Res.getValue(); + if (Res) + Result = *Res; break; } } @@ -6596,9 +6596,9 @@ ScalarEvolution::getRangeRef(const SCEV *S, // Check if the IR explicitly contains !range metadata. Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); - if (MDRange.hasValue()) - ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), - RangeType); + if (MDRange) + ConservativeResult = + ConservativeResult.intersectWith(*MDRange, RangeType); // Use facts about recurrences in the underlying IR. Note that add // recurrences are AddRecExprs and thus don't hit this path. This @@ -9710,15 +9710,15 @@ GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { /// (b) if neither X nor Y exist, return None, /// (c) if exactly one of X and Y exists, return that value. static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { - if (X.hasValue() && Y.hasValue()) { + if (X && Y) { unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); APInt XW = X->sext(W); APInt YW = Y->sext(W); return XW.slt(YW) ? *X : *Y; } - if (!X.hasValue() && !Y.hasValue()) + if (!X && !Y) return None; - return X.hasValue() ? *X : *Y; + return X ? *X : *Y; } /// Helper function to truncate an optional APInt to a given BitWidth. @@ -9760,13 +9760,13 @@ SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { APInt A, B, C, M; unsigned BitWidth; auto T = GetQuadraticEquation(AddRec); - if (!T.hasValue()) + if (!T) return None; std::tie(A, B, C, M, BitWidth) = *T; LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); - if (!X.hasValue()) + if (!X) return None; ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); @@ -10471,8 +10471,8 @@ ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, auto ResultSwapped = getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); - assert(ResultSwapped.hasValue() && "should be able to analyze both!"); - assert(ResultSwapped.getValue() != Result.getValue() && + assert(ResultSwapped && "should be able to analyze both!"); + assert(*ResultSwapped != *Result && "monotonicity should flip as we flip the predicate"); } #endif diff --git a/llvm/lib/Analysis/StratifiedSets.h b/llvm/lib/Analysis/StratifiedSets.h index 8468f2b..883ebd2 100644 --- a/llvm/lib/Analysis/StratifiedSets.h +++ b/llvm/lib/Analysis/StratifiedSets.h @@ -340,10 +340,10 @@ public: return StratifiedSets<T>(std::move(Values), std::move(StratLinks)); } - bool has(const T &Elem) const { return get(Elem).hasValue(); } + bool has(const T &Elem) const { return get(Elem).has_value(); } bool add(const T &Main) { - if (get(Main).hasValue()) + if (get(Main)) return false; auto NewIndex = getNewUnlinkedIndex(); diff --git a/llvm/lib/Analysis/VectorUtils.cpp b/llvm/lib/Analysis/VectorUtils.cpp index beb14c4..56a5983 100644 --- a/llvm/lib/Analysis/VectorUtils.cpp +++ b/llvm/lib/Analysis/VectorUtils.cpp @@ -1501,8 +1501,8 @@ void VFABI::getVectorVariantNames( #ifndef NDEBUG LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n"); Optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, *(CI.getModule())); - assert(Info.hasValue() && "Invalid name for a VFABI variant."); - assert(CI.getModule()->getFunction(Info.getValue().VectorName) && + assert(Info && "Invalid name for a VFABI variant."); + assert(CI.getModule()->getFunction(Info->VectorName) && "Vector function is missing."); #endif VariantMappings.push_back(std::string(S)); diff --git a/llvm/lib/CodeGen/BasicBlockSections.cpp b/llvm/lib/CodeGen/BasicBlockSections.cpp index e6f4e39..b6b018c 100644 --- a/llvm/lib/CodeGen/BasicBlockSections.cpp +++ b/llvm/lib/CodeGen/BasicBlockSections.cpp @@ -234,9 +234,8 @@ assignSections(MachineFunction &MF, // If we already have one cluster containing eh_pads, this must be updated // to ExceptionSectionID. Otherwise, we set it equal to the current // section ID. - EHPadsSectionID = EHPadsSectionID.hasValue() - ? MBBSectionID::ExceptionSectionID - : MBB.getSectionID(); + EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID + : MBB.getSectionID(); } } diff --git a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp index 674649c..2c94f87 100644 --- a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp +++ b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp @@ -1291,12 +1291,12 @@ bool CombinerHelper::matchCombineConstantFoldFpUnary(MachineInstr &MI, Register SrcReg = MI.getOperand(1).getReg(); LLT DstTy = MRI.getType(DstReg); Cst = constantFoldFpUnary(MI.getOpcode(), DstTy, SrcReg, MRI); - return Cst.hasValue(); + return Cst.has_value(); } void CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI, Optional<APFloat> &Cst) { - assert(Cst.hasValue() && "Optional is unexpectedly empty!"); + assert(Cst && "Optional is unexpectedly empty!"); Builder.setInstrAndDebugLoc(MI); MachineFunction &MF = Builder.getMF(); auto *FPVal = ConstantFP::get(MF.getFunction().getContext(), *Cst); diff --git a/llvm/lib/CodeGen/MIRParser/MIParser.cpp b/llvm/lib/CodeGen/MIRParser/MIParser.cpp index 879ec00..5ddfc69 100644 --- a/llvm/lib/CodeGen/MIRParser/MIParser.cpp +++ b/llvm/lib/CodeGen/MIRParser/MIParser.cpp @@ -741,8 +741,8 @@ bool MIParser::parseBasicBlockDefinition( MBB->setIsEHPad(IsLandingPad); MBB->setIsInlineAsmBrIndirectTarget(IsInlineAsmBrIndirectTarget); MBB->setIsEHFuncletEntry(IsEHFuncletEntry); - if (SectionID.hasValue()) { - MBB->setSectionID(SectionID.getValue()); + if (SectionID) { + MBB->setSectionID(*SectionID); MF.setBBSectionsType(BasicBlockSection::List); } return false; diff --git a/llvm/lib/CodeGen/MachineBasicBlock.cpp b/llvm/lib/CodeGen/MachineBasicBlock.cpp index c186d0b..a50e188a 100644 --- a/llvm/lib/CodeGen/MachineBasicBlock.cpp +++ b/llvm/lib/CodeGen/MachineBasicBlock.cpp @@ -450,8 +450,8 @@ void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST, if (IrrLoopHeaderWeight && IsStandalone) { if (Indexes) OS << '\t'; - OS.indent(2) << "; Irreducible loop header weight: " - << IrrLoopHeaderWeight.getValue() << '\n'; + OS.indent(2) << "; Irreducible loop header weight: " << *IrrLoopHeaderWeight + << '\n'; } } diff --git a/llvm/lib/CodeGen/MachineFunctionSplitter.cpp b/llvm/lib/CodeGen/MachineFunctionSplitter.cpp index 7d0f294..3f55a82 100644 --- a/llvm/lib/CodeGen/MachineFunctionSplitter.cpp +++ b/llvm/lib/CodeGen/MachineFunctionSplitter.cpp @@ -106,9 +106,8 @@ bool MachineFunctionSplitter::runOnMachineFunction(MachineFunction &MF) { // We don't want to proceed further for cold functions // or functions of unknown hotness. Lukewarm functions have no prefix. Optional<StringRef> SectionPrefix = MF.getFunction().getSectionPrefix(); - if (SectionPrefix.hasValue() && - (SectionPrefix.getValue().equals("unlikely") || - SectionPrefix.getValue().equals("unknown"))) { + if (SectionPrefix && + (SectionPrefix->equals("unlikely") || SectionPrefix->equals("unknown"))) { return false; } diff --git a/llvm/lib/CodeGen/ModuloSchedule.cpp b/llvm/lib/CodeGen/ModuloSchedule.cpp index 8e8cdb2..37b851f 100644 --- a/llvm/lib/CodeGen/ModuloSchedule.cpp +++ b/llvm/lib/CodeGen/ModuloSchedule.cpp @@ -1447,8 +1447,8 @@ Register KernelRewriter::remapUse(Register Reg, MachineInstr &MI) { Register KernelRewriter::phi(Register LoopReg, Optional<Register> InitReg, const TargetRegisterClass *RC) { // If the init register is not undef, try and find an existing phi. - if (InitReg.hasValue()) { - auto I = Phis.find({LoopReg, InitReg.getValue()}); + if (InitReg) { + auto I = Phis.find({LoopReg, *InitReg}); if (I != Phis.end()) return I->second; } else { @@ -1469,10 +1469,10 @@ Register KernelRewriter::phi(Register LoopReg, Optional<Register> InitReg, return R; // Found a phi taking undef as input, so rewrite it to take InitReg. MachineInstr *MI = MRI.getVRegDef(R); - MI->getOperand(1).setReg(InitReg.getValue()); - Phis.insert({{LoopReg, InitReg.getValue()}, R}); + MI->getOperand(1).setReg(*InitReg); + Phis.insert({{LoopReg, *InitReg}, R}); const TargetRegisterClass *ConstrainRegClass = - MRI.constrainRegClass(R, MRI.getRegClass(InitReg.getValue())); + MRI.constrainRegClass(R, MRI.getRegClass(*InitReg)); assert(ConstrainRegClass && "Expected a valid constrained register class!"); (void)ConstrainRegClass; UndefPhis.erase(I); @@ -1483,18 +1483,18 @@ Register KernelRewriter::phi(Register LoopReg, Optional<Register> InitReg, if (!RC) RC = MRI.getRegClass(LoopReg); Register R = MRI.createVirtualRegister(RC); - if (InitReg.hasValue()) { + if (InitReg) { const TargetRegisterClass *ConstrainRegClass = MRI.constrainRegClass(R, MRI.getRegClass(*InitReg)); assert(ConstrainRegClass && "Expected a valid constrained register class!"); (void)ConstrainRegClass; } BuildMI(*BB, BB->getFirstNonPHI(), DebugLoc(), TII->get(TargetOpcode::PHI), R) - .addReg(InitReg.hasValue() ? *InitReg : undef(RC)) + .addReg(InitReg ? *InitReg : undef(RC)) .addMBB(PreheaderBB) .addReg(LoopReg) .addMBB(BB); - if (!InitReg.hasValue()) + if (!InitReg) UndefPhis[LoopReg] = R; else Phis[{LoopReg, *InitReg}] = R; diff --git a/llvm/lib/CodeGen/SelectOptimize.cpp b/llvm/lib/CodeGen/SelectOptimize.cpp index c199b6a..4032227 100644 --- a/llvm/lib/CodeGen/SelectOptimize.cpp +++ b/llvm/lib/CodeGen/SelectOptimize.cpp @@ -870,8 +870,8 @@ bool SelectOptimize::computeLoopCosts( ORE->emit(ORmissL); return false; } - IPredCost += Scaled64::get(ILatency.getValue()); - INonPredCost += Scaled64::get(ILatency.getValue()); + IPredCost += Scaled64::get(*ILatency); + INonPredCost += Scaled64::get(*ILatency); // For a select that can be converted to branch, // compute its cost as a branch (non-predicated cost). diff --git a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp index 38f440a..aa688d9d 100644 --- a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp +++ b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp @@ -24514,9 +24514,8 @@ bool DAGCombiner::mayAlias(SDNode *Op0, SDNode *Op1) const { auto &Size0 = MUC0.NumBytes; auto &Size1 = MUC1.NumBytes; if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && - Size0.hasValue() && Size1.hasValue() && *Size0 == *Size1 && - OrigAlignment0 > *Size0 && SrcValOffset0 % *Size0 == 0 && - SrcValOffset1 % *Size1 == 0) { + Size0 && Size1 && *Size0 == *Size1 && OrigAlignment0 > *Size0 && + SrcValOffset0 % *Size0 == 0 && SrcValOffset1 % *Size1 == 0) { int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0.value(); int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1.value(); @@ -24535,8 +24534,8 @@ bool DAGCombiner::mayAlias(SDNode *Op0, SDNode *Op1) const { UseAA = false; #endif - if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() && - Size0.hasValue() && Size1.hasValue()) { + if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() && Size0 && + Size1) { // Use alias analysis information. int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); int64_t Overlap0 = *Size0 + SrcValOffset0 - MinOffset; diff --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp index 15455eb..103da92 100644 --- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp +++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp @@ -703,8 +703,8 @@ static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, unsigned NumRegs; if (IsABIRegCopy) { NumRegs = TLI.getVectorTypeBreakdownForCallingConv( - *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, - NumIntermediates, RegisterVT); + *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, + RegisterVT); } else { NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, @@ -800,11 +800,11 @@ RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, for (EVT ValueVT : ValueVTs) { unsigned NumRegs = isABIMangled() - ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) + ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) : TLI.getNumRegisters(Context, ValueVT); MVT RegisterVT = isABIMangled() - ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) + ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) : TLI.getRegisterType(Context, ValueVT); for (unsigned i = 0; i != NumRegs; ++i) Regs.push_back(Reg + i); @@ -831,10 +831,10 @@ SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, // Copy the legal parts from the registers. EVT ValueVT = ValueVTs[Value]; unsigned NumRegs = RegCount[Value]; - MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( - *DAG.getContext(), - CallConv.getValue(), RegVTs[Value]) - : RegVTs[Value]; + MVT RegisterVT = isABIMangled() + ? TLI.getRegisterTypeForCallingConv( + *DAG.getContext(), *CallConv, RegVTs[Value]) + : RegVTs[Value]; Parts.resize(NumRegs); for (unsigned i = 0; i != NumRegs; ++i) { @@ -914,10 +914,10 @@ void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { unsigned NumParts = RegCount[Value]; - MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( - *DAG.getContext(), - CallConv.getValue(), RegVTs[Value]) - : RegVTs[Value]; + MVT RegisterVT = isABIMangled() + ? TLI.getRegisterTypeForCallingConv( + *DAG.getContext(), *CallConv, RegVTs[Value]) + : RegVTs[Value]; if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) ExtendKind = ISD::ZERO_EXTEND; @@ -8867,10 +8867,10 @@ void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, : OpInfo; const auto RegError = getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); - if (RegError.hasValue()) { + if (RegError) { const MachineFunction &MF = DAG.getMachineFunction(); const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); - const char *RegName = TRI.getName(RegError.getValue()); + const char *RegName = TRI.getName(*RegError); emitInlineAsmError(Call, "register '" + Twine(RegName) + "' allocated for constraint '" + Twine(OpInfo.ConstraintCode) + diff --git a/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp index b318c2a..68c53fd 100644 --- a/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp +++ b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp @@ -196,10 +196,10 @@ static Optional<int> findPreviousSpillSlot(const Value *Val, for (auto &IncomingValue : Phi->incoming_values()) { Optional<int> SpillSlot = findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1); - if (!SpillSlot.hasValue()) + if (!SpillSlot) return None; - if (MergedResult.hasValue() && *MergedResult != *SpillSlot) + if (MergedResult && *MergedResult != *SpillSlot) return None; MergedResult = SpillSlot; @@ -530,16 +530,14 @@ lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops, GCStrategy &S = GFI->getStrategy(); for (const Value *V : SI.Bases) { auto Opt = S.isGCManagedPointer(V->getType()->getScalarType()); - if (Opt.hasValue()) { - assert(Opt.getValue() && - "non gc managed base pointer found in statepoint"); + if (Opt) { + assert(*Opt && "non gc managed base pointer found in statepoint"); } } for (const Value *V : SI.Ptrs) { auto Opt = S.isGCManagedPointer(V->getType()->getScalarType()); - if (Opt.hasValue()) { - assert(Opt.getValue() && - "non gc managed derived pointer found in statepoint"); + if (Opt) { + assert(*Opt && "non gc managed derived pointer found in statepoint"); } } assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!"); diff --git a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp index a6b471e..c286d21 100644 --- a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp +++ b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp @@ -1972,9 +1972,9 @@ bool TargetLowering::SimplifyDemandedBits( KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); Known = KnownBits::umin(Known0, Known1); if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) - return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1); + return TLO.CombineTo(Op, *IsULE ? Op0 : Op1); if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) - return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1); + return TLO.CombineTo(Op, *IsULT ? Op0 : Op1); break; } case ISD::UMAX: { @@ -1985,9 +1985,9 @@ bool TargetLowering::SimplifyDemandedBits( KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); Known = KnownBits::umax(Known0, Known1); if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) - return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1); + return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1); if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) - return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1); + return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1); break; } case ISD::BITREVERSE: { diff --git a/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp b/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp index c49c2e5..a66f9af 100644 --- a/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp +++ b/llvm/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp @@ -70,10 +70,10 @@ uint32_t CodeViewRecordIO::maxFieldLength() const { Optional<uint32_t> Min = Limits.front().bytesRemaining(Offset); for (auto X : makeArrayRef(Limits).drop_front()) { Optional<uint32_t> ThisMin = X.bytesRemaining(Offset); - if (ThisMin.hasValue()) - Min = (Min.hasValue()) ? std::min(*Min, *ThisMin) : *ThisMin; + if (ThisMin) + Min = Min ? std::min(*Min, *ThisMin) : *ThisMin; } - assert(Min.hasValue() && "Every field must have a maximum length!"); + assert(Min && "Every field must have a maximum length!"); return *Min; } diff --git a/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp b/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp index 9b35b23..27f63b9 100644 --- a/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp +++ b/llvm/lib/DebugInfo/CodeView/TypeRecordMapping.cpp @@ -228,8 +228,8 @@ static Error mapNameAndUniqueName(CodeViewRecordIO &IO, StringRef &Name, } Error TypeRecordMapping::visitTypeBegin(CVType &CVR) { - assert(!TypeKind.hasValue() && "Already in a type mapping!"); - assert(!MemberKind.hasValue() && "Already in a member mapping!"); + assert(!TypeKind && "Already in a type mapping!"); + assert(!MemberKind && "Already in a member mapping!"); // FieldList and MethodList records can be any length because they can be // split with continuation records. All other record types cannot be @@ -260,8 +260,8 @@ Error TypeRecordMapping::visitTypeBegin(CVType &CVR, TypeIndex Index) { } Error TypeRecordMapping::visitTypeEnd(CVType &Record) { - assert(TypeKind.hasValue() && "Not in a type mapping!"); - assert(!MemberKind.hasValue() && "Still in a member mapping!"); + assert(TypeKind && "Not in a type mapping!"); + assert(!MemberKind && "Still in a member mapping!"); error(IO.endRecord()); @@ -270,8 +270,8 @@ Error TypeRecordMapping::visitTypeEnd(CVType &Record) { } Error TypeRecordMapping::visitMemberBegin(CVMemberRecord &Record) { - assert(TypeKind.hasValue() && "Not in a type mapping!"); - assert(!MemberKind.hasValue() && "Already in a member mapping!"); + assert(TypeKind && "Not in a type mapping!"); + assert(!MemberKind && "Already in a member mapping!"); // The largest possible subrecord is one in which there is a record prefix, // followed by the subrecord, followed by a continuation, and that entire @@ -296,8 +296,8 @@ Error TypeRecordMapping::visitMemberBegin(CVMemberRecord &Record) { } Error TypeRecordMapping::visitMemberEnd(CVMemberRecord &Record) { - assert(TypeKind.hasValue() && "Not in a type mapping!"); - assert(MemberKind.hasValue() && "Not in a member mapping!"); + assert(TypeKind && "Not in a type mapping!"); + assert(MemberKind && "Not in a member mapping!"); if (IO.isReading()) { if (auto EC = IO.skipPadding()) diff --git a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp index c785026..dd49ef8 100644 --- a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp +++ b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp @@ -1205,13 +1205,12 @@ void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram, if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) { if (const auto *LT = CU->getContext().getLineTableForUnit(CU)) LT->getFileNameByIndex( - DeclFileAttr->getAsUnsignedConstant().getValue(), - CU->getCompilationDir(), + *DeclFileAttr->getAsUnsignedConstant(), CU->getCompilationDir(), DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Local.DeclFile); } if (auto DeclLineAttr = Die.find(DW_AT_decl_line)) - Local.DeclLine = DeclLineAttr->getAsUnsignedConstant().getValue(); + Local.DeclLine = *DeclLineAttr->getAsUnsignedConstant(); Result.push_back(Local); return; diff --git a/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp b/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp index 2e0780e..25d0b9f 100644 --- a/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp +++ b/llvm/lib/DebugInfo/DWARF/DWARFDebugLine.cpp @@ -327,20 +327,20 @@ parseV5DirFileTables(const DWARFDataExtractor &DebugLineData, FileEntry.Source = Value; break; case DW_LNCT_directory_index: - FileEntry.DirIdx = Value.getAsUnsignedConstant().getValue(); + FileEntry.DirIdx = *Value.getAsUnsignedConstant(); break; case DW_LNCT_timestamp: - FileEntry.ModTime = Value.getAsUnsignedConstant().getValue(); + FileEntry.ModTime = *Value.getAsUnsignedConstant(); break; case DW_LNCT_size: - FileEntry.Length = Value.getAsUnsignedConstant().getValue(); + FileEntry.Length = *Value.getAsUnsignedConstant(); break; case DW_LNCT_MD5: - if (!Value.getAsBlock() || Value.getAsBlock().getValue().size() != 16) + if (!Value.getAsBlock() || Value.getAsBlock()->size() != 16) return createStringError( errc::invalid_argument, "failed to parse file entry because the MD5 hash is invalid"); - std::uninitialized_copy_n(Value.getAsBlock().getValue().begin(), 16, + std::uninitialized_copy_n(Value.getAsBlock()->begin(), 16, FileEntry.Checksum.begin()); break; default: diff --git a/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp b/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp index 1cb332c..3a719bd 100644 --- a/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp +++ b/llvm/lib/DebugInfo/PDB/Native/DbiStreamBuilder.cpp @@ -427,14 +427,14 @@ Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout, for (auto &Stream : DbgStreams) { uint16_t StreamNumber = kInvalidStreamIndex; - if (Stream.hasValue()) + if (Stream) StreamNumber = Stream->StreamNumber; if (auto EC = Writer.writeInteger(StreamNumber)) return EC; } for (auto &Stream : DbgStreams) { - if (!Stream.hasValue()) + if (!Stream) continue; assert(Stream->StreamNumber != kInvalidStreamIndex); diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index eea08b2..017548f 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -212,9 +212,8 @@ static int isVariantApplicableInContextHelper( return Ctx.matchesISATrait(RawString); }); - Optional<bool> Result = HandleTrait(Property, IsActiveTrait); - if (Result.hasValue()) - return Result.getValue(); + if (Optional<bool> Result = HandleTrait(Property, IsActiveTrait)) + return *Result; } if (!DeviceSetOnly) { @@ -233,9 +232,8 @@ static int isVariantApplicableInContextHelper( if (ConstructMatches) ConstructMatches->push_back(ConstructIdx - 1); - Optional<bool> Result = HandleTrait(Property, FoundInOrder); - if (Result.hasValue()) - return Result.getValue(); + if (Optional<bool> Result = HandleTrait(Property, FoundInOrder)) + return *Result; if (!FoundInOrder) { LLVM_DEBUG(dbgs() << "[" << DEBUG_TYPE << "] Construct property " diff --git a/llvm/lib/IR/Instructions.cpp b/llvm/lib/IR/Instructions.cpp index 22e8ca7..7e718ac 100644 --- a/llvm/lib/IR/Instructions.cpp +++ b/llvm/lib/IR/Instructions.cpp @@ -4423,10 +4423,9 @@ MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() { assert(SI.getNumSuccessors() == Weights->size() && "num of prof branch_weights must accord with num of successors"); - bool AllZeroes = - all_of(Weights.getValue(), [](uint32_t W) { return W == 0; }); + bool AllZeroes = all_of(*Weights, [](uint32_t W) { return W == 0; }); - if (AllZeroes || Weights.getValue().size() < 2) + if (AllZeroes || Weights->size() < 2) return nullptr; return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights); @@ -4460,8 +4459,8 @@ SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) { // Copy the last case to the place of the removed one and shrink. // This is tightly coupled with the way SwitchInst::removeCase() removes // the cases in SwitchInst::removeCase(CaseIt). - Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back(); - Weights.getValue().pop_back(); + Weights.value()[I->getCaseIndex() + 1] = Weights->back(); + Weights->pop_back(); } return SI.removeCase(I); } @@ -4474,10 +4473,10 @@ void SwitchInstProfUpdateWrapper::addCase( if (!Weights && W && *W) { Changed = true; Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0); - Weights.getValue()[SI.getNumSuccessors() - 1] = *W; + Weights.value()[SI.getNumSuccessors() - 1] = *W; } else if (Weights) { Changed = true; - Weights.getValue().push_back(W.value_or(0)); + Weights->push_back(W.value_or(0)); } if (Weights) assert(SI.getNumSuccessors() == Weights->size() && diff --git a/llvm/lib/IR/IntrinsicInst.cpp b/llvm/lib/IR/IntrinsicInst.cpp index ac03b14..953090f 100644 --- a/llvm/lib/IR/IntrinsicInst.cpp +++ b/llvm/lib/IR/IntrinsicInst.cpp @@ -223,13 +223,13 @@ ConstrainedFPIntrinsic::getExceptionBehavior() const { bool ConstrainedFPIntrinsic::isDefaultFPEnvironment() const { Optional<fp::ExceptionBehavior> Except = getExceptionBehavior(); if (Except) { - if (Except.getValue() != fp::ebIgnore) + if (*Except != fp::ebIgnore) return false; } Optional<RoundingMode> Rounding = getRoundingMode(); if (Rounding) { - if (Rounding.getValue() != RoundingMode::NearestTiesToEven) + if (*Rounding != RoundingMode::NearestTiesToEven) return false; } @@ -363,14 +363,14 @@ VPIntrinsic::getVectorLengthParamPos(Intrinsic::ID IntrinsicID) { /// scatter. MaybeAlign VPIntrinsic::getPointerAlignment() const { Optional<unsigned> PtrParamOpt = getMemoryPointerParamPos(getIntrinsicID()); - assert(PtrParamOpt.hasValue() && "no pointer argument!"); - return getParamAlign(PtrParamOpt.getValue()); + assert(PtrParamOpt && "no pointer argument!"); + return getParamAlign(*PtrParamOpt); } /// \return The pointer operand of this load,store, gather or scatter. Value *VPIntrinsic::getMemoryPointerParam() const { if (auto PtrParamOpt = getMemoryPointerParamPos(getIntrinsicID())) - return getArgOperand(PtrParamOpt.getValue()); + return getArgOperand(*PtrParamOpt); return nullptr; } @@ -388,10 +388,9 @@ Optional<unsigned> VPIntrinsic::getMemoryPointerParamPos(Intrinsic::ID VPID) { /// \return The data (payload) operand of this store or scatter. Value *VPIntrinsic::getMemoryDataParam() const { - auto DataParamOpt = getMemoryDataParamPos(getIntrinsicID()); - if (!DataParamOpt.hasValue()) - return nullptr; - return getArgOperand(DataParamOpt.getValue()); + if (auto DataParamOpt = getMemoryDataParamPos(getIntrinsicID())) + return getArgOperand(*DataParamOpt); + return nullptr; } Optional<unsigned> VPIntrinsic::getMemoryDataParamPos(Intrinsic::ID VPID) { diff --git a/llvm/lib/IR/LLVMContextImpl.cpp b/llvm/lib/IR/LLVMContextImpl.cpp index dc44a34..7e005b3 100644 --- a/llvm/lib/IR/LLVMContextImpl.cpp +++ b/llvm/lib/IR/LLVMContextImpl.cpp @@ -250,17 +250,17 @@ void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) { } bool LLVMContextImpl::hasOpaquePointersValue() { - return OpaquePointers.hasValue(); + return OpaquePointers.has_value(); } bool LLVMContextImpl::getOpaquePointers() { - if (LLVM_UNLIKELY(!(OpaquePointers.hasValue()))) + if (LLVM_UNLIKELY(!OpaquePointers)) OpaquePointers = OpaquePointersCL; return *OpaquePointers; } void LLVMContextImpl::setOpaquePointers(bool OP) { - assert((!OpaquePointers.hasValue() || OpaquePointers.getValue() == OP) && + assert((!OpaquePointers || *OpaquePointers == OP) && "Cannot change opaque pointers mode once set"); OpaquePointers = OP; } diff --git a/llvm/lib/IR/VectorBuilder.cpp b/llvm/lib/IR/VectorBuilder.cpp index 82995ce..e7be7a9 100644 --- a/llvm/lib/IR/VectorBuilder.cpp +++ b/llvm/lib/IR/VectorBuilder.cpp @@ -90,9 +90,9 @@ Value *VectorBuilder::createVectorInstruction(unsigned Opcode, Type *ReturnTy, } } - if (MaskPosOpt.hasValue()) + if (MaskPosOpt) IntrinParams[*MaskPosOpt] = &requestMask(); - if (VLenPosOpt.hasValue()) + if (VLenPosOpt) IntrinParams[*VLenPosOpt] = &requestEVL(); auto *VPDecl = VPIntrinsic::getDeclarationForParams(&getModule(), VPID, diff --git a/llvm/lib/IR/Verifier.cpp b/llvm/lib/IR/Verifier.cpp index 8f857933..cbdf1d1 100644 --- a/llvm/lib/IR/Verifier.cpp +++ b/llvm/lib/IR/Verifier.cpp @@ -5844,10 +5844,10 @@ void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) { // match the specification in the intrinsic call table. Thus, no // argument type check is needed here. - Check(FPI.getExceptionBehavior().hasValue(), + Check(FPI.getExceptionBehavior().has_value(), "invalid exception behavior argument", &FPI); if (HasRoundingMD) { - Check(FPI.getRoundingMode().hasValue(), "invalid rounding mode argument", + Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument", &FPI); } } diff --git a/llvm/lib/InterfaceStub/IFSHandler.cpp b/llvm/lib/InterfaceStub/IFSHandler.cpp index 71189e7..c999387 100644 --- a/llvm/lib/InterfaceStub/IFSHandler.cpp +++ b/llvm/lib/InterfaceStub/IFSHandler.cpp @@ -202,8 +202,8 @@ Error ifs::writeIFSToOutputStream(raw_ostream &OS, const IFSStub &Stub) { yaml::Output YamlOut(OS, nullptr, /*WrapColumn =*/0); std::unique_ptr<IFSStubTriple> CopyStub(new IFSStubTriple(Stub)); if (Stub.Target.Arch) { - CopyStub->Target.ArchString = std::string( - ELF::convertEMachineToArchName(Stub.Target.Arch.getValue())); + CopyStub->Target.ArchString = + std::string(ELF::convertEMachineToArchName(*Stub.Target.Arch)); } IFSTarget Target = Stub.Target; @@ -222,36 +222,33 @@ Error ifs::overrideIFSTarget(IFSStub &Stub, Optional<IFSArch> OverrideArch, Optional<std::string> OverrideTriple) { std::error_code OverrideEC(1, std::generic_category()); if (OverrideArch) { - if (Stub.Target.Arch && - Stub.Target.Arch.getValue() != OverrideArch.getValue()) { + if (Stub.Target.Arch && *Stub.Target.Arch != *OverrideArch) { return make_error<StringError>( "Supplied Arch conflicts with the text stub", OverrideEC); } - Stub.Target.Arch = OverrideArch.getValue(); + Stub.Target.Arch = *OverrideArch; } if (OverrideEndianness) { if (Stub.Target.Endianness && - Stub.Target.Endianness.getValue() != OverrideEndianness.getValue()) { + *Stub.Target.Endianness != *OverrideEndianness) { return make_error<StringError>( "Supplied Endianness conflicts with the text stub", OverrideEC); } - Stub.Target.Endianness = OverrideEndianness.getValue(); + Stub.Target.Endianness = *OverrideEndianness; } if (OverrideBitWidth) { - if (Stub.Target.BitWidth && - Stub.Target.BitWidth.getValue() != OverrideBitWidth.getValue()) { + if (Stub.Target.BitWidth && *Stub.Target.BitWidth != *OverrideBitWidth) { return make_error<StringError>( "Supplied BitWidth conflicts with the text stub", OverrideEC); } - Stub.Target.BitWidth = OverrideBitWidth.getValue(); + Stub.Target.BitWidth = *OverrideBitWidth; } if (OverrideTriple) { - if (Stub.Target.Triple && - Stub.Target.Triple.getValue() != OverrideTriple.getValue()) { + if (Stub.Target.Triple && *Stub.Target.Triple != *OverrideTriple) { return make_error<StringError>( "Supplied Triple conflicts with the text stub", OverrideEC); } - Stub.Target.Triple = OverrideTriple.getValue(); + Stub.Target.Triple = *OverrideTriple; } return Error::success(); } diff --git a/llvm/lib/MC/MCContext.cpp b/llvm/lib/MC/MCContext.cpp index 1c0c711..e8f0987 100644 --- a/llvm/lib/MC/MCContext.cpp +++ b/llvm/lib/MC/MCContext.cpp @@ -767,14 +767,13 @@ MCSectionXCOFF *MCContext::getXCOFFSection( Optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed, const char *BeginSymName, Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) { - bool IsDwarfSec = DwarfSectionSubtypeFlags.hasValue(); - assert((IsDwarfSec != CsectProp.hasValue()) && "Invalid XCOFF section!"); + bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value(); + assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!"); // Do the lookup. If we have a hit, return it. auto IterBool = XCOFFUniquingMap.insert(std::make_pair( - IsDwarfSec - ? XCOFFSectionKey(Section.str(), DwarfSectionSubtypeFlags.getValue()) - : XCOFFSectionKey(Section.str(), CsectProp->MappingClass), + IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags) + : XCOFFSectionKey(Section.str(), CsectProp->MappingClass), nullptr)); auto &Entry = *IterBool.first; if (!IterBool.second) { @@ -804,10 +803,9 @@ MCSectionXCOFF *MCContext::getXCOFFSection( // CachedName contains invalid character(s) such as '$' for an XCOFF symbol. MCSectionXCOFF *Result = nullptr; if (IsDwarfSec) - Result = new (XCOFFAllocator.Allocate()) - MCSectionXCOFF(QualName->getUnqualifiedName(), Kind, QualName, - DwarfSectionSubtypeFlags.getValue(), Begin, CachedName, - MultiSymbolsAllowed); + Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF( + QualName->getUnqualifiedName(), Kind, QualName, + *DwarfSectionSubtypeFlags, Begin, CachedName, MultiSymbolsAllowed); else Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass, diff --git a/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp b/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp index c6035dc..af52c34 100644 --- a/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp +++ b/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp @@ -83,12 +83,13 @@ bool XCOFFSymbolInfo::operator<(const XCOFFSymbolInfo &SymInfo) const { return SymInfo.IsLabel; // Symbols with a StorageMappingClass have higher priority than those without. - if (StorageMappingClass.hasValue() != SymInfo.StorageMappingClass.hasValue()) - return SymInfo.StorageMappingClass.hasValue(); + if (StorageMappingClass.has_value() != + SymInfo.StorageMappingClass.has_value()) + return SymInfo.StorageMappingClass.has_value(); - if (StorageMappingClass.hasValue()) { - return getSMCPriority(StorageMappingClass.getValue()) < - getSMCPriority(SymInfo.StorageMappingClass.getValue()); + if (StorageMappingClass) { + return getSMCPriority(*StorageMappingClass) < + getSMCPriority(*SymInfo.StorageMappingClass); } return false; diff --git a/llvm/lib/MC/MCParser/MasmParser.cpp b/llvm/lib/MC/MCParser/MasmParser.cpp index 7ed37b0..c4240ca 100644 --- a/llvm/lib/MC/MCParser/MasmParser.cpp +++ b/llvm/lib/MC/MCParser/MasmParser.cpp @@ -4239,10 +4239,9 @@ bool MasmParser::parseStructInitializer(const StructInfo &Structure, auto &FieldInitializers = Initializer.FieldInitializers; size_t FieldIndex = 0; - if (EndToken.hasValue()) { + if (EndToken) { // Initialize all fields with given initializers. - while (getTok().isNot(EndToken.getValue()) && - FieldIndex < Structure.Fields.size()) { + while (getTok().isNot(*EndToken) && FieldIndex < Structure.Fields.size()) { const FieldInfo &Field = Structure.Fields[FieldIndex++]; if (parseOptionalToken(AsmToken::Comma)) { // Empty initializer; use the default and continue. (Also, allow line @@ -4272,11 +4271,11 @@ bool MasmParser::parseStructInitializer(const StructInfo &Structure, FieldInitializers.push_back(Field.Contents); } - if (EndToken.hasValue()) { - if (EndToken.getValue() == AsmToken::Greater) + if (EndToken) { + if (*EndToken == AsmToken::Greater) return parseAngleBracketClose(); - return parseToken(EndToken.getValue()); + return parseToken(*EndToken); } return false; diff --git a/llvm/lib/MC/MCSchedule.cpp b/llvm/lib/MC/MCSchedule.cpp index db08e20..dd1ecce 100644 --- a/llvm/lib/MC/MCSchedule.cpp +++ b/llvm/lib/MC/MCSchedule.cpp @@ -96,10 +96,10 @@ MCSchedModel::getReciprocalThroughput(const MCSubtargetInfo &STI, continue; unsigned NumUnits = SM.getProcResource(I->ProcResourceIdx)->NumUnits; double Temp = NumUnits * 1.0 / I->Cycles; - Throughput = Throughput ? std::min(Throughput.getValue(), Temp) : Temp; + Throughput = Throughput ? std::min(*Throughput, Temp) : Temp; } - if (Throughput.hasValue()) - return 1.0 / Throughput.getValue(); + if (Throughput) + return 1.0 / *Throughput; // If no throughput value was calculated, assume that we can execute at the // maximum issue width scaled by number of micro-ops for the schedule class. @@ -140,10 +140,10 @@ MCSchedModel::getReciprocalThroughput(unsigned SchedClass, if (!I->getCycles()) continue; double Temp = countPopulation(I->getUnits()) * 1.0 / I->getCycles(); - Throughput = Throughput ? std::min(Throughput.getValue(), Temp) : Temp; + Throughput = Throughput ? std::min(*Throughput, Temp) : Temp; } - if (Throughput.hasValue()) - return 1.0 / Throughput.getValue(); + if (Throughput) + return 1.0 / *Throughput; // If there are no execution resources specified for this class, then assume // that it can execute at the maximum default issue width. diff --git a/llvm/lib/MC/MCSectionXCOFF.cpp b/llvm/lib/MC/MCSectionXCOFF.cpp index ee8fa04..0f6d5d5 100644 --- a/llvm/lib/MC/MCSectionXCOFF.cpp +++ b/llvm/lib/MC/MCSectionXCOFF.cpp @@ -110,8 +110,8 @@ void MCSectionXCOFF::printSwitchToSection(const MCAsmInfo &MAI, const Triple &T, // XCOFF debug sections. if (getKind().isMetadata() && isDwarfSect()) { - OS << "\n\t.dwsect " - << format("0x%" PRIx32, getDwarfSubtypeFlags().getValue()) << '\n'; + OS << "\n\t.dwsect " << format("0x%" PRIx32, *getDwarfSubtypeFlags()) + << '\n'; OS << MAI.getPrivateLabelPrefix() << getName() << ':' << '\n'; return; } diff --git a/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp b/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp index a7b7a47..01c0ae7 100644 --- a/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp +++ b/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp @@ -601,8 +601,8 @@ handleUserSection(const NewSectionInfo &NewSection, static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig, Object &Obj) { if (Config.OutputArch) { - Obj.Machine = Config.OutputArch.getValue().EMachine; - Obj.OSABI = Config.OutputArch.getValue().OSABI; + Obj.Machine = Config.OutputArch->EMachine; + Obj.OSABI = Config.OutputArch->OSABI; } if (!Config.SplitDWO.empty() && Config.ExtractDWO) { @@ -639,8 +639,8 @@ static Error handleArgs(const CommonConfig &Config, const ELFConfig &ELFConfig, if (Iter != Config.SectionsToRename.end()) { const SectionRename &SR = Iter->second; Sec.Name = std::string(SR.NewName); - if (SR.NewFlags.hasValue()) - setSectionFlagsAndType(Sec, SR.NewFlags.getValue()); + if (SR.NewFlags) + setSectionFlagsAndType(Sec, *SR.NewFlags); RenamedSections.insert(&Sec); } else if (RelocSec && !(Sec.Flags & SHF_ALLOC)) // Postpone processing relocation sections which are not specified in @@ -808,9 +808,9 @@ Error objcopy::elf::executeObjcopyOnBinary(const CommonConfig &Config, if (!Obj) return Obj.takeError(); // Prefer OutputArch (-O<format>) if set, otherwise infer it from the input. - const ElfType OutputElfType = - Config.OutputArch ? getOutputElfType(Config.OutputArch.getValue()) - : getOutputElfType(In); + const ElfType OutputElfType = Config.OutputArch + ? getOutputElfType(*Config.OutputArch) + : getOutputElfType(In); if (Error E = handleArgs(Config, ELFConfig, **Obj)) return createFileError(Config.InputFilename, std::move(E)); diff --git a/llvm/lib/Object/ELFObjectFile.cpp b/llvm/lib/Object/ELFObjectFile.cpp index 9bac454..9ab0357 100644 --- a/llvm/lib/Object/ELFObjectFile.cpp +++ b/llvm/lib/Object/ELFObjectFile.cpp @@ -167,12 +167,12 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const { bool isV7 = false; Optional<unsigned> Attr = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch); - if (Attr.hasValue()) - isV7 = Attr.getValue() == ARMBuildAttrs::v7; + if (Attr) + isV7 = *Attr == ARMBuildAttrs::v7; Attr = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch_profile); - if (Attr.hasValue()) { - switch (Attr.getValue()) { + if (Attr) { + switch (*Attr) { case ARMBuildAttrs::ApplicationProfile: Features.AddFeature("aclass"); break; @@ -190,8 +190,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const { } Attr = Attributes.getAttributeValue(ARMBuildAttrs::THUMB_ISA_use); - if (Attr.hasValue()) { - switch (Attr.getValue()) { + if (Attr) { + switch (*Attr) { default: break; case ARMBuildAttrs::Not_Allowed: @@ -205,8 +205,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const { } Attr = Attributes.getAttributeValue(ARMBuildAttrs::FP_arch); - if (Attr.hasValue()) { - switch (Attr.getValue()) { + if (Attr) { + switch (*Attr) { default: break; case ARMBuildAttrs::Not_Allowed: @@ -229,8 +229,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const { } Attr = Attributes.getAttributeValue(ARMBuildAttrs::Advanced_SIMD_arch); - if (Attr.hasValue()) { - switch (Attr.getValue()) { + if (Attr) { + switch (*Attr) { default: break; case ARMBuildAttrs::Not_Allowed: @@ -248,8 +248,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const { } Attr = Attributes.getAttributeValue(ARMBuildAttrs::MVE_arch); - if (Attr.hasValue()) { - switch (Attr.getValue()) { + if (Attr) { + switch (*Attr) { default: break; case ARMBuildAttrs::Not_Allowed: @@ -267,8 +267,8 @@ SubtargetFeatures ELFObjectFileBase::getARMFeatures() const { } Attr = Attributes.getAttributeValue(ARMBuildAttrs::DIV_use); - if (Attr.hasValue()) { - switch (Attr.getValue()) { + if (Attr) { + switch (*Attr) { default: break; case ARMBuildAttrs::DisallowDIV: @@ -521,8 +521,8 @@ void ELFObjectFileBase::setARMSubArch(Triple &TheTriple) const { Optional<unsigned> Attr = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch); - if (Attr.hasValue()) { - switch (Attr.getValue()) { + if (Attr) { + switch (*Attr) { case ARMBuildAttrs::v4: Triple += "v4"; break; @@ -553,8 +553,8 @@ void ELFObjectFileBase::setARMSubArch(Triple &TheTriple) const { case ARMBuildAttrs::v7: { Optional<unsigned> ArchProfileAttr = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch_profile); - if (ArchProfileAttr.hasValue() && - ArchProfileAttr.getValue() == ARMBuildAttrs::MicroControllerProfile) + if (ArchProfileAttr && + *ArchProfileAttr == ARMBuildAttrs::MicroControllerProfile) Triple += "v7m"; else Triple += "v7"; diff --git a/llvm/lib/ObjectYAML/DXContainerEmitter.cpp b/llvm/lib/ObjectYAML/DXContainerEmitter.cpp index 9834b03..d51120b 100644 --- a/llvm/lib/ObjectYAML/DXContainerEmitter.cpp +++ b/llvm/lib/ObjectYAML/DXContainerEmitter.cpp @@ -133,17 +133,17 @@ void DXContainerWriter::writeParts(raw_ostream &OS) { // Compute the optional fields if needed... if (P.Program->DXILOffset) - Header.Bitcode.Offset = P.Program->DXILOffset.getValue(); + Header.Bitcode.Offset = *P.Program->DXILOffset; else Header.Bitcode.Offset = sizeof(dxbc::BitcodeHeader); if (P.Program->DXILSize) - Header.Bitcode.Size = P.Program->DXILSize.getValue(); + Header.Bitcode.Size = *P.Program->DXILSize; else Header.Bitcode.Size = P.Program->DXIL ? P.Program->DXIL->size() : 0; if (P.Program->Size) - Header.Size = P.Program->Size.getValue(); + Header.Size = *P.Program->Size; else Header.Size = sizeof(dxbc::ProgramHeader) + Header.Bitcode.Size; diff --git a/llvm/lib/Support/Process.cpp b/llvm/lib/Support/Process.cpp index 547b3b7..d93b7de 100644 --- a/llvm/lib/Support/Process.cpp +++ b/llvm/lib/Support/Process.cpp @@ -42,12 +42,12 @@ Optional<std::string> Process::FindInEnvPath(StringRef EnvName, assert(!path::is_absolute(FileName)); Optional<std::string> FoundPath; Optional<std::string> OptPath = Process::GetEnv(EnvName); - if (!OptPath.hasValue()) + if (!OptPath) return FoundPath; const char EnvPathSeparatorStr[] = {Separator, '\0'}; SmallVector<StringRef, 8> Dirs; - SplitString(OptPath.getValue(), Dirs, EnvPathSeparatorStr); + SplitString(*OptPath, Dirs, EnvPathSeparatorStr); for (StringRef Dir : Dirs) { if (Dir.empty()) diff --git a/llvm/lib/Support/VirtualFileSystem.cpp b/llvm/lib/Support/VirtualFileSystem.cpp index 9c6a0c0..9f6ad7e 100644 --- a/llvm/lib/Support/VirtualFileSystem.cpp +++ b/llvm/lib/Support/VirtualFileSystem.cpp @@ -2667,15 +2667,15 @@ void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries, OS << "{\n" " 'version': 0,\n"; - if (IsCaseSensitive.hasValue()) - OS << " 'case-sensitive': '" - << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n"; - if (UseExternalNames.hasValue()) - OS << " 'use-external-names': '" - << (UseExternalNames.getValue() ? "true" : "false") << "',\n"; + if (IsCaseSensitive) + OS << " 'case-sensitive': '" << (*IsCaseSensitive ? "true" : "false") + << "',\n"; + if (UseExternalNames) + OS << " 'use-external-names': '" << (*UseExternalNames ? "true" : "false") + << "',\n"; bool UseOverlayRelative = false; - if (IsOverlayRelative.hasValue()) { - UseOverlayRelative = IsOverlayRelative.getValue(); + if (IsOverlayRelative) { + UseOverlayRelative = *IsOverlayRelative; OS << " 'overlay-relative': '" << (UseOverlayRelative ? "true" : "false") << "',\n"; } diff --git a/llvm/lib/Support/raw_ostream.cpp b/llvm/lib/Support/raw_ostream.cpp index 7648dac..0c83259 100644 --- a/llvm/lib/Support/raw_ostream.cpp +++ b/llvm/lib/Support/raw_ostream.cpp @@ -428,8 +428,8 @@ raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) { while (!Bytes.empty()) { indent(FB.IndentLevel); - if (FB.FirstByteOffset.hasValue()) { - uint64_t Offset = FB.FirstByteOffset.getValue(); + if (FB.FirstByteOffset) { + uint64_t Offset = *FB.FirstByteOffset; llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth); *this << ": "; } diff --git a/llvm/lib/TableGen/Record.cpp b/llvm/lib/TableGen/Record.cpp index e100251..64f0953 100644 --- a/llvm/lib/TableGen/Record.cpp +++ b/llvm/lib/TableGen/Record.cpp @@ -2598,10 +2598,10 @@ Init *Record::getValueInit(StringRef FieldName) const { StringRef Record::getValueAsString(StringRef FieldName) const { llvm::Optional<StringRef> S = getValueAsOptionalString(FieldName); - if (!S.hasValue()) + if (!S) PrintFatalError(getLoc(), "Record `" + getName() + "' does not have a field named `" + FieldName + "'!\n"); - return S.getValue(); + return *S; } llvm::Optional<StringRef> diff --git a/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp b/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp index 76a39d0..4e2dfc6 100644 --- a/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp +++ b/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp @@ -1171,8 +1171,8 @@ bool AMDGPUInstructionSelector::selectBallot(MachineInstr &I) const { Optional<ValueAndVReg> Arg = getIConstantVRegValWithLookThrough(I.getOperand(2).getReg(), *MRI); - if (Arg.hasValue()) { - const int64_t Value = Arg.getValue().Value.getSExtValue(); + if (Arg) { + const int64_t Value = Arg->Value.getSExtValue(); if (Value == 0) { unsigned Opcode = Is64 ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32; BuildMI(*BB, &I, DL, TII.get(Opcode), DstReg).addImm(0); @@ -4201,8 +4201,8 @@ AMDGPUInstructionSelector::selectMUBUFScratchOffen(MachineOperand &Root) const { MIB.addReg(Info->getScratchRSrcReg()); }, [=](MachineInstrBuilder &MIB) { // vaddr - if (FI.hasValue()) - MIB.addFrameIndex(FI.getValue()); + if (FI) + MIB.addFrameIndex(*FI); else MIB.addReg(VAddr); }, diff --git a/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h b/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h index 1b513c4..2572b04 100644 --- a/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h +++ b/llvm/lib/Target/AMDGPU/AMDGPUMachineModuleInfo.h @@ -131,8 +131,8 @@ public: bool IsAOneAddressSpace = isOneAddressSpace(A); bool IsBOneAddressSpace = isOneAddressSpace(B); - return AIO.getValue() >= BIO.getValue() && - (IsAOneAddressSpace == IsBOneAddressSpace || !IsAOneAddressSpace); + return *AIO >= *BIO && + (IsAOneAddressSpace == IsBOneAddressSpace || !IsAOneAddressSpace); } }; diff --git a/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp b/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp index 8a66213..19989a3 100644 --- a/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp +++ b/llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp @@ -2329,13 +2329,13 @@ bool SIMemoryLegalizer::runOnMachineFunction(MachineFunction &MF) { continue; if (const auto &MOI = MOA.getLoadInfo(MI)) - Changed |= expandLoad(MOI.getValue(), MI); + Changed |= expandLoad(*MOI, MI); else if (const auto &MOI = MOA.getStoreInfo(MI)) - Changed |= expandStore(MOI.getValue(), MI); + Changed |= expandStore(*MOI, MI); else if (const auto &MOI = MOA.getAtomicFenceInfo(MI)) - Changed |= expandAtomicFence(MOI.getValue(), MI); + Changed |= expandAtomicFence(*MOI, MI); else if (const auto &MOI = MOA.getAtomicCmpxchgOrRmwInfo(MI)) - Changed |= expandAtomicCmpxchgOrRmw(MOI.getValue(), MI); + Changed |= expandAtomicCmpxchgOrRmw(*MOI, MI); } } diff --git a/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp b/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp index 3078534..310d3ed 100644 --- a/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp +++ b/llvm/lib/Target/ARM/MVEGatherScatterLowering.cpp @@ -351,13 +351,13 @@ Optional<int64_t> MVEGatherScatterLowering::getIfConst(const Value *V) { if (!Op0 || !Op1) return Optional<int64_t>{}; if (I->getOpcode() == Instruction::Add) - return Optional<int64_t>{Op0.getValue() + Op1.getValue()}; + return Optional<int64_t>{*Op0 + *Op1}; if (I->getOpcode() == Instruction::Mul) - return Optional<int64_t>{Op0.getValue() * Op1.getValue()}; + return Optional<int64_t>{*Op0 * *Op1}; if (I->getOpcode() == Instruction::Shl) - return Optional<int64_t>{Op0.getValue() << Op1.getValue()}; + return Optional<int64_t>{*Op0 << *Op1}; if (I->getOpcode() == Instruction::Or) - return Optional<int64_t>{Op0.getValue() | Op1.getValue()}; + return Optional<int64_t>{*Op0 | *Op1}; } return Optional<int64_t>{}; } diff --git a/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp b/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp index 56d471a..9641791 100644 --- a/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp +++ b/llvm/lib/Target/Hexagon/HexagonFrameLowering.cpp @@ -1021,11 +1021,9 @@ findCFILocation(MachineBasicBlock &B) { } void HexagonFrameLowering::insertCFIInstructions(MachineFunction &MF) const { - for (auto &B : MF) { - auto At = findCFILocation(B); - if (At.hasValue()) - insertCFIInstructionsAt(B, At.getValue()); - } + for (auto &B : MF) + if (auto At = findCFILocation(B)) + insertCFIInstructionsAt(B, *At); } void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB, diff --git a/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp b/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp index 660215c..5ef28cc 100644 --- a/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp +++ b/llvm/lib/Target/Lanai/AsmParser/LanaiAsmParser.cpp @@ -704,15 +704,15 @@ LanaiAsmParser::parseRegister(bool RestoreOnFailure) { if (Lexer.getKind() == AsmToken::Identifier) { RegNum = MatchRegisterName(Lexer.getTok().getIdentifier()); if (RegNum == 0) { - if (PercentTok.hasValue() && RestoreOnFailure) - Lexer.UnLex(PercentTok.getValue()); + if (PercentTok && RestoreOnFailure) + Lexer.UnLex(*PercentTok); return nullptr; } Parser.Lex(); // Eat identifier token return LanaiOperand::createReg(RegNum, Start, End); } - if (PercentTok.hasValue() && RestoreOnFailure) - Lexer.UnLex(PercentTok.getValue()); + if (PercentTok && RestoreOnFailure) + Lexer.UnLex(*PercentTok); return nullptr; } diff --git a/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp b/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp index e52b49e..312ab0a 100644 --- a/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp +++ b/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp @@ -1860,8 +1860,8 @@ SDValue NVPTXTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, Chain = Ret.getValue(1); InFlag = Ret.getValue(2); - if (ProxyRegTruncates[i].hasValue()) { - Ret = DAG.getNode(ISD::TRUNCATE, dl, ProxyRegTruncates[i].getValue(), Ret); + if (ProxyRegTruncates[i]) { + Ret = DAG.getNode(ISD::TRUNCATE, dl, *ProxyRegTruncates[i], Ret); } InVals.push_back(Ret); diff --git a/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp b/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp index caf1457..58b74c6 100644 --- a/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp +++ b/llvm/lib/Target/PowerPC/PPCMacroFusion.cpp @@ -267,13 +267,13 @@ static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, continue; auto DepOpIdx = Feature.depOpIdx(); - if (DepOpIdx.hasValue()) { + if (DepOpIdx) { // Checking if the result of the FirstMI is the desired operand of the // SecondMI if the DepOpIdx is set. Otherwise, ignore it. if (!matchingRegOps(*FirstMI, 0, SecondMI, *DepOpIdx)) return false; } - + // Checking more on the instruction operands. if (checkOpConstraints(Feature.getKind(), *FirstMI, SecondMI)) return true; diff --git a/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp b/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp index dd7a9fe..fe396cb 100644 --- a/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp +++ b/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp @@ -246,10 +246,10 @@ static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT, static Reloc::Model getEffectiveRelocModel(const Triple &TT, Optional<Reloc::Model> RM) { - assert((!TT.isOSAIX() || !RM.hasValue() || *RM == Reloc::PIC_) && + assert((!TT.isOSAIX() || !RM || *RM == Reloc::PIC_) && "Invalid relocation model for AIX."); - if (RM.hasValue()) + if (RM) return *RM; // Big Endian PPC and AIX default to PIC. diff --git a/llvm/lib/Target/VE/VVPISelLowering.cpp b/llvm/lib/Target/VE/VVPISelLowering.cpp index cd67a0f..e4c35da 100644 --- a/llvm/lib/Target/VE/VVPISelLowering.cpp +++ b/llvm/lib/Target/VE/VVPISelLowering.cpp @@ -39,9 +39,9 @@ SDValue VETargetLowering::lowerToVVP(SDValue Op, SelectionDAG &DAG) const { // Can we represent this as a VVP node. const unsigned Opcode = Op->getOpcode(); auto VVPOpcodeOpt = getVVPOpcode(Opcode); - if (!VVPOpcodeOpt.hasValue()) + if (!VVPOpcodeOpt) return SDValue(); - unsigned VVPOpcode = VVPOpcodeOpt.getValue(); + unsigned VVPOpcode = *VVPOpcodeOpt; const bool FromVP = ISD::isVPOpcode(Opcode); // The representative and legalized vector type of this operation. diff --git a/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp b/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp index 61097e1..abc6115 100644 --- a/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp +++ b/llvm/lib/Target/WebAssembly/AsmParser/WebAssemblyAsmTypeCheck.cpp @@ -86,18 +86,15 @@ bool WebAssemblyAsmTypeCheck::popType(SMLoc ErrorLoc, Optional<wasm::ValType> EVT) { if (Stack.empty()) { return typeError(ErrorLoc, - EVT.hasValue() - ? StringRef("empty stack while popping ") + - WebAssembly::typeToString(EVT.getValue()) - : StringRef( - "empty stack while popping value")); + EVT ? StringRef("empty stack while popping ") + + WebAssembly::typeToString(*EVT) + : StringRef("empty stack while popping value")); } auto PVT = Stack.pop_back_val(); - if (EVT.hasValue() && EVT.getValue() != PVT) { - return typeError( - ErrorLoc, StringRef("popped ") + WebAssembly::typeToString(PVT) + - ", expected " + - WebAssembly::typeToString(EVT.getValue())); + if (EVT && *EVT != PVT) { + return typeError(ErrorLoc, + StringRef("popped ") + WebAssembly::typeToString(PVT) + + ", expected " + WebAssembly::typeToString(*EVT)); } return false; } diff --git a/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp b/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp index f09758a..65aa709 100644 --- a/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp +++ b/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp @@ -552,8 +552,8 @@ Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) { Optional<unsigned> NEltArg; std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs(); SizeArg += 1; - if (NEltArg.hasValue()) - NEltArg = NEltArg.getValue() + 1; + if (NEltArg) + NEltArg = *NEltArg + 1; FnAttrs.addAllocSizeAttr(SizeArg, NEltArg); } // In case the callee has 'noreturn' attribute, We need to remove it, because diff --git a/llvm/lib/Transforms/IPO/Attributor.cpp b/llvm/lib/Transforms/IPO/Attributor.cpp index 769d79b..284b9b3 100644 --- a/llvm/lib/Transforms/IPO/Attributor.cpp +++ b/llvm/lib/Transforms/IPO/Attributor.cpp @@ -297,11 +297,11 @@ AA::combineOptionalValuesInAAValueLatice(const Optional<Value *> &A, const Optional<Value *> &B, Type *Ty) { if (A == B) return A; - if (!B.hasValue()) + if (!B) return A; if (*B == nullptr) return nullptr; - if (!A.hasValue()) + if (!A) return Ty ? getWithType(**B, *Ty) : nullptr; if (*A == nullptr) return nullptr; @@ -718,8 +718,8 @@ Argument *IRPosition::getAssociatedArgument() const { } // If we found a unique callback candidate argument, return it. - if (CBCandidateArg.hasValue() && CBCandidateArg.getValue()) - return CBCandidateArg.getValue(); + if (CBCandidateArg && *CBCandidateArg) + return *CBCandidateArg; // If no callbacks were found, or none used the underlying call site operand // exclusively, use the direct callee argument if available. @@ -1048,11 +1048,11 @@ Attributor::getAssumedConstant(const IRPosition &IRP, recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); return llvm::None; } - if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue())) { + if (isa_and_nonnull<UndefValue>(*SimplifiedV)) { recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); return UndefValue::get(IRP.getAssociatedType()); } - Constant *CI = dyn_cast_or_null<Constant>(SimplifiedV.getValue()); + Constant *CI = dyn_cast_or_null<Constant>(*SimplifiedV); if (CI) CI = dyn_cast_or_null<Constant>( AA::getWithType(*CI, *IRP.getAssociatedType())); @@ -2695,10 +2695,10 @@ void InformationCache::initializeInformationCache(const Function &CF, while (!Worklist.empty()) { const Instruction *I = Worklist.pop_back_val(); Optional<short> &NumUses = AssumeUsesMap[I]; - if (!NumUses.hasValue()) + if (!NumUses) NumUses = I->getNumUses(); - NumUses = NumUses.getValue() - /* this assume */ 1; - if (NumUses.getValue() != 0) + NumUses = *NumUses - /* this assume */ 1; + if (*NumUses != 0) continue; AssumeOnlyValues.insert(I); for (const Value *Op : I->operands()) diff --git a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp index b36c712..5483e42 100644 --- a/llvm/lib/Transforms/IPO/AttributorAttributes.cpp +++ b/llvm/lib/Transforms/IPO/AttributorAttributes.cpp @@ -395,9 +395,9 @@ static bool genericValueTraversal( if (UseValueSimplify && !isa<Constant>(V)) { Optional<Value *> SimpleV = A.getAssumedSimplified(*V, QueryingAA, UsedAssumedInformation); - if (!SimpleV.hasValue()) + if (!SimpleV) continue; - Value *NewV = SimpleV.getValue(); + Value *NewV = *SimpleV; if (NewV && NewV != V) { if ((VS & AA::Interprocedural) || !CtxI || AA::isValidInScope(*NewV, CtxI->getFunction())) { @@ -1851,14 +1851,14 @@ ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) { // Check if we have an assumed unique return value that we could manifest. Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A); - if (!UniqueRV.hasValue() || !UniqueRV.getValue()) + if (!UniqueRV || !*UniqueRV) return Changed; // Bookkeeping. STATS_DECLTRACK(UniqueReturnValue, FunctionReturn, "Number of function with unique return"); // If the assumed unique return value is an argument, annotate it. - if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) { + if (auto *UniqueRVArg = dyn_cast<Argument>(*UniqueRV)) { if (UniqueRVArg->getType()->canLosslesslyBitCastTo( getAssociatedFunction()->getReturnType())) { getIRPosition() = IRPosition::argument(*UniqueRVArg); @@ -2626,9 +2626,9 @@ struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior { // Either we stopped and the appropriate action was taken, // or we got back a simplified value to continue. Optional<Value *> SimplifiedPtrOp = stopOnUndefOrAssumed(A, PtrOp, &I); - if (!SimplifiedPtrOp.hasValue() || !SimplifiedPtrOp.getValue()) + if (!SimplifiedPtrOp || !*SimplifiedPtrOp) return true; - const Value *PtrOpVal = SimplifiedPtrOp.getValue(); + const Value *PtrOpVal = *SimplifiedPtrOp; // A memory access through a pointer is considered UB // only if the pointer has constant null value. @@ -2717,15 +2717,14 @@ struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior { IRPosition::value(*ArgVal), *this, UsedAssumedInformation); if (UsedAssumedInformation) continue; - if (SimplifiedVal.hasValue() && !SimplifiedVal.getValue()) + if (SimplifiedVal && !*SimplifiedVal) return true; - if (!SimplifiedVal.hasValue() || - isa<UndefValue>(*SimplifiedVal.getValue())) { + if (!SimplifiedVal || isa<UndefValue>(**SimplifiedVal)) { KnownUBInsts.insert(&I); continue; } if (!ArgVal->getType()->isPointerTy() || - !isa<ConstantPointerNull>(*SimplifiedVal.getValue())) + !isa<ConstantPointerNull>(**SimplifiedVal)) continue; auto &NonNullAA = A.getAAFor<AANonNull>(*this, CalleeArgumentIRP, DepClassTy::NONE); @@ -4062,11 +4061,11 @@ identifyAliveSuccessors(Attributor &A, const SwitchInst &SI, bool UsedAssumedInformation = false; Optional<Constant *> C = A.getAssumedConstant(*SI.getCondition(), AA, UsedAssumedInformation); - if (!C.hasValue() || isa_and_nonnull<UndefValue>(C.getValue())) { + if (!C || isa_and_nonnull<UndefValue>(*C)) { // No value yet, assume all edges are dead. - } else if (isa_and_nonnull<ConstantInt>(C.getValue())) { + } else if (isa_and_nonnull<ConstantInt>(*C)) { for (auto &CaseIt : SI.cases()) { - if (CaseIt.getCaseValue() == C.getValue()) { + if (CaseIt.getCaseValue() == *C) { AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front()); return UsedAssumedInformation; } @@ -5481,11 +5480,11 @@ struct AAValueSimplifyImpl : AAValueSimplify { bool UsedAssumedInformation = false; Optional<Value *> SimpleV = A.getAssumedSimplified(V, QueryingAA, UsedAssumedInformation); - if (!SimpleV.hasValue()) + if (!SimpleV) return PoisonValue::get(&Ty); Value *EffectiveV = &V; - if (SimpleV.getValue()) - EffectiveV = SimpleV.getValue(); + if (*SimpleV) + EffectiveV = *SimpleV; if (auto *C = dyn_cast<Constant>(EffectiveV)) if (!C->canTrap()) return C; @@ -5501,8 +5500,8 @@ struct AAValueSimplifyImpl : AAValueSimplify { /// Return a value we can use as replacement for the associated one, or /// nullptr if we don't have one that makes sense. Value *manifestReplacementValue(Attributor &A, Instruction *CtxI) const { - Value *NewV = SimplifiedAssociatedValue.hasValue() - ? SimplifiedAssociatedValue.getValue() + Value *NewV = SimplifiedAssociatedValue + ? *SimplifiedAssociatedValue : UndefValue::get(getAssociatedType()); if (NewV && NewV != &getAssociatedValue()) { ValueToValueMapTy VMap; @@ -5631,9 +5630,9 @@ struct AAValueSimplifyArgument final : AAValueSimplifyImpl { bool UsedAssumedInformation = false; Optional<Constant *> SimpleArgOp = A.getAssumedConstant(ACSArgPos, *this, UsedAssumedInformation); - if (!SimpleArgOp.hasValue()) + if (!SimpleArgOp) return true; - if (!SimpleArgOp.getValue()) + if (!*SimpleArgOp) return false; if (!AA::isDynamicallyUnique(A, *this, **SimpleArgOp)) return false; @@ -5746,18 +5745,18 @@ struct AAValueSimplifyFloating : AAValueSimplifyImpl { const auto &SimplifiedLHS = A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedLHS.hasValue()) + if (!SimplifiedLHS) return true; - if (!SimplifiedLHS.getValue()) + if (!*SimplifiedLHS) return false; LHS = *SimplifiedLHS; const auto &SimplifiedRHS = A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedRHS.hasValue()) + if (!SimplifiedRHS) return true; - if (!SimplifiedRHS.getValue()) + if (!*SimplifiedRHS) return false; RHS = *SimplifiedRHS; @@ -5826,11 +5825,11 @@ struct AAValueSimplifyFloating : AAValueSimplifyImpl { *this, UsedAssumedInformation); // If we are not sure about any operand we are not sure about the entire // instruction, we'll wait. - if (!SimplifiedOp.hasValue()) + if (!SimplifiedOp) return true; - if (SimplifiedOp.getValue()) - NewOps[Idx] = SimplifiedOp.getValue(); + if (*SimplifiedOp) + NewOps[Idx] = *SimplifiedOp; else NewOps[Idx] = Op; @@ -6249,11 +6248,10 @@ struct AAHeapToStackFunction final : public AAHeapToStack { Alignment = std::max(Alignment, *RetAlign); if (Value *Align = getAllocAlignment(AI.CB, TLI)) { Optional<APInt> AlignmentAPI = getAPInt(A, *this, *Align); - assert(AlignmentAPI.hasValue() && - AlignmentAPI.getValue().getZExtValue() > 0 && + assert(AlignmentAPI && AlignmentAPI->getZExtValue() > 0 && "Expected an alignment during manifest!"); - Alignment = std::max( - Alignment, assumeAligned(AlignmentAPI.getValue().getZExtValue())); + Alignment = + std::max(Alignment, assumeAligned(AlignmentAPI->getZExtValue())); } // TODO: Hoist the alloca towards the function entry. @@ -6299,9 +6297,9 @@ struct AAHeapToStackFunction final : public AAHeapToStack { bool UsedAssumedInformation = false; Optional<Constant *> SimpleV = A.getAssumedConstant(V, AA, UsedAssumedInformation); - if (!SimpleV.hasValue()) + if (!SimpleV) return APInt(64, 0); - if (auto *CI = dyn_cast_or_null<ConstantInt>(SimpleV.getValue())) + if (auto *CI = dyn_cast_or_null<ConstantInt>(*SimpleV)) return CI->getValue(); return llvm::None; } @@ -6578,9 +6576,9 @@ ChangeStatus AAHeapToStackFunction::updateImpl(Attributor &A) { if (MaxHeapToStackSize != -1) { Optional<APInt> Size = getSize(A, *this, AI); - if (!Size.hasValue() || Size.getValue().ugt(MaxHeapToStackSize)) { + if (!Size || Size->ugt(MaxHeapToStackSize)) { LLVM_DEBUG({ - if (!Size.hasValue()) + if (!Size) dbgs() << "[H2S] Unknown allocation size: " << *AI.CB << "\n"; else dbgs() << "[H2S] Allocation size too large: " << *AI.CB << " vs. " @@ -6633,9 +6631,9 @@ struct AAPrivatizablePtrImpl : public AAPrivatizablePtr { /// Return a privatizable type that encloses both T0 and T1. /// TODO: This is merely a stub for now as we should manage a mapping as well. Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) { - if (!T0.hasValue()) + if (!T0) return T1; - if (!T1.hasValue()) + if (!T1) return T0; if (T0 == T1) return T0; @@ -6695,9 +6693,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl { LLVM_DEBUG({ dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: "; - if (CSTy.hasValue() && CSTy.getValue()) - CSTy.getValue()->print(dbgs()); - else if (CSTy.hasValue()) + if (CSTy && *CSTy) + CSTy.value()->print(dbgs()); + else if (CSTy) dbgs() << "<nullptr>"; else dbgs() << "<none>"; @@ -6707,16 +6705,16 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl { LLVM_DEBUG({ dbgs() << " : New Type: "; - if (Ty.hasValue() && Ty.getValue()) - Ty.getValue()->print(dbgs()); - else if (Ty.hasValue()) + if (Ty && *Ty) + (*Ty)->print(dbgs()); + else if (Ty) dbgs() << "<nullptr>"; else dbgs() << "<none>"; dbgs() << "\n"; }); - return !Ty.hasValue() || Ty.getValue(); + return !Ty || *Ty; }; if (!A.checkForAllCallSites(CallSiteCheck, *this, true, @@ -6728,9 +6726,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl { /// See AbstractAttribute::updateImpl(...). ChangeStatus updateImpl(Attributor &A) override { PrivatizableType = identifyPrivatizableType(A); - if (!PrivatizableType.hasValue()) + if (!PrivatizableType) return ChangeStatus::UNCHANGED; - if (!PrivatizableType.getValue()) + if (!*PrivatizableType) return indicatePessimisticFixpoint(); // The dependence is optional so we don't give up once we give up on the @@ -6817,9 +6815,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl { *this, IRPosition::argument(CBArg), DepClassTy::REQUIRED); if (CBArgPrivAA.isValidState()) { auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType(); - if (!CBArgPrivTy.hasValue()) + if (!CBArgPrivTy) continue; - if (CBArgPrivTy.getValue() == PrivatizableType) + if (*CBArgPrivTy == PrivatizableType) continue; } @@ -6864,9 +6862,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl { DepClassTy::REQUIRED); if (DCArgPrivAA.isValidState()) { auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType(); - if (!DCArgPrivTy.hasValue()) + if (!DCArgPrivTy) return true; - if (DCArgPrivTy.getValue() == PrivatizableType) + if (*DCArgPrivTy == PrivatizableType) return true; } } @@ -7006,9 +7004,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl { /// See AbstractAttribute::manifest(...) ChangeStatus manifest(Attributor &A) override { - if (!PrivatizableType.hasValue()) + if (!PrivatizableType) return ChangeStatus::UNCHANGED; - assert(PrivatizableType.getValue() && "Expected privatizable type!"); + assert(*PrivatizableType && "Expected privatizable type!"); // Collect all tail calls in the function as we cannot allow new allocas to // escape into tail recursion. @@ -7041,9 +7039,9 @@ struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl { Instruction *IP = &*EntryBB.getFirstInsertionPt(); const DataLayout &DL = IP->getModule()->getDataLayout(); unsigned AS = DL.getAllocaAddrSpace(); - Instruction *AI = new AllocaInst(PrivatizableType.getValue(), AS, + Instruction *AI = new AllocaInst(*PrivatizableType, AS, Arg->getName() + ".priv", IP); - createInitialization(PrivatizableType.getValue(), *AI, ReplacementFn, + createInitialization(*PrivatizableType, *AI, ReplacementFn, ArgIt->getArgNo(), *IP); if (AI->getType() != Arg->getType()) @@ -7149,9 +7147,9 @@ struct AAPrivatizablePtrCallSiteArgument final /// See AbstractAttribute::updateImpl(...). ChangeStatus updateImpl(Attributor &A) override { PrivatizableType = identifyPrivatizableType(A); - if (!PrivatizableType.hasValue()) + if (!PrivatizableType) return ChangeStatus::UNCHANGED; - if (!PrivatizableType.getValue()) + if (!*PrivatizableType) return indicatePessimisticFixpoint(); const IRPosition &IRP = getIRPosition(); @@ -8610,18 +8608,18 @@ struct AAValueConstantRangeFloating : AAValueConstantRangeImpl { const auto &SimplifiedLHS = A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedLHS.hasValue()) + if (!SimplifiedLHS) return true; - if (!SimplifiedLHS.getValue()) + if (!*SimplifiedLHS) return false; LHS = *SimplifiedLHS; const auto &SimplifiedRHS = A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedRHS.hasValue()) + if (!SimplifiedRHS) return true; - if (!SimplifiedRHS.getValue()) + if (!*SimplifiedRHS) return false; RHS = *SimplifiedRHS; @@ -8663,9 +8661,9 @@ struct AAValueConstantRangeFloating : AAValueConstantRangeImpl { const auto &SimplifiedOpV = A.getAssumedSimplified(IRPosition::value(*OpV, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedOpV.hasValue()) + if (!SimplifiedOpV) return true; - if (!SimplifiedOpV.getValue()) + if (!*SimplifiedOpV) return false; OpV = *SimplifiedOpV; @@ -8693,18 +8691,18 @@ struct AAValueConstantRangeFloating : AAValueConstantRangeImpl { const auto &SimplifiedLHS = A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedLHS.hasValue()) + if (!SimplifiedLHS) return true; - if (!SimplifiedLHS.getValue()) + if (!*SimplifiedLHS) return false; LHS = *SimplifiedLHS; const auto &SimplifiedRHS = A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedRHS.hasValue()) + if (!SimplifiedRHS) return true; - if (!SimplifiedRHS.getValue()) + if (!*SimplifiedRHS) return false; RHS = *SimplifiedRHS; @@ -8767,9 +8765,9 @@ struct AAValueConstantRangeFloating : AAValueConstantRangeImpl { const auto &SimplifiedOpV = A.getAssumedSimplified(IRPosition::value(V, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedOpV.hasValue()) + if (!SimplifiedOpV) return true; - if (!SimplifiedOpV.getValue()) + if (!*SimplifiedOpV) return false; Value *VPtr = *SimplifiedOpV; @@ -9128,18 +9126,18 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl { const auto &SimplifiedLHS = A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedLHS.hasValue()) + if (!SimplifiedLHS) return ChangeStatus::UNCHANGED; - if (!SimplifiedLHS.getValue()) + if (!*SimplifiedLHS) return indicatePessimisticFixpoint(); LHS = *SimplifiedLHS; const auto &SimplifiedRHS = A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedRHS.hasValue()) + if (!SimplifiedRHS) return ChangeStatus::UNCHANGED; - if (!SimplifiedRHS.getValue()) + if (!*SimplifiedRHS) return indicatePessimisticFixpoint(); RHS = *SimplifiedRHS; @@ -9211,18 +9209,18 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl { const auto &SimplifiedLHS = A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedLHS.hasValue()) + if (!SimplifiedLHS) return ChangeStatus::UNCHANGED; - if (!SimplifiedLHS.getValue()) + if (!*SimplifiedLHS) return indicatePessimisticFixpoint(); LHS = *SimplifiedLHS; const auto &SimplifiedRHS = A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedRHS.hasValue()) + if (!SimplifiedRHS) return ChangeStatus::UNCHANGED; - if (!SimplifiedRHS.getValue()) + if (!*SimplifiedRHS) return indicatePessimisticFixpoint(); RHS = *SimplifiedRHS; @@ -9234,9 +9232,9 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl { // Check if we only need one operand. bool OnlyLeft = false, OnlyRight = false; - if (C.hasValue() && *C && (*C)->isOneValue()) + if (C && *C && (*C)->isOneValue()) OnlyLeft = true; - else if (C.hasValue() && *C && (*C)->isZeroValue()) + else if (C && *C && (*C)->isZeroValue()) OnlyRight = true; const AAPotentialConstantValues *LHSAA = nullptr, *RHSAA = nullptr; @@ -9286,9 +9284,9 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl { const auto &SimplifiedSrc = A.getAssumedSimplified(IRPosition::value(*Src, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedSrc.hasValue()) + if (!SimplifiedSrc) return ChangeStatus::UNCHANGED; - if (!SimplifiedSrc.getValue()) + if (!*SimplifiedSrc) return indicatePessimisticFixpoint(); Src = *SimplifiedSrc; @@ -9319,18 +9317,18 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl { const auto &SimplifiedLHS = A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedLHS.hasValue()) + if (!SimplifiedLHS) return ChangeStatus::UNCHANGED; - if (!SimplifiedLHS.getValue()) + if (!*SimplifiedLHS) return indicatePessimisticFixpoint(); LHS = *SimplifiedLHS; const auto &SimplifiedRHS = A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedRHS.hasValue()) + if (!SimplifiedRHS) return ChangeStatus::UNCHANGED; - if (!SimplifiedRHS.getValue()) + if (!*SimplifiedRHS) return indicatePessimisticFixpoint(); RHS = *SimplifiedRHS; @@ -9387,9 +9385,9 @@ struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl { const auto &SimplifiedIncomingValue = A.getAssumedSimplified( IRPosition::value(*IncomingValue, getCallBaseContext()), *this, UsedAssumedInformation); - if (!SimplifiedIncomingValue.hasValue()) + if (!SimplifiedIncomingValue) continue; - if (!SimplifiedIncomingValue.getValue()) + if (!*SimplifiedIncomingValue) return indicatePessimisticFixpoint(); IncomingValue = *SimplifiedIncomingValue; @@ -9876,9 +9874,8 @@ private: bool isReachable(Attributor &A, AAFunctionReachability &AA, ArrayRef<const AACallEdges *> AAEdgesList, const Function &Fn) { - Optional<bool> Cached = isCachedReachable(Fn); - if (Cached.hasValue()) - return Cached.getValue(); + if (Optional<bool> Cached = isCachedReachable(Fn)) + return *Cached; // The query was not cached, thus it is new. We need to request an update // explicitly to make sure this the information is properly run to a diff --git a/llvm/lib/Transforms/IPO/IROutliner.cpp b/llvm/lib/Transforms/IPO/IROutliner.cpp index 89ae575..9ed21de 100644 --- a/llvm/lib/Transforms/IPO/IROutliner.cpp +++ b/llvm/lib/Transforms/IPO/IROutliner.cpp @@ -554,8 +554,8 @@ collectRegionsConstants(OutlinableRegion &Region, // the the number has been found to be not the same value in each instance. for (Value *V : ID.OperVals) { Optional<unsigned> GVNOpt = C.getGVN(V); - assert(GVNOpt.hasValue() && "Expected a GVN for operand?"); - unsigned GVN = GVNOpt.getValue(); + assert(GVNOpt && "Expected a GVN for operand?"); + unsigned GVN = *GVNOpt; // Check if this global value has been found to not be the same already. if (NotSame.contains(GVN)) { @@ -569,8 +569,8 @@ collectRegionsConstants(OutlinableRegion &Region, // global value number. If the global value does not map to a Constant, // it is considered to not be the same value. Optional<bool> ConstantMatches = constantMatches(V, GVN, GVNToConstant); - if (ConstantMatches.hasValue()) { - if (ConstantMatches.getValue()) + if (ConstantMatches) { + if (*ConstantMatches) continue; else ConstantsTheSame = false; @@ -650,8 +650,8 @@ Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group, "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M); // Transfer the swifterr attribute to the correct function parameter. - if (Group.SwiftErrorArgument.hasValue()) - Group.OutlinedFunction->addParamAttr(Group.SwiftErrorArgument.getValue(), + if (Group.SwiftErrorArgument) + Group.OutlinedFunction->addParamAttr(*Group.SwiftErrorArgument, Attribute::SwiftError); Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize); @@ -808,9 +808,8 @@ static void mapInputsToGVNs(IRSimilarityCandidate &C, assert(Input && "Have a nullptr as an input"); if (OutputMappings.find(Input) != OutputMappings.end()) Input = OutputMappings.find(Input)->second; - assert(C.getGVN(Input).hasValue() && - "Could not find a numbering for the given input"); - EndInputNumbers.push_back(C.getGVN(Input).getValue()); + assert(C.getGVN(Input) && "Could not find a numbering for the given input"); + EndInputNumbers.push_back(*C.getGVN(Input)); } } @@ -948,12 +947,12 @@ findExtractedInputToOverallInputMapping(OutlinableRegion &Region, // numbering overrides any discovered location for the extracted code. for (unsigned InputVal : InputGVNs) { Optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal); - assert(CanonicalNumberOpt.hasValue() && "Canonical number not found?"); - unsigned CanonicalNumber = CanonicalNumberOpt.getValue(); + assert(CanonicalNumberOpt && "Canonical number not found?"); + unsigned CanonicalNumber = *CanonicalNumberOpt; Optional<Value *> InputOpt = C.fromGVN(InputVal); - assert(InputOpt.hasValue() && "Global value number not found?"); - Value *Input = InputOpt.getValue(); + assert(InputOpt && "Global value number not found?"); + Value *Input = *InputOpt; DenseMap<unsigned, unsigned>::iterator AggArgIt = Group.CanonicalNumberToAggArg.find(CanonicalNumber); @@ -1235,16 +1234,15 @@ static Optional<unsigned> getGVNForPHINode(OutlinableRegion &Region, DenseMap<hash_code, unsigned>::iterator GVNToPHIIt; DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt; Optional<unsigned> BBGVN = Cand.getGVN(PHIBB); - assert(BBGVN.hasValue() && "Could not find GVN for the incoming block!"); + assert(BBGVN && "Could not find GVN for the incoming block!"); - BBGVN = Cand.getCanonicalNum(BBGVN.getValue()); - assert(BBGVN.hasValue() && - "Could not find canonical number for the incoming block!"); + BBGVN = Cand.getCanonicalNum(*BBGVN); + assert(BBGVN && "Could not find canonical number for the incoming block!"); // Create a pair of the exit block canonical value, and the aggregate // argument location, connected to the canonical numbers stored in the // PHINode. PHINodeData TemporaryPair = - std::make_pair(std::make_pair(BBGVN.getValue(), AggArgIdx), PHIGVNs); + std::make_pair(std::make_pair(*BBGVN, AggArgIdx), PHIGVNs); hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair); // Look for and create a new entry in our connection between canonical @@ -1517,9 +1515,8 @@ CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) { // Make sure that the argument in the new function has the SwiftError // argument. - if (Group.SwiftErrorArgument.hasValue()) - Call->addParamAttr(Group.SwiftErrorArgument.getValue(), - Attribute::SwiftError); + if (Group.SwiftErrorArgument) + Call->addParamAttr(*Group.SwiftErrorArgument, Attribute::SwiftError); return Call; } @@ -1650,9 +1647,9 @@ static void findCanonNumsForPHI( // Find and add the canonical number for the incoming value. Optional<unsigned> GVN = Region.Candidate->getGVN(IVal); - assert(GVN.hasValue() && "No GVN for incoming value"); + assert(GVN && "No GVN for incoming value"); Optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN); - assert(CanonNum.hasValue() && "No Canonical Number for GVN"); + assert(CanonNum && "No Canonical Number for GVN"); CanonNums.push_back(std::make_pair(*CanonNum, IBlock)); } } @@ -2081,12 +2078,11 @@ static void alignOutputBlockWithAggFunc( // If there is, we remove the new output blocks. If it does not, // we add it to our list of sets of output blocks. - if (MatchingBB.hasValue()) { + if (MatchingBB) { LLVM_DEBUG(dbgs() << "Set output block for region in function" - << Region.ExtractedFunction << " to " - << MatchingBB.getValue()); + << Region.ExtractedFunction << " to " << *MatchingBB); - Region.OutputBlockNum = MatchingBB.getValue(); + Region.OutputBlockNum = *MatchingBB; for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) VtoBB.second->eraseFromParent(); return; @@ -2504,9 +2500,9 @@ static Value *findOutputValueInRegion(OutlinableRegion &Region, OutputCanon = *It->second.second.begin(); } Optional<unsigned> OGVN = Region.Candidate->fromCanonicalNum(OutputCanon); - assert(OGVN.hasValue() && "Could not find GVN for Canonical Number?"); + assert(OGVN && "Could not find GVN for Canonical Number?"); Optional<Value *> OV = Region.Candidate->fromGVN(*OGVN); - assert(OV.hasValue() && "Could not find value for GVN?"); + assert(OV && "Could not find value for GVN?"); return *OV; } @@ -2681,15 +2677,14 @@ void IROutliner::updateOutputMapping(OutlinableRegion &Region, if (!OutputIdx) return; - if (OutputMappings.find(Outputs[OutputIdx.getValue()]) == - OutputMappings.end()) { + if (OutputMappings.find(Outputs[*OutputIdx]) == OutputMappings.end()) { LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to " - << *Outputs[OutputIdx.getValue()] << "\n"); - OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.getValue()])); + << *Outputs[*OutputIdx] << "\n"); + OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.value()])); } else { - Value *Orig = OutputMappings.find(Outputs[OutputIdx.getValue()])->second; + Value *Orig = OutputMappings.find(Outputs[OutputIdx.value()])->second; LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to " - << *Outputs[OutputIdx.getValue()] << "\n"); + << *Outputs[*OutputIdx] << "\n"); OutputMappings.insert(std::make_pair(LI, Orig)); } } diff --git a/llvm/lib/Transforms/IPO/OpenMPOpt.cpp b/llvm/lib/Transforms/IPO/OpenMPOpt.cpp index f458afa..20555af 100644 --- a/llvm/lib/Transforms/IPO/OpenMPOpt.cpp +++ b/llvm/lib/Transforms/IPO/OpenMPOpt.cpp @@ -2514,13 +2514,13 @@ struct AAICVTrackerFunction : public AAICVTracker { if (ValuesMap.count(CurrInst)) { Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst); // Unknown value, track new. - if (!ReplVal.hasValue()) { + if (!ReplVal) { ReplVal = NewReplVal; break; } // If we found a new value, we can't know the icv value anymore. - if (NewReplVal.hasValue()) + if (NewReplVal) if (ReplVal != NewReplVal) return nullptr; @@ -2528,11 +2528,11 @@ struct AAICVTrackerFunction : public AAICVTracker { } Optional<Value *> NewReplVal = getValueForCall(A, *CurrInst, ICV); - if (!NewReplVal.hasValue()) + if (!NewReplVal) continue; // Unknown value, track new. - if (!ReplVal.hasValue()) { + if (!ReplVal) { ReplVal = NewReplVal; break; } @@ -4422,13 +4422,13 @@ struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall { std::string Str("simplified value: "); - if (!SimplifiedValue.hasValue()) + if (!SimplifiedValue) return Str + std::string("none"); - if (!SimplifiedValue.getValue()) + if (!SimplifiedValue.value()) return Str + std::string("nullptr"); - if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.getValue())) + if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.value())) return Str + std::to_string(CI->getSExtValue()); return Str + std::string("unknown"); @@ -4452,8 +4452,8 @@ struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall { IRPosition::callsite_returned(CB), [&](const IRPosition &IRP, const AbstractAttribute *AA, bool &UsedAssumedInformation) -> Optional<Value *> { - assert((isValidState() || (SimplifiedValue.hasValue() && - SimplifiedValue.getValue() == nullptr)) && + assert((isValidState() || + (SimplifiedValue && *SimplifiedValue == nullptr)) && "Unexpected invalid state!"); if (!isAtFixpoint()) { diff --git a/llvm/lib/Transforms/IPO/SampleContextTracker.cpp b/llvm/lib/Transforms/IPO/SampleContextTracker.cpp index 9cb558b..caeddae 100644 --- a/llvm/lib/Transforms/IPO/SampleContextTracker.cpp +++ b/llvm/lib/Transforms/IPO/SampleContextTracker.cpp @@ -132,10 +132,10 @@ void ContextTrieNode::setFunctionSamples(FunctionSamples *FSamples) { Optional<uint32_t> ContextTrieNode::getFunctionSize() const { return FuncSize; } void ContextTrieNode::addFunctionSize(uint32_t FSize) { - if (!FuncSize.hasValue()) + if (!FuncSize) FuncSize = 0; - FuncSize = FuncSize.getValue() + FSize; + FuncSize = *FuncSize + FSize; } LineLocation ContextTrieNode::getCallSiteLoc() const { return CallSiteLoc; } diff --git a/llvm/lib/Transforms/IPO/SampleProfile.cpp b/llvm/lib/Transforms/IPO/SampleProfile.cpp index 8e45347..e5d6e26 100644 --- a/llvm/lib/Transforms/IPO/SampleProfile.cpp +++ b/llvm/lib/Transforms/IPO/SampleProfile.cpp @@ -1351,14 +1351,14 @@ SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) { bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) { Optional<InlineCost> Cost = getExternalInlineAdvisorCost(CB); - return Cost ? !!Cost.getValue() : false; + return Cost ? !!*Cost : false; } InlineCost SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) { if (Optional<InlineCost> ReplayCost = getExternalInlineAdvisorCost(*Candidate.CallInstr)) - return ReplayCost.getValue(); + return *ReplayCost; // Adjust threshold based on call site hotness, only do this for callsite // prioritized inliner because otherwise cost-benefit check is done earlier. int SampleThreshold = SampleColdCallSiteThreshold; diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp index 449c0f1..120f991 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp @@ -2677,9 +2677,8 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) { } default: { // Handle target specific intrinsics - Optional<Instruction *> V = targetInstCombineIntrinsic(*II); - if (V.hasValue()) - return V.getValue(); + if (Optional<Instruction *> V = targetInstCombineIntrinsic(*II)) + return *V; break; } } diff --git a/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp b/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp index d801f4d..d8a2a96 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp @@ -924,8 +924,8 @@ Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask, // Handle target specific intrinsics Optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic( *II, DemandedMask, Known, KnownBitsComputed); - if (V.hasValue()) - return V.getValue(); + if (V) + return *V; break; } } @@ -1635,8 +1635,8 @@ Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V, Optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic( *II, DemandedElts, UndefElts, UndefElts2, UndefElts3, simplifyAndSetOp); - if (V.hasValue()) - return V.getValue(); + if (V) + return *V; break; } } // switch on IntrinsicID diff --git a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp index 5cc5804..284a4c2 100644 --- a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp +++ b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp @@ -483,10 +483,10 @@ void ThreadSanitizer::chooseInstructionsToInstrument( static bool isTsanAtomic(const Instruction *I) { // TODO: Ask TTI whether synchronization scope is between threads. auto SSID = getAtomicSyncScopeID(I); - if (!SSID.hasValue()) + if (!SSID) return false; if (isa<LoadInst>(I) || isa<StoreInst>(I)) - return SSID.getValue() != SyncScope::SingleThread; + return *SSID != SyncScope::SingleThread; return true; } diff --git a/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp b/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp index 8a17615..b698503 100644 --- a/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp +++ b/llvm/lib/Transforms/Scalar/ConstantHoisting.cpp @@ -611,9 +611,9 @@ ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S, ConstCand->ConstInt->getValue()); if (Diff) { const InstructionCost ImmCosts = - TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty); + TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, *Diff, Ty); Cost -= ImmCosts; - LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " " + LLVM_DEBUG(dbgs() << "Offset " << *Diff << " " << "has penalty: " << ImmCosts << "\n" << "Adjusted cost: " << Cost << "\n"); } diff --git a/llvm/lib/Transforms/Scalar/GVN.cpp b/llvm/lib/Transforms/Scalar/GVN.cpp index 783301f..af2b48c 100644 --- a/llvm/lib/Transforms/Scalar/GVN.cpp +++ b/llvm/lib/Transforms/Scalar/GVN.cpp @@ -748,14 +748,14 @@ void GVNPass::printPipeline( OS << "<"; if (Options.AllowPRE != None) - OS << (Options.AllowPRE.getValue() ? "" : "no-") << "pre;"; + OS << (*Options.AllowPRE ? "" : "no-") << "pre;"; if (Options.AllowLoadPRE != None) - OS << (Options.AllowLoadPRE.getValue() ? "" : "no-") << "load-pre;"; + OS << (*Options.AllowLoadPRE ? "" : "no-") << "load-pre;"; if (Options.AllowLoadPRESplitBackedge != None) - OS << (Options.AllowLoadPRESplitBackedge.getValue() ? "" : "no-") + OS << (*Options.AllowLoadPRESplitBackedge ? "" : "no-") << "split-backedge-load-pre;"; if (Options.AllowMemDep != None) - OS << (Options.AllowMemDep.getValue() ? "" : "no-") << "memdep"; + OS << (*Options.AllowMemDep ? "" : "no-") << "memdep"; OS << ">"; } diff --git a/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp b/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp index 0e27c85..94ed288 100644 --- a/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp +++ b/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp @@ -1427,9 +1427,9 @@ bool LoopConstrainer::run() { // constructor. ClonedLoop PreLoop, PostLoop; bool NeedsPreLoop = - Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue(); + Increasing ? SR.LowLimit.has_value() : SR.HighLimit.has_value(); bool NeedsPostLoop = - Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue(); + Increasing ? SR.HighLimit.has_value() : SR.LowLimit.has_value(); Value *ExitPreLoopAt = nullptr; Value *ExitMainLoopAt = nullptr; @@ -1708,9 +1708,9 @@ IntersectSignedRange(ScalarEvolution &SE, const InductiveRangeCheck::Range &R2) { if (R2.isEmpty(SE, /* IsSigned */ true)) return None; - if (!R1.hasValue()) + if (!R1) return R2; - auto &R1Value = R1.getValue(); + auto &R1Value = *R1; // We never return empty ranges from this function, and R1 is supposed to be // a result of intersection. Thus, R1 is never empty. assert(!R1Value.isEmpty(SE, /* IsSigned */ true) && @@ -1737,9 +1737,9 @@ IntersectUnsignedRange(ScalarEvolution &SE, const InductiveRangeCheck::Range &R2) { if (R2.isEmpty(SE, /* IsSigned */ false)) return None; - if (!R1.hasValue()) + if (!R1) return R2; - auto &R1Value = R1.getValue(); + auto &R1Value = *R1; // We never return empty ranges from this function, and R1 is supposed to be // a result of intersection. Thus, R1 is never empty. assert(!R1Value.isEmpty(SE, /* IsSigned */ false) && @@ -1948,24 +1948,21 @@ bool InductiveRangeCheckElimination::run( for (InductiveRangeCheck &IRC : RangeChecks) { auto Result = IRC.computeSafeIterationSpace(SE, IndVar, LS.IsSignedPredicate); - if (Result.hasValue()) { - auto MaybeSafeIterRange = - IntersectRange(SE, SafeIterRange, Result.getValue()); - if (MaybeSafeIterRange.hasValue()) { - assert( - !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) && - "We should never return empty ranges!"); + if (Result) { + auto MaybeSafeIterRange = IntersectRange(SE, SafeIterRange, *Result); + if (MaybeSafeIterRange) { + assert(!MaybeSafeIterRange->isEmpty(SE, LS.IsSignedPredicate) && + "We should never return empty ranges!"); RangeChecksToEliminate.push_back(IRC); - SafeIterRange = MaybeSafeIterRange.getValue(); + SafeIterRange = *MaybeSafeIterRange; } } } - if (!SafeIterRange.hasValue()) + if (!SafeIterRange) return false; - LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT, - SafeIterRange.getValue()); + LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT, *SafeIterRange); bool Changed = LC.run(); if (Changed) { diff --git a/llvm/lib/Transforms/Scalar/LoopDistribute.cpp b/llvm/lib/Transforms/Scalar/LoopDistribute.cpp index f606e9b..f70ab0d 100644 --- a/llvm/lib/Transforms/Scalar/LoopDistribute.cpp +++ b/llvm/lib/Transforms/Scalar/LoopDistribute.cpp @@ -600,9 +600,9 @@ private: {LLVMLoopDistributeFollowupAll, Part->hasDepCycle() ? LLVMLoopDistributeFollowupSequential : LLVMLoopDistributeFollowupCoincident}); - if (PartitionID.hasValue()) { + if (PartitionID) { Loop *NewLoop = Part->getDistributedLoop(); - NewLoop->setLoopID(PartitionID.getValue()); + NewLoop->setLoopID(*PartitionID); } } }; @@ -821,12 +821,10 @@ public: // The unversioned loop will not be changed, so we inherit all attributes // from the original loop, but remove the loop distribution metadata to // avoid to distribute it again. - MDNode *UnversionedLoopID = - makeFollowupLoopID(OrigLoopID, - {LLVMLoopDistributeFollowupAll, - LLVMLoopDistributeFollowupFallback}, - "llvm.loop.distribute.", true) - .getValue(); + MDNode *UnversionedLoopID = *makeFollowupLoopID( + OrigLoopID, + {LLVMLoopDistributeFollowupAll, LLVMLoopDistributeFollowupFallback}, + "llvm.loop.distribute.", true); LVer.getNonVersionedLoop()->setLoopID(UnversionedLoopID); } diff --git a/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp b/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp index 6d4c675..4bcf102 100644 --- a/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp +++ b/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp @@ -1481,9 +1481,9 @@ bool LoopIdiomRecognize::processLoopStoreOfLoopLoad( return Changed; // We cannot allow unaligned ops for unordered load/store, so reject // anything where the alignment isn't at least the element size. - assert((StoreAlign.hasValue() && LoadAlign.hasValue()) && + assert((StoreAlign && LoadAlign) && "Expect unordered load/store to have align."); - if (StoreAlign.getValue() < StoreSize || LoadAlign.getValue() < StoreSize) + if (*StoreAlign < StoreSize || *LoadAlign < StoreSize) return Changed; // If the element.atomic memcpy is not lowered into explicit @@ -1497,9 +1497,8 @@ bool LoopIdiomRecognize::processLoopStoreOfLoopLoad( // Note that unordered atomic loads/stores are *required* by the spec to // have an alignment but non-atomic loads/stores may not. NewCall = Builder.CreateElementUnorderedAtomicMemCpy( - StoreBasePtr, StoreAlign.getValue(), LoadBasePtr, LoadAlign.getValue(), - NumBytes, StoreSize, AATags.TBAA, AATags.TBAAStruct, AATags.Scope, - AATags.NoAlias); + StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, StoreSize, + AATags.TBAA, AATags.TBAAStruct, AATags.Scope, AATags.NoAlias); } NewCall->setDebugLoc(TheStore->getDebugLoc()); diff --git a/llvm/lib/Transforms/Scalar/LoopRotation.cpp b/llvm/lib/Transforms/Scalar/LoopRotation.cpp index 533c853..d9c33b5f 100644 --- a/llvm/lib/Transforms/Scalar/LoopRotation.cpp +++ b/llvm/lib/Transforms/Scalar/LoopRotation.cpp @@ -60,8 +60,8 @@ PreservedAnalyses LoopRotatePass::run(Loop &L, LoopAnalysisManager &AM, MSSAU = MemorySSAUpdater(AR.MSSA); bool Changed = LoopRotation(&L, &AR.LI, &AR.TTI, &AR.AC, &AR.DT, &AR.SE, - MSSAU.hasValue() ? MSSAU.getPointer() : nullptr, SQ, false, - Threshold, false, PrepareForLTO || PrepareForLTOOption); + MSSAU ? MSSAU.getPointer() : nullptr, SQ, false, Threshold, + false, PrepareForLTO || PrepareForLTOOption); if (!Changed) return PreservedAnalyses::all(); @@ -131,9 +131,8 @@ public: : MaxHeaderSize; return LoopRotation(L, LI, TTI, AC, &DT, &SE, - MSSAU.hasValue() ? MSSAU.getPointer() : nullptr, SQ, - false, Threshold, false, - PrepareForLTO || PrepareForLTOOption); + MSSAU ? MSSAU.getPointer() : nullptr, SQ, false, + Threshold, false, PrepareForLTO || PrepareForLTOOption); } }; } // end namespace diff --git a/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp b/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp index c2c29d9..51007b9 100644 --- a/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp +++ b/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp @@ -735,9 +735,9 @@ public: if (MSSAA && VerifyMemorySSA) MSSAU->getMemorySSA()->verifyMemorySSA(); bool DeleteCurrentLoop = false; - bool Changed = simplifyLoopCFG( - *L, DT, LI, SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr, - DeleteCurrentLoop); + bool Changed = + simplifyLoopCFG(*L, DT, LI, SE, MSSAU ? MSSAU.getPointer() : nullptr, + DeleteCurrentLoop); if (DeleteCurrentLoop) LPM.markLoopAsDeleted(*L); return Changed; diff --git a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp index 9959e40..49c3083 100644 --- a/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp +++ b/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp @@ -6406,9 +6406,8 @@ static bool SalvageDVI(llvm::Loop *L, ScalarEvolution &SE, // less DWARF ops than an iteration count-based expression. if (Optional<APInt> Offset = SE.computeConstantDifference(DVIRec.SCEVs[i], SCEVInductionVar)) { - if (Offset.getValue().getMinSignedBits() <= 64) - SalvageExpr->createOffsetExpr(Offset.getValue().getSExtValue(), - LSRInductionVar); + if (Offset->getMinSignedBits() <= 64) + SalvageExpr->createOffsetExpr(Offset->getSExtValue(), LSRInductionVar); } else if (!SalvageExpr->createIterCountExpr(DVIRec.SCEVs[i], IterCountExpr, SE)) return false; diff --git a/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp b/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp index a33e5cc..8ea8f28 100644 --- a/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp +++ b/llvm/lib/Transforms/Scalar/LoopUnrollAndJamPass.cpp @@ -372,8 +372,8 @@ tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, Optional<MDNode *> NewInnerEpilogueLoopID = makeFollowupLoopID( OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupRemainderInner}); - if (NewInnerEpilogueLoopID.hasValue()) - SubLoop->setLoopID(NewInnerEpilogueLoopID.getValue()); + if (NewInnerEpilogueLoopID) + SubLoop->setLoopID(*NewInnerEpilogueLoopID); // Find trip count and trip multiple BasicBlock *Latch = L->getLoopLatch(); @@ -402,15 +402,15 @@ tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, Optional<MDNode *> NewOuterEpilogueLoopID = makeFollowupLoopID( OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupRemainderOuter}); - if (NewOuterEpilogueLoopID.hasValue()) - EpilogueOuterLoop->setLoopID(NewOuterEpilogueLoopID.getValue()); + if (NewOuterEpilogueLoopID) + EpilogueOuterLoop->setLoopID(*NewOuterEpilogueLoopID); } Optional<MDNode *> NewInnerLoopID = makeFollowupLoopID(OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupInner}); - if (NewInnerLoopID.hasValue()) - SubLoop->setLoopID(NewInnerLoopID.getValue()); + if (NewInnerLoopID) + SubLoop->setLoopID(*NewInnerLoopID); else SubLoop->setLoopID(OrigSubLoopID); @@ -418,8 +418,8 @@ tryToUnrollAndJamLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, Optional<MDNode *> NewOuterLoopID = makeFollowupLoopID( OrigOuterLoopID, {LLVMLoopUnrollAndJamFollowupAll, LLVMLoopUnrollAndJamFollowupOuter}); - if (NewOuterLoopID.hasValue()) { - L->setLoopID(NewOuterLoopID.getValue()); + if (NewOuterLoopID) { + L->setLoopID(*NewOuterLoopID); // Do not setLoopAlreadyUnrolled if a followup was given. return UnrollResult; diff --git a/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp b/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp index 1969513..08f21be 100644 --- a/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp +++ b/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp @@ -253,19 +253,19 @@ TargetTransformInfo::UnrollingPreferences llvm::gatherUnrollingPreferences( UP.MaxIterationsCountToAnalyze = UnrollMaxIterationsCountToAnalyze; // Apply user values provided by argument - if (UserThreshold.hasValue()) { + if (UserThreshold) { UP.Threshold = *UserThreshold; UP.PartialThreshold = *UserThreshold; } - if (UserCount.hasValue()) + if (UserCount) UP.Count = *UserCount; - if (UserAllowPartial.hasValue()) + if (UserAllowPartial) UP.Partial = *UserAllowPartial; - if (UserRuntime.hasValue()) + if (UserRuntime) UP.Runtime = *UserRuntime; - if (UserUpperBound.hasValue()) + if (UserUpperBound) UP.UpperBound = *UserUpperBound; - if (UserFullUnrollMaxCount.hasValue()) + if (UserFullUnrollMaxCount) UP.FullUnrollMaxCount = *UserFullUnrollMaxCount; return UP; @@ -1323,16 +1323,16 @@ static LoopUnrollResult tryToUnrollLoop( Optional<MDNode *> RemainderLoopID = makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder}); - if (RemainderLoopID.hasValue()) - RemainderLoop->setLoopID(RemainderLoopID.getValue()); + if (RemainderLoopID) + RemainderLoop->setLoopID(*RemainderLoopID); } if (UnrollResult != LoopUnrollResult::FullyUnrolled) { Optional<MDNode *> NewLoopID = makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupUnrolled}); - if (NewLoopID.hasValue()) { - L->setLoopID(NewLoopID.getValue()); + if (NewLoopID) { + L->setLoopID(*NewLoopID); // Do not setLoopAlreadyUnrolled if loop attributes have been specified // explicitly. @@ -1645,15 +1645,15 @@ void LoopUnrollPass::printPipeline( OS, MapClassName2PassName); OS << "<"; if (UnrollOpts.AllowPartial != None) - OS << (UnrollOpts.AllowPartial.getValue() ? "" : "no-") << "partial;"; + OS << (*UnrollOpts.AllowPartial ? "" : "no-") << "partial;"; if (UnrollOpts.AllowPeeling != None) - OS << (UnrollOpts.AllowPeeling.getValue() ? "" : "no-") << "peeling;"; + OS << (*UnrollOpts.AllowPeeling ? "" : "no-") << "peeling;"; if (UnrollOpts.AllowRuntime != None) - OS << (UnrollOpts.AllowRuntime.getValue() ? "" : "no-") << "runtime;"; + OS << (*UnrollOpts.AllowRuntime ? "" : "no-") << "runtime;"; if (UnrollOpts.AllowUpperBound != None) - OS << (UnrollOpts.AllowUpperBound.getValue() ? "" : "no-") << "upperbound;"; + OS << (*UnrollOpts.AllowUpperBound ? "" : "no-") << "upperbound;"; if (UnrollOpts.AllowProfileBasedPeeling != None) - OS << (UnrollOpts.AllowProfileBasedPeeling.getValue() ? "" : "no-") + OS << (*UnrollOpts.AllowProfileBasedPeeling ? "" : "no-") << "profile-peeling;"; if (UnrollOpts.FullUnrollMaxCount != None) OS << "full-unroll-max=" << UnrollOpts.FullUnrollMaxCount << ";"; diff --git a/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp b/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp index a886563..47493b5 100644 --- a/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp +++ b/llvm/lib/Transforms/Scalar/LowerConstantIntrinsics.cpp @@ -143,10 +143,10 @@ static bool lowerConstantIntrinsics(Function &F, const TargetLibraryInfo &TLI, break; } HasDeadBlocks |= replaceConditionalBranchesOnConstant( - II, NewValue, DTU.hasValue() ? DTU.getPointer() : nullptr); + II, NewValue, DTU ? DTU.getPointer() : nullptr); } if (HasDeadBlocks) - removeUnreachableBlocks(F, DTU.hasValue() ? DTU.getPointer() : nullptr); + removeUnreachableBlocks(F, DTU ? DTU.getPointer() : nullptr); return !Worklist.empty(); } diff --git a/llvm/lib/Transforms/Utils/CodeExtractor.cpp b/llvm/lib/Transforms/Utils/CodeExtractor.cpp index c4ef979..8240386 100644 --- a/llvm/lib/Transforms/Utils/CodeExtractor.cpp +++ b/llvm/lib/Transforms/Utils/CodeExtractor.cpp @@ -1775,9 +1775,9 @@ CodeExtractor::extractCodeRegion(const CodeExtractorAnalysisCache &CEAC, // Update the entry count of the function. if (BFI) { auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency()); - if (Count.hasValue()) + if (Count) newFunction->setEntryCount( - ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME + ProfileCount(*Count, Function::PCT_Real)); // FIXME BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency()); } diff --git a/llvm/lib/Transforms/Utils/LoopPeel.cpp b/llvm/lib/Transforms/Utils/LoopPeel.cpp index 7f0852c..f093fea 100644 --- a/llvm/lib/Transforms/Utils/LoopPeel.cpp +++ b/llvm/lib/Transforms/Utils/LoopPeel.cpp @@ -719,9 +719,9 @@ TargetTransformInfo::PeelingPreferences llvm::gatherPeelingPreferences( } // User specifed values provided by argument. - if (UserAllowPeeling.hasValue()) + if (UserAllowPeeling) PP.AllowPeeling = *UserAllowPeeling; - if (UserAllowProfileBasedPeeling.hasValue()) + if (UserAllowProfileBasedPeeling) PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling; return PP; diff --git a/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp b/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp index df24af5..295ae03 100644 --- a/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp +++ b/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp @@ -397,8 +397,8 @@ CloneLoopBlocks(Loop *L, Value *NewIter, const bool UseEpilogRemainder, Optional<MDNode *> NewLoopID = makeFollowupLoopID( LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder}); - if (NewLoopID.hasValue()) { - NewLoop->setLoopID(NewLoopID.getValue()); + if (NewLoopID) { + NewLoop->setLoopID(*NewLoopID); // Do not setLoopAlreadyUnrolled if loop attributes have been defined // explicitly. diff --git a/llvm/lib/Transforms/Utils/LoopUtils.cpp b/llvm/lib/Transforms/Utils/LoopUtils.cpp index b7656f4..7dc94d8 100644 --- a/llvm/lib/Transforms/Utils/LoopUtils.cpp +++ b/llvm/lib/Transforms/Utils/LoopUtils.cpp @@ -358,8 +358,8 @@ TransformationMode llvm::hasUnrollTransformation(const Loop *L) { Optional<int> Count = getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count"); - if (Count.hasValue()) - return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; + if (Count) + return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser; if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable")) return TM_ForcedByUser; @@ -379,8 +379,8 @@ TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) { Optional<int> Count = getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count"); - if (Count.hasValue()) - return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; + if (Count) + return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser; if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable")) return TM_ForcedByUser; diff --git a/llvm/lib/Transforms/Utils/MisExpect.cpp b/llvm/lib/Transforms/Utils/MisExpect.cpp index 5ace0c6..a7acd8d 100644 --- a/llvm/lib/Transforms/Utils/MisExpect.cpp +++ b/llvm/lib/Transforms/Utils/MisExpect.cpp @@ -219,18 +219,18 @@ void verifyMisExpect(Instruction &I, ArrayRef<uint32_t> RealWeights, void checkBackendInstrumentation(Instruction &I, const ArrayRef<uint32_t> RealWeights) { auto ExpectedWeightsOpt = extractWeights(&I, I.getContext()); - if (!ExpectedWeightsOpt.hasValue()) + if (!ExpectedWeightsOpt) return; - auto ExpectedWeights = ExpectedWeightsOpt.getValue(); + auto ExpectedWeights = *ExpectedWeightsOpt; verifyMisExpect(I, RealWeights, ExpectedWeights); } void checkFrontendInstrumentation(Instruction &I, const ArrayRef<uint32_t> ExpectedWeights) { auto RealWeightsOpt = extractWeights(&I, I.getContext()); - if (!RealWeightsOpt.hasValue()) + if (!RealWeightsOpt) return; - auto RealWeights = RealWeightsOpt.getValue(); + auto RealWeights = *RealWeightsOpt; verifyMisExpect(I, RealWeights, ExpectedWeights); } diff --git a/llvm/lib/Transforms/Utils/ModuleUtils.cpp b/llvm/lib/Transforms/Utils/ModuleUtils.cpp index 7388a4b..694837a 100644 --- a/llvm/lib/Transforms/Utils/ModuleUtils.cpp +++ b/llvm/lib/Transforms/Utils/ModuleUtils.cpp @@ -254,8 +254,8 @@ void VFABI::setVectorVariantNames(CallInst *CI, for (const std::string &VariantMapping : VariantMappings) { LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << VariantMapping << "'\n"); Optional<VFInfo> VI = VFABI::tryDemangleForVFABI(VariantMapping, *M); - assert(VI.hasValue() && "Cannot add an invalid VFABI name."); - assert(M->getNamedValue(VI.getValue().VectorName) && + assert(VI && "Cannot add an invalid VFABI name."); + assert(M->getNamedValue(VI->VectorName) && "Cannot add variant to attribute: " "vector function declaration is missing."); } diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp index 5e7a762..8ab7fc0 100644 --- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp +++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp @@ -4877,8 +4877,8 @@ LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) { if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange)) MaxVScale = TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax(); - MaxScalableVF = ElementCount::getScalable( - MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0); + MaxScalableVF = + ElementCount::getScalable(MaxVScale ? (MaxSafeElements / *MaxVScale) : 0); if (!MaxScalableVF) reportVectorizationInfo( "Max legal vector width too small, scalable vectorization " @@ -5273,9 +5273,9 @@ bool LoopVectorizationCostModel::isMoreProfitable( unsigned EstimatedWidthB = B.Width.getKnownMinValue(); if (Optional<unsigned> VScale = getVScaleForTuning()) { if (A.Width.isScalable()) - EstimatedWidthA *= VScale.getValue(); + EstimatedWidthA *= *VScale; if (B.Width.isScalable()) - EstimatedWidthB *= VScale.getValue(); + EstimatedWidthB *= *VScale; } // Assume vscale may be larger than 1 (or the value being tuned for), @@ -7612,8 +7612,8 @@ void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF, VPBasicBlock *HeaderVPBB = BestVPlan.getVectorLoopRegion()->getEntryBasicBlock(); Loop *L = LI->getLoopFor(State.CFG.VPBB2IRBB[HeaderVPBB]); - if (VectorizedLoopID.hasValue()) - L->setLoopID(VectorizedLoopID.getValue()); + if (VectorizedLoopID) + L->setLoopID(*VectorizedLoopID); else { // Keep all loop hints from the original loop on the vector loop (we'll // replace the vectorizer-specific hints below). @@ -10622,8 +10622,8 @@ bool LoopVectorizePass::processLoop(Loop *L) { Optional<MDNode *> RemainderLoopID = makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll, LLVMLoopVectorizeFollowupEpilogue}); - if (RemainderLoopID.hasValue()) { - L->setLoopID(RemainderLoopID.getValue()); + if (RemainderLoopID) { + L->setLoopID(*RemainderLoopID); } else { if (DisableRuntimeUnroll) AddRuntimeUnrollDisableMetaData(L); diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp index d7769ef..a9bccbc 100644 --- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp +++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp @@ -2636,8 +2636,8 @@ private: // First check if the result is already in the cache. AliasCacheKey key = std::make_pair(Inst1, Inst2); Optional<bool> &result = AliasCache[key]; - if (result.hasValue()) { - return result.getValue(); + if (result) { + return *result; } bool aliased = true; if (Loc1.Ptr && isSimple(Inst1)) diff --git a/llvm/lib/WindowsDriver/MSVCPaths.cpp b/llvm/lib/WindowsDriver/MSVCPaths.cpp index 46a4426b..0661ed7 100644 --- a/llvm/lib/WindowsDriver/MSVCPaths.cpp +++ b/llvm/lib/WindowsDriver/MSVCPaths.cpp @@ -98,14 +98,14 @@ static bool getWindowsSDKDirViaCommandLine( llvm::Optional<llvm::StringRef> WinSdkVersion, llvm::Optional<llvm::StringRef> WinSysRoot, std::string &Path, int &Major, std::string &Version) { - if (WinSdkDir.hasValue() || WinSysRoot.hasValue()) { + if (WinSdkDir || WinSysRoot) { // Don't validate the input; trust the value supplied by the user. // The motivation is to prevent unnecessary file and registry access. llvm::VersionTuple SDKVersion; - if (WinSdkVersion.hasValue()) + if (WinSdkVersion) SDKVersion.tryParse(*WinSdkVersion); - if (WinSysRoot.hasValue()) { + if (WinSysRoot) { llvm::SmallString<128> SDKPath(*WinSysRoot); llvm::sys::path::append(SDKPath, "Windows Kits"); if (!SDKVersion.empty()) @@ -479,12 +479,12 @@ bool findVCToolChainViaCommandLine(vfs::FileSystem &VFS, std::string &Path, ToolsetLayout &VSLayout) { // Don't validate the input; trust the value supplied by the user. // The primary motivation is to prevent unnecessary file and registry access. - if (VCToolsDir.hasValue() || WinSysRoot.hasValue()) { - if (WinSysRoot.hasValue()) { + if (VCToolsDir || WinSysRoot) { + if (WinSysRoot) { SmallString<128> ToolsPath(*WinSysRoot); sys::path::append(ToolsPath, "VC", "Tools", "MSVC"); std::string ToolsVersion; - if (VCToolsVersion.hasValue()) + if (VCToolsVersion) ToolsVersion = VCToolsVersion->str(); else ToolsVersion = getHighestNumericTupleInDirectory(VFS, ToolsPath); diff --git a/llvm/tools/lli/lli.cpp b/llvm/tools/lli/lli.cpp index f2e3886..2bc7391 100644 --- a/llvm/tools/lli/lli.cpp +++ b/llvm/tools/lli/lli.cpp @@ -536,9 +536,9 @@ int main(int argc, char **argv, char * const *envp) { builder.setMCPU(codegen::getCPUStr()); builder.setMAttrs(codegen::getFeatureList()); if (auto RM = codegen::getExplicitRelocModel()) - builder.setRelocationModel(RM.getValue()); + builder.setRelocationModel(RM.value()); if (auto CM = codegen::getExplicitCodeModel()) - builder.setCodeModel(CM.getValue()); + builder.setCodeModel(CM.value()); builder.setErrorStr(&ErrorMsg); builder.setEngineKind(ForceInterpreter ? EngineKind::Interpreter diff --git a/llvm/tools/llvm-cov/CoverageExporterJson.cpp b/llvm/tools/llvm-cov/CoverageExporterJson.cpp index d341abe..2e161f5 100644 --- a/llvm/tools/llvm-cov/CoverageExporterJson.cpp +++ b/llvm/tools/llvm-cov/CoverageExporterJson.cpp @@ -291,8 +291,8 @@ void CoverageExporterJson::renderRoot(ArrayRef<std::string> SourceFiles) { const json::Object *ObjB = B.getAsObject(); assert(ObjA != nullptr && "Value A was not an Object"); assert(ObjB != nullptr && "Value B was not an Object"); - const StringRef FilenameA = ObjA->getString("filename").getValue(); - const StringRef FilenameB = ObjB->getString("filename").getValue(); + const StringRef FilenameA = ObjA->getString("filename").value(); + const StringRef FilenameB = ObjB->getString("filename").value(); return FilenameA.compare(FilenameB) < 0; }); auto Export = json::Object( diff --git a/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp b/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp index f38eb00..46782c9 100644 --- a/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp +++ b/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp @@ -561,12 +561,12 @@ void SourceCoverageViewHTML::renderLine(raw_ostream &OS, LineRef L, else Color = None; - if (Color.hasValue()) + if (Color) Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col, CurSeg->Col + Snippets[I + 1].size()); } - if (Color.hasValue() && Segments.empty()) + if (Color && Segments.empty()) Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size()); if (getOptions().Debug) { diff --git a/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp b/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp index 049cc68..0ad6645 100644 --- a/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp +++ b/llvm/tools/llvm-exegesis/lib/MCInstrDescView.cpp @@ -47,9 +47,9 @@ bool Operand::isUse() const { return !IsDef; } bool Operand::isReg() const { return Tracker; } -bool Operand::isTied() const { return TiedToIndex.hasValue(); } +bool Operand::isTied() const { return TiedToIndex.has_value(); } -bool Operand::isVariable() const { return VariableIndex.hasValue(); } +bool Operand::isVariable() const { return VariableIndex.has_value(); } bool Operand::isMemory() const { return isExplicit() && diff --git a/llvm/tools/llvm-ifs/llvm-ifs.cpp b/llvm/tools/llvm-ifs/llvm-ifs.cpp index f9b6a8c..6909bd1 100644 --- a/llvm/tools/llvm-ifs/llvm-ifs.cpp +++ b/llvm/tools/llvm-ifs/llvm-ifs.cpp @@ -533,34 +533,33 @@ int main(int argc, char *argv[]) { << "Triple should be defined when output format is TBD"; return -1; } - return writeTbdStub(llvm::Triple(Stub.Target.Triple.getValue()), + return writeTbdStub(llvm::Triple(Stub.Target.Triple.value()), Stub.Symbols, "TBD", Out); } case FileFormat::IFS: { Stub.IfsVersion = IfsVersionCurrent; - if (Config.InputFormat.getValue() == FileFormat::ELF && + if (Config.InputFormat.value() == FileFormat::ELF && Config.HintIfsTarget) { std::error_code HintEC(1, std::generic_category()); IFSTarget HintTarget = parseTriple(*Config.HintIfsTarget); - if (Stub.Target.Arch.getValue() != HintTarget.Arch.getValue()) + if (Stub.Target.Arch.value() != HintTarget.Arch.value()) fatalError(make_error<StringError>( "Triple hint does not match the actual architecture", HintEC)); - if (Stub.Target.Endianness.getValue() != - HintTarget.Endianness.getValue()) + if (Stub.Target.Endianness.value() != HintTarget.Endianness.value()) fatalError(make_error<StringError>( "Triple hint does not match the actual endianness", HintEC)); - if (Stub.Target.BitWidth.getValue() != HintTarget.BitWidth.getValue()) + if (Stub.Target.BitWidth.value() != HintTarget.BitWidth.value()) fatalError(make_error<StringError>( "Triple hint does not match the actual bit width", HintEC)); stripIFSTarget(Stub, true, false, false, false); - Stub.Target.Triple = Config.HintIfsTarget.getValue(); + Stub.Target.Triple = Config.HintIfsTarget.value(); } else { stripIFSTarget(Stub, Config.StripIfsTarget, Config.StripIfsArch, Config.StripIfsEndianness, Config.StripIfsBitwidth); } Error IFSWriteError = - writeIFS(Config.Output.getValue(), Stub, Config.WriteIfChanged); + writeIFS(Config.Output.value(), Stub, Config.WriteIfChanged); if (IFSWriteError) fatalError(std::move(IFSWriteError)); break; @@ -589,29 +588,28 @@ int main(int argc, char *argv[]) { } if (Config.OutputIfs) { Stub.IfsVersion = IfsVersionCurrent; - if (Config.InputFormat.getValue() == FileFormat::ELF && + if (Config.InputFormat.value() == FileFormat::ELF && Config.HintIfsTarget) { std::error_code HintEC(1, std::generic_category()); IFSTarget HintTarget = parseTriple(*Config.HintIfsTarget); - if (Stub.Target.Arch.getValue() != HintTarget.Arch.getValue()) + if (Stub.Target.Arch.value() != HintTarget.Arch.value()) fatalError(make_error<StringError>( "Triple hint does not match the actual architecture", HintEC)); - if (Stub.Target.Endianness.getValue() != - HintTarget.Endianness.getValue()) + if (Stub.Target.Endianness.value() != HintTarget.Endianness.value()) fatalError(make_error<StringError>( "Triple hint does not match the actual endianness", HintEC)); - if (Stub.Target.BitWidth.getValue() != HintTarget.BitWidth.getValue()) + if (Stub.Target.BitWidth.value() != HintTarget.BitWidth.value()) fatalError(make_error<StringError>( "Triple hint does not match the actual bit width", HintEC)); stripIFSTarget(Stub, true, false, false, false); - Stub.Target.Triple = Config.HintIfsTarget.getValue(); + Stub.Target.Triple = Config.HintIfsTarget.value(); } else { stripIFSTarget(Stub, Config.StripIfsTarget, Config.StripIfsArch, Config.StripIfsEndianness, Config.StripIfsBitwidth); } Error IFSWriteError = - writeIFS(Config.OutputIfs.getValue(), Stub, Config.WriteIfChanged); + writeIFS(Config.OutputIfs.value(), Stub, Config.WriteIfChanged); if (IFSWriteError) fatalError(std::move(IFSWriteError)); } @@ -628,8 +626,8 @@ int main(int argc, char *argv[]) { << "Triple should be defined when output format is TBD"; return -1; } - return writeTbdStub(llvm::Triple(Stub.Target.Triple.getValue()), - Stub.Symbols, "TBD", Out); + return writeTbdStub(llvm::Triple(*Stub.Target.Triple), Stub.Symbols, + "TBD", Out); } } return 0; diff --git a/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp b/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp index 28915e5..d3f9738 100644 --- a/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp +++ b/llvm/tools/llvm-mca/Views/InstructionInfoView.cpp @@ -70,8 +70,8 @@ void InstructionInfoView::printView(raw_ostream &OS) const { else if (IIVDEntry.Latency < 100) TempStream << ' '; - if (IIVDEntry.RThroughput.hasValue()) { - double RT = IIVDEntry.RThroughput.getValue(); + if (IIVDEntry.RThroughput) { + double RT = IIVDEntry.RThroughput.value(); TempStream << format("%.2f", RT) << ' '; if (RT < 10.0) TempStream << " "; diff --git a/llvm/tools/llvm-objdump/XCOFFDump.cpp b/llvm/tools/llvm-objdump/XCOFFDump.cpp index 159741b..befc9c0 100644 --- a/llvm/tools/llvm-objdump/XCOFFDump.cpp +++ b/llvm/tools/llvm-objdump/XCOFFDump.cpp @@ -97,8 +97,8 @@ std::string objdump::getXCOFFSymbolDescription(const SymbolInfoTy &SymbolInfo, std::string Result; // Dummy symbols have no symbol index. if (SymbolInfo.XCOFFSymInfo.Index) - Result = ("(idx: " + Twine(SymbolInfo.XCOFFSymInfo.Index.getValue()) + - ") " + SymbolName) + Result = ("(idx: " + Twine(SymbolInfo.XCOFFSymInfo.Index.value()) + ") " + + SymbolName) .str(); else Result.append(SymbolName.begin(), SymbolName.end()); diff --git a/llvm/tools/llvm-objdump/llvm-objdump.cpp b/llvm/tools/llvm-objdump/llvm-objdump.cpp index 42c3820..e95e745 100644 --- a/llvm/tools/llvm-objdump/llvm-objdump.cpp +++ b/llvm/tools/llvm-objdump/llvm-objdump.cpp @@ -1408,8 +1408,8 @@ static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj, // Right now, most targets return None i.e ignore to treat a symbol // separately. But WebAssembly decodes preludes for some symbols. // - if (Status.hasValue()) { - if (Status.getValue() == MCDisassembler::Fail) { + if (Status) { + if (*Status == MCDisassembler::Fail) { outs() << "// Error in decoding " << SymbolName << " : Decoding failed region as bytes.\n"; for (uint64_t I = 0; I < Size; ++I) { @@ -2139,8 +2139,8 @@ void objdump::printSymbol(const ObjectFile *O, const SymbolRef &Symbol, SymName = demangle(SymName); if (SymbolDescription) - SymName = getXCOFFSymbolDescription( - createSymbolInfo(O, SymRef.getValue()), SymName); + SymName = getXCOFFSymbolDescription(createSymbolInfo(O, *SymRef), + SymName); outs() << ' ' << SymName; outs() << ") "; @@ -2247,8 +2247,8 @@ static void printRawClangAST(const ObjectFile *Obj) { if (!ClangASTSection) return; - StringRef ClangASTContents = unwrapOrError( - ClangASTSection.getValue().getContents(), Obj->getFileName()); + StringRef ClangASTContents = + unwrapOrError(ClangASTSection->getContents(), Obj->getFileName()); outs().write(ClangASTContents.data(), ClangASTContents.size()); } diff --git a/llvm/tools/llvm-profdata/llvm-profdata.cpp b/llvm/tools/llvm-profdata/llvm-profdata.cpp index 11387ac..9c65864 100644 --- a/llvm/tools/llvm-profdata/llvm-profdata.cpp +++ b/llvm/tools/llvm-profdata/llvm-profdata.cpp @@ -777,12 +777,12 @@ mergeSampleProfile(const WeightedFileVector &Inputs, SymbolRemapper *Remapper, } SampleProfileMap &Profiles = Reader->getProfiles(); - if (ProfileIsProbeBased.hasValue() && + if (ProfileIsProbeBased && ProfileIsProbeBased != FunctionSamples::ProfileIsProbeBased) exitWithError( "cannot merge probe-based profile with non-probe-based profile"); ProfileIsProbeBased = FunctionSamples::ProfileIsProbeBased; - if (ProfileIsCS.hasValue() && ProfileIsCS != FunctionSamples::ProfileIsCS) + if (ProfileIsCS && ProfileIsCS != FunctionSamples::ProfileIsCS) exitWithError("cannot merge CS profile with non-CS profile"); ProfileIsCS = FunctionSamples::ProfileIsCS; for (SampleProfileMap::iterator I = Profiles.begin(), E = Profiles.end(); diff --git a/llvm/tools/llvm-profgen/ProfiledBinary.cpp b/llvm/tools/llvm-profgen/ProfiledBinary.cpp index adf7770..aaf7a00 100644 --- a/llvm/tools/llvm-profgen/ProfiledBinary.cpp +++ b/llvm/tools/llvm-profgen/ProfiledBinary.cpp @@ -100,26 +100,25 @@ BinarySizeContextTracker::getFuncSizeForContext(const SampleContext &Context) { PrevNode = CurrNode; CurrNode = CurrNode->getChildContext(ChildFrame.Location, ChildFrame.FuncName); - if (CurrNode && CurrNode->getFunctionSize().hasValue()) - Size = CurrNode->getFunctionSize().getValue(); + if (CurrNode && CurrNode->getFunctionSize()) + Size = CurrNode->getFunctionSize().value(); } // If we traversed all nodes along the path of the context and haven't // found a size yet, pivot to look for size from sibling nodes, i.e size // of inlinee under different context. - if (!Size.hasValue()) { + if (!Size) { if (!CurrNode) CurrNode = PrevNode; - while (!Size.hasValue() && CurrNode && - !CurrNode->getAllChildContext().empty()) { + while (!Size && CurrNode && !CurrNode->getAllChildContext().empty()) { CurrNode = &CurrNode->getAllChildContext().begin()->second; - if (CurrNode->getFunctionSize().hasValue()) - Size = CurrNode->getFunctionSize().getValue(); + if (CurrNode->getFunctionSize()) + Size = CurrNode->getFunctionSize().value(); } } - assert(Size.hasValue() && "We should at least find one context size."); - return Size.getValue(); + assert(Size && "We should at least find one context size."); + return Size.value(); } void BinarySizeContextTracker::trackInlineesOptimizedAway( diff --git a/llvm/tools/llvm-sim/llvm-sim.cpp b/llvm/tools/llvm-sim/llvm-sim.cpp index 26e370f..2b717d7 100644 --- a/llvm/tools/llvm-sim/llvm-sim.cpp +++ b/llvm/tools/llvm-sim/llvm-sim.cpp @@ -85,14 +85,13 @@ exportToFile(const StringRef FilePath, Optional<unsigned> End = getPositionInModule((*C.back()).Inst, LLVMInstNum); - assert(Start.hasValue() && + assert(Start && "Could not find instruction number for first instruction"); - assert(End.hasValue() && - "Could not find instruction number for last instruction"); + assert(End && "Could not find instruction number for last instruction"); J.object([&] { - J.attribute("start", Start.getValue()); - J.attribute("end", End.getValue()); + J.attribute("start", Start.value()); + J.attribute("end", End.value()); }); } J.arrayEnd(); diff --git a/llvm/tools/obj2yaml/dwarf2yaml.cpp b/llvm/tools/obj2yaml/dwarf2yaml.cpp index c0c23ea..4436cef 100644 --- a/llvm/tools/obj2yaml/dwarf2yaml.cpp +++ b/llvm/tools/obj2yaml/dwarf2yaml.cpp @@ -247,15 +247,15 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) { auto FormValue = DIEWrapper.find(AttrSpec.Attr); if (!FormValue) return; - auto Form = FormValue.getValue().getForm(); + auto Form = FormValue->getForm(); bool indirect = false; do { indirect = false; switch (Form) { case dwarf::DW_FORM_addr: case dwarf::DW_FORM_GNU_addr_index: - if (auto Val = FormValue.getValue().getAsAddress()) - NewValue.Value = Val.getValue(); + if (auto Val = FormValue->getAsAddress()) + NewValue.Value = Val.value(); break; case dwarf::DW_FORM_ref_addr: case dwarf::DW_FORM_ref1: @@ -264,16 +264,16 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) { case dwarf::DW_FORM_ref8: case dwarf::DW_FORM_ref_udata: case dwarf::DW_FORM_ref_sig8: - if (auto Val = FormValue.getValue().getAsReferenceUVal()) - NewValue.Value = Val.getValue(); + if (auto Val = FormValue->getAsReferenceUVal()) + NewValue.Value = Val.value(); break; case dwarf::DW_FORM_exprloc: case dwarf::DW_FORM_block: case dwarf::DW_FORM_block1: case dwarf::DW_FORM_block2: case dwarf::DW_FORM_block4: - if (auto Val = FormValue.getValue().getAsBlock()) { - auto BlockData = Val.getValue(); + if (auto Val = FormValue->getAsBlock()) { + auto BlockData = Val.value(); std::copy(BlockData.begin(), BlockData.end(), std::back_inserter(NewValue.BlockData)); } @@ -288,8 +288,8 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) { case dwarf::DW_FORM_udata: case dwarf::DW_FORM_ref_sup4: case dwarf::DW_FORM_ref_sup8: - if (auto Val = FormValue.getValue().getAsUnsignedConstant()) - NewValue.Value = Val.getValue(); + if (auto Val = FormValue->getAsUnsignedConstant()) + NewValue.Value = Val.value(); break; case dwarf::DW_FORM_string: if (auto Val = dwarf::toString(FormValue)) @@ -297,10 +297,10 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) { break; case dwarf::DW_FORM_indirect: indirect = true; - if (auto Val = FormValue.getValue().getAsUnsignedConstant()) { - NewValue.Value = Val.getValue(); + if (auto Val = FormValue->getAsUnsignedConstant()) { + NewValue.Value = Val.value(); NewEntry.Values.push_back(NewValue); - Form = static_cast<dwarf::Form>(Val.getValue()); + Form = static_cast<dwarf::Form>(Val.value()); } break; case dwarf::DW_FORM_strp: @@ -311,8 +311,8 @@ void dumpDebugInfo(DWARFContext &DCtx, DWARFYAML::Data &Y) { case dwarf::DW_FORM_strp_sup: case dwarf::DW_FORM_GNU_str_index: case dwarf::DW_FORM_strx: - if (auto Val = FormValue.getValue().getAsCStringOffset()) - NewValue.Value = Val.getValue(); + if (auto Val = FormValue->getAsCStringOffset()) + NewValue.Value = Val.value(); break; case dwarf::DW_FORM_flag_present: NewValue.Value = 1; diff --git a/llvm/tools/obj2yaml/dxcontainer2yaml.cpp b/llvm/tools/obj2yaml/dxcontainer2yaml.cpp index a57b8cf..122ae7d 100644 --- a/llvm/tools/obj2yaml/dxcontainer2yaml.cpp +++ b/llvm/tools/obj2yaml/dxcontainer2yaml.cpp @@ -40,8 +40,8 @@ dumpDXContainer(MemoryBufferRef Source) { Obj->Header.PartOffsets->push_back(P.Offset); if (P.Part.getName() == "DXIL") { Optional<DXContainer::DXILData> DXIL = Container.getDXIL(); - assert(DXIL.hasValue() && "Since we are iterating and found a DXIL part, " - "this should never not have a value"); + assert(DXIL && "Since we are iterating and found a DXIL part, " + "this should never not have a value"); Obj->Parts.push_back(DXContainerYAML::Part{ P.Part.getName().str(), P.Part.Size, DXContainerYAML::DXILProgram{ diff --git a/llvm/unittests/ADT/OptionalTest.cpp b/llvm/unittests/ADT/OptionalTest.cpp index f88437f..94032c6 100644 --- a/llvm/unittests/ADT/OptionalTest.cpp +++ b/llvm/unittests/ADT/OptionalTest.cpp @@ -29,13 +29,13 @@ void OptionalWorksInConstexpr() { constexpr Optional<int> x2{}; static_assert(!x1.has_value() && !x2.has_value(), "Default construction and hasValue() are contexpr"); - static_assert(!x1.hasValue() && !x2.hasValue(), + static_assert(!x1.has_value() && !x2.has_value(), "Default construction and hasValue() are contexpr"); constexpr auto y1 = Optional<int>(3); constexpr Optional<int> y2{3}; static_assert(y1.value() == y2.value() && y1.value() == 3, "Construction with value and getValue() are constexpr"); - static_assert(y1.getValue() == y2.getValue() && y1.getValue() == 3, + static_assert(y1.value() == *y2 && *y1 == 3, "Construction with value and getValue() are constexpr"); static_assert(Optional<int>{3} >= 2 && Optional<int>{1} < Optional<int>{2}, "Comparisons work in constexpr"); @@ -252,14 +252,14 @@ TEST(OptionalTest, Emplace) { A.emplace(1, 2); EXPECT_TRUE(A.has_value()); - EXPECT_TRUE(A.hasValue()); + EXPECT_TRUE(A.has_value()); EXPECT_EQ(1, A->x); EXPECT_EQ(2, A->y); EXPECT_EQ(0u, MultiArgConstructor::Destructions); A.emplace(5, false); EXPECT_TRUE(A.has_value()); - EXPECT_TRUE(A.hasValue()); + EXPECT_TRUE(A.has_value()); EXPECT_EQ(5, A->x); EXPECT_EQ(-5, A->y); EXPECT_EQ(1u, MultiArgConstructor::Destructions); @@ -270,12 +270,12 @@ TEST(OptionalTest, InPlaceConstructionMultiArgConstructorTest) { { Optional<MultiArgConstructor> A{in_place, 1, 2}; EXPECT_TRUE(A.has_value()); - EXPECT_TRUE(A.hasValue()); + EXPECT_TRUE(A.has_value()); EXPECT_EQ(1, A->x); EXPECT_EQ(2, A->y); Optional<MultiArgConstructor> B{in_place, 5, false}; EXPECT_TRUE(B.has_value()); - EXPECT_TRUE(B.hasValue()); + EXPECT_TRUE(B.has_value()); EXPECT_EQ(5, B->x); EXPECT_EQ(-5, B->y); EXPECT_EQ(0u, MultiArgConstructor::Destructions); diff --git a/llvm/unittests/ADT/StatisticTest.cpp b/llvm/unittests/ADT/StatisticTest.cpp index 17d9911..523f510 100644 --- a/llvm/unittests/ADT/StatisticTest.cpp +++ b/llvm/unittests/ADT/StatisticTest.cpp @@ -92,8 +92,8 @@ TEST(StatisticTest, API) { OptionalStatistic S2; extractCounters(Range1, S1, S2); - EXPECT_EQ(S1.hasValue(), true); - EXPECT_EQ(S2.hasValue(), false); + EXPECT_EQ(S1.has_value(), true); + EXPECT_EQ(S2.has_value(), false); } // Counter2 will be registered when it's first touched. @@ -108,8 +108,8 @@ TEST(StatisticTest, API) { OptionalStatistic S2; extractCounters(Range, S1, S2); - EXPECT_EQ(S1.hasValue(), true); - EXPECT_EQ(S2.hasValue(), true); + EXPECT_EQ(S1.has_value(), true); + EXPECT_EQ(S2.has_value(), true); EXPECT_EQ(S1->first, "Counter"); EXPECT_EQ(S1->second, 2u); @@ -135,8 +135,8 @@ TEST(StatisticTest, API) { OptionalStatistic S1; OptionalStatistic S2; extractCounters(Range, S1, S2); - EXPECT_EQ(S1.hasValue(), false); - EXPECT_EQ(S2.hasValue(), false); + EXPECT_EQ(S1.has_value(), false); + EXPECT_EQ(S2.has_value(), false); } // Now check that they successfully re-register and count. @@ -153,8 +153,8 @@ TEST(StatisticTest, API) { OptionalStatistic S2; extractCounters(Range, S1, S2); - EXPECT_EQ(S1.hasValue(), true); - EXPECT_EQ(S2.hasValue(), true); + EXPECT_EQ(S1.has_value(), true); + EXPECT_EQ(S2.has_value(), true); EXPECT_EQ(S1->first, "Counter"); EXPECT_EQ(S1->second, 1u); diff --git a/llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp b/llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp index 5dd3995..91009ab 100644 --- a/llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp +++ b/llvm/unittests/Analysis/BlockFrequencyInfoTest.cpp @@ -75,11 +75,11 @@ TEST_F(BlockFrequencyInfoTest, Basic) { EXPECT_EQ(BB0Freq, BB1Freq + BB2Freq); EXPECT_EQ(BB0Freq, BB3Freq); - EXPECT_EQ(BFI.getBlockProfileCount(&BB0).getValue(), UINT64_C(100)); - EXPECT_EQ(BFI.getBlockProfileCount(BB3).getValue(), UINT64_C(100)); - EXPECT_EQ(BFI.getBlockProfileCount(BB1).getValue(), + EXPECT_EQ(BFI.getBlockProfileCount(&BB0).value(), UINT64_C(100)); + EXPECT_EQ(BFI.getBlockProfileCount(BB3).value(), UINT64_C(100)); + EXPECT_EQ(BFI.getBlockProfileCount(BB1).value(), (100 * BB1Freq + BB0Freq / 2) / BB0Freq); - EXPECT_EQ(BFI.getBlockProfileCount(BB2).getValue(), + EXPECT_EQ(BFI.getBlockProfileCount(BB2).value(), (100 * BB2Freq + BB0Freq / 2) / BB0Freq); // Scale the frequencies of BB0, BB1 and BB2 by a factor of two. diff --git a/llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp b/llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp index cfe2c25..f6a0537 100644 --- a/llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp +++ b/llvm/unittests/Analysis/IRSimilarityIdentifierTest.cpp @@ -2188,9 +2188,9 @@ TEST(IRSimilarityCandidate, CanonicalNumbering) { for (std::pair<unsigned, DenseSet<unsigned>> &P : Mapping2) { unsigned Source = P.first; - ASSERT_TRUE(Cand2.getCanonicalNum(Source).hasValue()); + ASSERT_TRUE(Cand2.getCanonicalNum(Source).has_value()); unsigned Canon = *Cand2.getCanonicalNum(Source); - ASSERT_TRUE(Cand1.fromCanonicalNum(Canon).hasValue()); + ASSERT_TRUE(Cand1.fromCanonicalNum(Canon).has_value()); unsigned Dest = *Cand1.fromCanonicalNum(Canon); DenseSet<unsigned>::iterator It = P.second.find(Dest); diff --git a/llvm/unittests/Analysis/MemorySSATest.cpp b/llvm/unittests/Analysis/MemorySSATest.cpp index 298a8bc..4c8942f 100644 --- a/llvm/unittests/Analysis/MemorySSATest.cpp +++ b/llvm/unittests/Analysis/MemorySSATest.cpp @@ -1191,14 +1191,13 @@ TEST_F(MemorySSATest, TestStoreMayAlias) { EXPECT_EQ(MemDef->isOptimized(), true) << "Store " << I << " was not optimized"; if (I == 1 || I == 3 || I == 4) - EXPECT_EQ(MemDef->getOptimizedAccessType().getValue(), - AliasResult::MayAlias) + EXPECT_EQ(MemDef->getOptimizedAccessType().value(), AliasResult::MayAlias) << "Store " << I << " doesn't have the correct alias information"; else if (I == 0 || I == 2) EXPECT_EQ(MemDef->getOptimizedAccessType(), None) << "Store " << I << " doesn't have the correct alias information"; else - EXPECT_EQ(MemDef->getOptimizedAccessType().getValue(), + EXPECT_EQ(MemDef->getOptimizedAccessType().value(), AliasResult::MustAlias) << "Store " << I << " doesn't have the correct alias information"; // EXPECT_EQ expands such that if we increment I above, it won't get diff --git a/llvm/unittests/Analysis/VectorFunctionABITest.cpp b/llvm/unittests/Analysis/VectorFunctionABITest.cpp index 7ac1b03..026732c 100644 --- a/llvm/unittests/Analysis/VectorFunctionABITest.cpp +++ b/llvm/unittests/Analysis/VectorFunctionABITest.cpp @@ -75,8 +75,8 @@ protected: reset(Name, IRType); const auto OptInfo = VFABI::tryDemangleForVFABI(MangledName, *(M.get())); - if (OptInfo.hasValue()) { - Info = OptInfo.getValue(); + if (OptInfo) { + Info = OptInfo.value(); return true; } diff --git a/llvm/unittests/BinaryFormat/DwarfTest.cpp b/llvm/unittests/BinaryFormat/DwarfTest.cpp index 5e49a5c..ddafbb4 100644 --- a/llvm/unittests/BinaryFormat/DwarfTest.cpp +++ b/llvm/unittests/BinaryFormat/DwarfTest.cpp @@ -147,48 +147,48 @@ TEST(DwarfTest, FixedFormSizes) { FormParams Params_2_4_32 = {2, 4, DWARF32}; RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_2_4_32); AddrSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_2_4_32); - EXPECT_TRUE(RefSize.hasValue()); - EXPECT_TRUE(AddrSize.hasValue()); + EXPECT_TRUE(RefSize.has_value()); + EXPECT_TRUE(AddrSize.has_value()); EXPECT_EQ(*RefSize, *AddrSize); // Test 32 bit DWARF version 2 with 8 byte addresses. FormParams Params_2_8_32 = {2, 8, DWARF32}; RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_2_8_32); AddrSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_2_8_32); - EXPECT_TRUE(RefSize.hasValue()); - EXPECT_TRUE(AddrSize.hasValue()); + EXPECT_TRUE(RefSize.has_value()); + EXPECT_TRUE(AddrSize.has_value()); EXPECT_EQ(*RefSize, *AddrSize); // DW_FORM_ref_addr is 4 bytes in DWARF 32 in DWARF version 3 and beyond. FormParams Params_3_4_32 = {3, 4, DWARF32}; RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_3_4_32); - EXPECT_TRUE(RefSize.hasValue()); + EXPECT_TRUE(RefSize.has_value()); EXPECT_EQ(*RefSize, 4); FormParams Params_4_4_32 = {4, 4, DWARF32}; RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_4_4_32); - EXPECT_TRUE(RefSize.hasValue()); + EXPECT_TRUE(RefSize.has_value()); EXPECT_EQ(*RefSize, 4); FormParams Params_5_4_32 = {5, 4, DWARF32}; RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_5_4_32); - EXPECT_TRUE(RefSize.hasValue()); + EXPECT_TRUE(RefSize.has_value()); EXPECT_EQ(*RefSize, 4); // DW_FORM_ref_addr is 8 bytes in DWARF 64 in DWARF version 3 and beyond. FormParams Params_3_8_64 = {3, 8, DWARF64}; RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_3_8_64); - EXPECT_TRUE(RefSize.hasValue()); + EXPECT_TRUE(RefSize.has_value()); EXPECT_EQ(*RefSize, 8); FormParams Params_4_8_64 = {4, 8, DWARF64}; RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_4_8_64); - EXPECT_TRUE(RefSize.hasValue()); + EXPECT_TRUE(RefSize.has_value()); EXPECT_EQ(*RefSize, 8); FormParams Params_5_8_64 = {5, 8, DWARF64}; RefSize = getFixedFormByteSize(DW_FORM_ref_addr, Params_5_8_64); - EXPECT_TRUE(RefSize.hasValue()); + EXPECT_TRUE(RefSize.has_value()); EXPECT_EQ(*RefSize, 8); } diff --git a/llvm/unittests/CodeGen/GlobalISel/ConstantFoldingTest.cpp b/llvm/unittests/CodeGen/GlobalISel/ConstantFoldingTest.cpp index 5053d54..33c1f0f 100644 --- a/llvm/unittests/CodeGen/GlobalISel/ConstantFoldingTest.cpp +++ b/llvm/unittests/CodeGen/GlobalISel/ConstantFoldingTest.cpp @@ -83,157 +83,157 @@ TEST_F(AArch64GISelMITest, FoldBinOp) { Optional<APInt> FoldGAddInt = ConstantFoldBinOp(TargetOpcode::G_ADD, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGAddInt.hasValue()); - EXPECT_EQ(25ULL, FoldGAddInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGAddInt.has_value()); + EXPECT_EQ(25ULL, FoldGAddInt->getLimitedValue()); Optional<APInt> FoldGAddMix = ConstantFoldBinOp(TargetOpcode::G_ADD, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGAddMix.hasValue()); - EXPECT_EQ(1073741840ULL, FoldGAddMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGAddMix.has_value()); + EXPECT_EQ(1073741840ULL, FoldGAddMix->getLimitedValue()); // Test G_AND folding Integer + Mixed Int-Float cases Optional<APInt> FoldGAndInt = ConstantFoldBinOp(TargetOpcode::G_AND, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGAndInt.hasValue()); - EXPECT_EQ(0ULL, FoldGAndInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGAndInt.has_value()); + EXPECT_EQ(0ULL, FoldGAndInt->getLimitedValue()); Optional<APInt> FoldGAndMix = ConstantFoldBinOp(TargetOpcode::G_AND, MIBCst2.getReg(0), MIBFCst1.getReg(0), *MRI); - EXPECT_TRUE(FoldGAndMix.hasValue()); - EXPECT_EQ(1ULL, FoldGAndMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGAndMix.has_value()); + EXPECT_EQ(1ULL, FoldGAndMix->getLimitedValue()); // Test G_ASHR folding Integer + Mixed cases Optional<APInt> FoldGAShrInt = ConstantFoldBinOp(TargetOpcode::G_ASHR, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGAShrInt.hasValue()); - EXPECT_EQ(0ULL, FoldGAShrInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGAShrInt.has_value()); + EXPECT_EQ(0ULL, FoldGAShrInt->getLimitedValue()); Optional<APInt> FoldGAShrMix = ConstantFoldBinOp(TargetOpcode::G_ASHR, MIBFCst2.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGAShrMix.hasValue()); - EXPECT_EQ(2097152ULL, FoldGAShrMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGAShrMix.has_value()); + EXPECT_EQ(2097152ULL, FoldGAShrMix->getLimitedValue()); // Test G_LSHR folding Integer + Mixed Int-Float cases Optional<APInt> FoldGLShrInt = ConstantFoldBinOp(TargetOpcode::G_LSHR, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGLShrInt.hasValue()); - EXPECT_EQ(0ULL, FoldGLShrInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGLShrInt.has_value()); + EXPECT_EQ(0ULL, FoldGLShrInt->getLimitedValue()); Optional<APInt> FoldGLShrMix = ConstantFoldBinOp(TargetOpcode::G_LSHR, MIBFCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGLShrMix.hasValue()); - EXPECT_EQ(2080768ULL, FoldGLShrMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGLShrMix.has_value()); + EXPECT_EQ(2080768ULL, FoldGLShrMix->getLimitedValue()); // Test G_MUL folding Integer + Mixed Int-Float cases Optional<APInt> FoldGMulInt = ConstantFoldBinOp(TargetOpcode::G_MUL, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGMulInt.hasValue()); - EXPECT_EQ(144ULL, FoldGMulInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGMulInt.has_value()); + EXPECT_EQ(144ULL, FoldGMulInt->getLimitedValue()); Optional<APInt> FoldGMulMix = ConstantFoldBinOp(TargetOpcode::G_MUL, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGMulMix.hasValue()); - EXPECT_EQ(0ULL, FoldGMulMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGMulMix.has_value()); + EXPECT_EQ(0ULL, FoldGMulMix->getLimitedValue()); // Test G_OR folding Integer + Mixed Int-Float cases Optional<APInt> FoldGOrInt = ConstantFoldBinOp(TargetOpcode::G_OR, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGOrInt.hasValue()); - EXPECT_EQ(25ULL, FoldGOrInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGOrInt.has_value()); + EXPECT_EQ(25ULL, FoldGOrInt->getLimitedValue()); Optional<APInt> FoldGOrMix = ConstantFoldBinOp(TargetOpcode::G_OR, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGOrMix.hasValue()); - EXPECT_EQ(1073741840ULL, FoldGOrMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGOrMix.has_value()); + EXPECT_EQ(1073741840ULL, FoldGOrMix->getLimitedValue()); // Test G_SHL folding Integer + Mixed Int-Float cases Optional<APInt> FoldGShlInt = ConstantFoldBinOp(TargetOpcode::G_SHL, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGShlInt.hasValue()); - EXPECT_EQ(8192ULL, FoldGShlInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGShlInt.has_value()); + EXPECT_EQ(8192ULL, FoldGShlInt->getLimitedValue()); Optional<APInt> FoldGShlMix = ConstantFoldBinOp(TargetOpcode::G_SHL, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGShlMix.hasValue()); - EXPECT_EQ(0ULL, FoldGShlMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGShlMix.has_value()); + EXPECT_EQ(0ULL, FoldGShlMix->getLimitedValue()); // Test G_SUB folding Integer + Mixed Int-Float cases Optional<APInt> FoldGSubInt = ConstantFoldBinOp(TargetOpcode::G_SUB, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGSubInt.hasValue()); - EXPECT_EQ(7ULL, FoldGSubInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGSubInt.has_value()); + EXPECT_EQ(7ULL, FoldGSubInt->getLimitedValue()); Optional<APInt> FoldGSubMix = ConstantFoldBinOp(TargetOpcode::G_SUB, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGSubMix.hasValue()); - EXPECT_EQ(3221225488ULL, FoldGSubMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGSubMix.has_value()); + EXPECT_EQ(3221225488ULL, FoldGSubMix->getLimitedValue()); // Test G_XOR folding Integer + Mixed Int-Float cases Optional<APInt> FoldGXorInt = ConstantFoldBinOp(TargetOpcode::G_XOR, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGXorInt.hasValue()); - EXPECT_EQ(25ULL, FoldGXorInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGXorInt.has_value()); + EXPECT_EQ(25ULL, FoldGXorInt->getLimitedValue()); Optional<APInt> FoldGXorMix = ConstantFoldBinOp(TargetOpcode::G_XOR, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGXorMix.hasValue()); - EXPECT_EQ(1073741840ULL, FoldGXorMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGXorMix.has_value()); + EXPECT_EQ(1073741840ULL, FoldGXorMix->getLimitedValue()); // Test G_UDIV folding Integer + Mixed Int-Float cases Optional<APInt> FoldGUdivInt = ConstantFoldBinOp(TargetOpcode::G_UDIV, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGUdivInt.hasValue()); - EXPECT_EQ(1ULL, FoldGUdivInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGUdivInt.has_value()); + EXPECT_EQ(1ULL, FoldGUdivInt->getLimitedValue()); Optional<APInt> FoldGUdivMix = ConstantFoldBinOp(TargetOpcode::G_UDIV, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGUdivMix.hasValue()); - EXPECT_EQ(0ULL, FoldGUdivMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGUdivMix.has_value()); + EXPECT_EQ(0ULL, FoldGUdivMix->getLimitedValue()); // Test G_SDIV folding Integer + Mixed Int-Float cases Optional<APInt> FoldGSdivInt = ConstantFoldBinOp(TargetOpcode::G_SDIV, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGSdivInt.hasValue()); - EXPECT_EQ(1ULL, FoldGSdivInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGSdivInt.has_value()); + EXPECT_EQ(1ULL, FoldGSdivInt->getLimitedValue()); Optional<APInt> FoldGSdivMix = ConstantFoldBinOp(TargetOpcode::G_SDIV, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGSdivMix.hasValue()); - EXPECT_EQ(0ULL, FoldGSdivMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGSdivMix.has_value()); + EXPECT_EQ(0ULL, FoldGSdivMix->getLimitedValue()); // Test G_UREM folding Integer + Mixed Int-Float cases Optional<APInt> FoldGUremInt = ConstantFoldBinOp(TargetOpcode::G_UDIV, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGUremInt.hasValue()); - EXPECT_EQ(1ULL, FoldGUremInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGUremInt.has_value()); + EXPECT_EQ(1ULL, FoldGUremInt->getLimitedValue()); Optional<APInt> FoldGUremMix = ConstantFoldBinOp(TargetOpcode::G_UDIV, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGUremMix.hasValue()); - EXPECT_EQ(0ULL, FoldGUremMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGUremMix.has_value()); + EXPECT_EQ(0ULL, FoldGUremMix->getLimitedValue()); // Test G_SREM folding Integer + Mixed Int-Float cases Optional<APInt> FoldGSremInt = ConstantFoldBinOp(TargetOpcode::G_SREM, MIBCst1.getReg(0), MIBCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGSremInt.hasValue()); - EXPECT_EQ(7ULL, FoldGSremInt.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGSremInt.has_value()); + EXPECT_EQ(7ULL, FoldGSremInt->getLimitedValue()); Optional<APInt> FoldGSremMix = ConstantFoldBinOp(TargetOpcode::G_SREM, MIBCst1.getReg(0), MIBFCst2.getReg(0), *MRI); - EXPECT_TRUE(FoldGSremMix.hasValue()); - EXPECT_EQ(16ULL, FoldGSremMix.getValue().getLimitedValue()); + EXPECT_TRUE(FoldGSremMix.has_value()); + EXPECT_EQ(16ULL, FoldGSremMix->getLimitedValue()); } } // namespace diff --git a/llvm/unittests/DebugInfo/DWARF/DWARFDebugFrameTest.cpp b/llvm/unittests/DebugInfo/DWARF/DWARFDebugFrameTest.cpp index 6a8f23c..dbc54e7 100644 --- a/llvm/unittests/DebugInfo/DWARF/DWARFDebugFrameTest.cpp +++ b/llvm/unittests/DebugInfo/DWARF/DWARFDebugFrameTest.cpp @@ -424,31 +424,31 @@ TEST(DWARFDebugFrame, RegisterLocations) { // Verify RegisterLocations::getRegisterLocation() works as expected. Optional<dwarf::UnwindLocation> OptionalLoc; OptionalLoc = Locs.getRegisterLocation(0); - EXPECT_FALSE(OptionalLoc.hasValue()); + EXPECT_FALSE(OptionalLoc.has_value()); OptionalLoc = Locs.getRegisterLocation(12); - EXPECT_TRUE(OptionalLoc.hasValue()); + EXPECT_TRUE(OptionalLoc.has_value()); EXPECT_EQ(*OptionalLoc, Reg12Loc); OptionalLoc = Locs.getRegisterLocation(13); - EXPECT_TRUE(OptionalLoc.hasValue()); + EXPECT_TRUE(OptionalLoc.has_value()); EXPECT_EQ(*OptionalLoc, Reg13Loc); OptionalLoc = Locs.getRegisterLocation(14); - EXPECT_TRUE(OptionalLoc.hasValue()); + EXPECT_TRUE(OptionalLoc.has_value()); EXPECT_EQ(*OptionalLoc, Reg14Loc); // Verify registers are correctly removed when multiple exist in the list. Locs.removeRegisterLocation(13); - EXPECT_FALSE(Locs.getRegisterLocation(13).hasValue()); + EXPECT_FALSE(Locs.getRegisterLocation(13).has_value()); EXPECT_TRUE(Locs.hasLocations()); expectDumpResult(Locs, "reg12=[CFA+4], reg14=same"); Locs.removeRegisterLocation(14); - EXPECT_FALSE(Locs.getRegisterLocation(14).hasValue()); + EXPECT_FALSE(Locs.getRegisterLocation(14).has_value()); EXPECT_TRUE(Locs.hasLocations()); expectDumpResult(Locs, "reg12=[CFA+4]"); Locs.removeRegisterLocation(12); - EXPECT_FALSE(Locs.getRegisterLocation(12).hasValue()); + EXPECT_FALSE(Locs.getRegisterLocation(12).has_value()); EXPECT_FALSE(Locs.hasLocations()); expectDumpResult(Locs, ""); } diff --git a/llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp b/llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp index 367e89e4..e4c65c0 100644 --- a/llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp +++ b/llvm/unittests/DebugInfo/DWARF/DWARFDebugInfoTest.cpp @@ -252,32 +252,32 @@ void TestAllForms() { FormValue = DieDG.find(Attr_DW_FORM_block); EXPECT_TRUE((bool)FormValue); BlockDataOpt = FormValue->getAsBlock(); - EXPECT_TRUE(BlockDataOpt.hasValue()); - ExtractedBlockData = BlockDataOpt.getValue(); + EXPECT_TRUE(BlockDataOpt.has_value()); + ExtractedBlockData = *BlockDataOpt; EXPECT_EQ(ExtractedBlockData.size(), BlockSize); EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0); FormValue = DieDG.find(Attr_DW_FORM_block1); EXPECT_TRUE((bool)FormValue); BlockDataOpt = FormValue->getAsBlock(); - EXPECT_TRUE(BlockDataOpt.hasValue()); - ExtractedBlockData = BlockDataOpt.getValue(); + EXPECT_TRUE(BlockDataOpt.has_value()); + ExtractedBlockData = *BlockDataOpt; EXPECT_EQ(ExtractedBlockData.size(), BlockSize); EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0); FormValue = DieDG.find(Attr_DW_FORM_block2); EXPECT_TRUE((bool)FormValue); BlockDataOpt = FormValue->getAsBlock(); - EXPECT_TRUE(BlockDataOpt.hasValue()); - ExtractedBlockData = BlockDataOpt.getValue(); + EXPECT_TRUE(BlockDataOpt.has_value()); + ExtractedBlockData = *BlockDataOpt; EXPECT_EQ(ExtractedBlockData.size(), BlockSize); EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0); FormValue = DieDG.find(Attr_DW_FORM_block4); EXPECT_TRUE((bool)FormValue); BlockDataOpt = FormValue->getAsBlock(); - EXPECT_TRUE(BlockDataOpt.hasValue()); - ExtractedBlockData = BlockDataOpt.getValue(); + EXPECT_TRUE(BlockDataOpt.has_value()); + ExtractedBlockData = *BlockDataOpt; EXPECT_EQ(ExtractedBlockData.size(), BlockSize); EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0); @@ -286,8 +286,8 @@ void TestAllForms() { FormValue = DieDG.find(Attr_DW_FORM_data16); EXPECT_TRUE((bool)FormValue); BlockDataOpt = FormValue->getAsBlock(); - EXPECT_TRUE(BlockDataOpt.hasValue()); - ExtractedBlockData = BlockDataOpt.getValue(); + EXPECT_TRUE(BlockDataOpt.has_value()); + ExtractedBlockData = *BlockDataOpt; EXPECT_EQ(ExtractedBlockData.size(), 16u); EXPECT_TRUE(memcmp(ExtractedBlockData.data(), Data16, 16) == 0); } @@ -989,21 +989,21 @@ template <uint16_t Version, class AddrType> void TestAddresses() { EXPECT_FALSE((bool)OptU64); } else { EXPECT_TRUE((bool)OptU64); - EXPECT_EQ(OptU64.getValue(), ActualHighPC); + EXPECT_EQ(*OptU64, ActualHighPC); } // Get the high PC as an unsigned constant. This should succeed if the high PC // was encoded as an offset and fail if the high PC was encoded as an address. OptU64 = toUnsigned(SubprogramDieLowHighPC.find(DW_AT_high_pc)); if (SupportsHighPCAsOffset) { EXPECT_TRUE((bool)OptU64); - EXPECT_EQ(OptU64.getValue(), ActualHighPCOffset); + EXPECT_EQ(*OptU64, ActualHighPCOffset); } else { EXPECT_FALSE((bool)OptU64); } OptU64 = SubprogramDieLowHighPC.getHighPC(ActualLowPC); EXPECT_TRUE((bool)OptU64); - EXPECT_EQ(OptU64.getValue(), ActualHighPC); + EXPECT_EQ(*OptU64, ActualHighPC); EXPECT_TRUE(SubprogramDieLowHighPC.getLowAndHighPC(LowPC, HighPC, SectionIndex)); EXPECT_EQ(LowPC, ActualLowPC); @@ -1638,13 +1638,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) { // First test that we don't get valid values back when using an optional with // no value. Optional<DWARFFormValue> FormValOpt1 = DWARFFormValue(); - EXPECT_FALSE(toString(FormValOpt1).hasValue()); - EXPECT_FALSE(toUnsigned(FormValOpt1).hasValue()); - EXPECT_FALSE(toReference(FormValOpt1).hasValue()); - EXPECT_FALSE(toSigned(FormValOpt1).hasValue()); - EXPECT_FALSE(toAddress(FormValOpt1).hasValue()); - EXPECT_FALSE(toSectionOffset(FormValOpt1).hasValue()); - EXPECT_FALSE(toBlock(FormValOpt1).hasValue()); + EXPECT_FALSE(toString(FormValOpt1).has_value()); + EXPECT_FALSE(toUnsigned(FormValOpt1).has_value()); + EXPECT_FALSE(toReference(FormValOpt1).has_value()); + EXPECT_FALSE(toSigned(FormValOpt1).has_value()); + EXPECT_FALSE(toAddress(FormValOpt1).has_value()); + EXPECT_FALSE(toSectionOffset(FormValOpt1).has_value()); + EXPECT_FALSE(toBlock(FormValOpt1).has_value()); EXPECT_EQ(nullptr, toString(FormValOpt1, nullptr)); EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt1, InvalidU64)); EXPECT_EQ(InvalidU64, toReference(FormValOpt1, InvalidU64)); @@ -1657,13 +1657,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) { Optional<DWARFFormValue> FormValOpt2 = DWARFFormValue::createFromUValue(DW_FORM_addr, Address); - EXPECT_FALSE(toString(FormValOpt2).hasValue()); - EXPECT_FALSE(toUnsigned(FormValOpt2).hasValue()); - EXPECT_FALSE(toReference(FormValOpt2).hasValue()); - EXPECT_FALSE(toSigned(FormValOpt2).hasValue()); - EXPECT_TRUE(toAddress(FormValOpt2).hasValue()); - EXPECT_FALSE(toSectionOffset(FormValOpt2).hasValue()); - EXPECT_FALSE(toBlock(FormValOpt2).hasValue()); + EXPECT_FALSE(toString(FormValOpt2).has_value()); + EXPECT_FALSE(toUnsigned(FormValOpt2).has_value()); + EXPECT_FALSE(toReference(FormValOpt2).has_value()); + EXPECT_FALSE(toSigned(FormValOpt2).has_value()); + EXPECT_TRUE(toAddress(FormValOpt2).has_value()); + EXPECT_FALSE(toSectionOffset(FormValOpt2).has_value()); + EXPECT_FALSE(toBlock(FormValOpt2).has_value()); EXPECT_EQ(nullptr, toString(FormValOpt2, nullptr)); EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt2, InvalidU64)); EXPECT_EQ(InvalidU64, toReference(FormValOpt2, InvalidU64)); @@ -1676,13 +1676,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) { Optional<DWARFFormValue> FormValOpt3 = DWARFFormValue::createFromUValue(DW_FORM_udata, UData8); - EXPECT_FALSE(toString(FormValOpt3).hasValue()); - EXPECT_TRUE(toUnsigned(FormValOpt3).hasValue()); - EXPECT_FALSE(toReference(FormValOpt3).hasValue()); - EXPECT_TRUE(toSigned(FormValOpt3).hasValue()); - EXPECT_FALSE(toAddress(FormValOpt3).hasValue()); - EXPECT_FALSE(toSectionOffset(FormValOpt3).hasValue()); - EXPECT_FALSE(toBlock(FormValOpt3).hasValue()); + EXPECT_FALSE(toString(FormValOpt3).has_value()); + EXPECT_TRUE(toUnsigned(FormValOpt3).has_value()); + EXPECT_FALSE(toReference(FormValOpt3).has_value()); + EXPECT_TRUE(toSigned(FormValOpt3).has_value()); + EXPECT_FALSE(toAddress(FormValOpt3).has_value()); + EXPECT_FALSE(toSectionOffset(FormValOpt3).has_value()); + EXPECT_FALSE(toBlock(FormValOpt3).has_value()); EXPECT_EQ(nullptr, toString(FormValOpt3, nullptr)); EXPECT_EQ(UData8, toUnsigned(FormValOpt3, InvalidU64)); EXPECT_EQ(InvalidU64, toReference(FormValOpt3, InvalidU64)); @@ -1695,13 +1695,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) { Optional<DWARFFormValue> FormValOpt4 = DWARFFormValue::createFromUValue(DW_FORM_ref_addr, RefData); - EXPECT_FALSE(toString(FormValOpt4).hasValue()); - EXPECT_FALSE(toUnsigned(FormValOpt4).hasValue()); - EXPECT_TRUE(toReference(FormValOpt4).hasValue()); - EXPECT_FALSE(toSigned(FormValOpt4).hasValue()); - EXPECT_FALSE(toAddress(FormValOpt4).hasValue()); - EXPECT_FALSE(toSectionOffset(FormValOpt4).hasValue()); - EXPECT_FALSE(toBlock(FormValOpt4).hasValue()); + EXPECT_FALSE(toString(FormValOpt4).has_value()); + EXPECT_FALSE(toUnsigned(FormValOpt4).has_value()); + EXPECT_TRUE(toReference(FormValOpt4).has_value()); + EXPECT_FALSE(toSigned(FormValOpt4).has_value()); + EXPECT_FALSE(toAddress(FormValOpt4).has_value()); + EXPECT_FALSE(toSectionOffset(FormValOpt4).has_value()); + EXPECT_FALSE(toBlock(FormValOpt4).has_value()); EXPECT_EQ(nullptr, toString(FormValOpt4, nullptr)); EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt4, InvalidU64)); EXPECT_EQ(RefData, toReference(FormValOpt4, InvalidU64)); @@ -1714,13 +1714,13 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) { Optional<DWARFFormValue> FormValOpt5 = DWARFFormValue::createFromSValue(DW_FORM_udata, SData8); - EXPECT_FALSE(toString(FormValOpt5).hasValue()); - EXPECT_TRUE(toUnsigned(FormValOpt5).hasValue()); - EXPECT_FALSE(toReference(FormValOpt5).hasValue()); - EXPECT_TRUE(toSigned(FormValOpt5).hasValue()); - EXPECT_FALSE(toAddress(FormValOpt5).hasValue()); - EXPECT_FALSE(toSectionOffset(FormValOpt5).hasValue()); - EXPECT_FALSE(toBlock(FormValOpt5).hasValue()); + EXPECT_FALSE(toString(FormValOpt5).has_value()); + EXPECT_TRUE(toUnsigned(FormValOpt5).has_value()); + EXPECT_FALSE(toReference(FormValOpt5).has_value()); + EXPECT_TRUE(toSigned(FormValOpt5).has_value()); + EXPECT_FALSE(toAddress(FormValOpt5).has_value()); + EXPECT_FALSE(toSectionOffset(FormValOpt5).has_value()); + EXPECT_FALSE(toBlock(FormValOpt5).has_value()); EXPECT_EQ(nullptr, toString(FormValOpt5, nullptr)); EXPECT_EQ((uint64_t)SData8, toUnsigned(FormValOpt5, InvalidU64)); EXPECT_EQ(InvalidU64, toReference(FormValOpt5, InvalidU64)); @@ -1734,14 +1734,14 @@ TEST(DWARFDebugInfo, TestDwarfToFunctions) { Optional<DWARFFormValue> FormValOpt6 = DWARFFormValue::createFromBlockValue(DW_FORM_block1, Array); - EXPECT_FALSE(toString(FormValOpt6).hasValue()); - EXPECT_FALSE(toUnsigned(FormValOpt6).hasValue()); - EXPECT_FALSE(toReference(FormValOpt6).hasValue()); - EXPECT_FALSE(toSigned(FormValOpt6).hasValue()); - EXPECT_FALSE(toAddress(FormValOpt6).hasValue()); - EXPECT_FALSE(toSectionOffset(FormValOpt6).hasValue()); + EXPECT_FALSE(toString(FormValOpt6).has_value()); + EXPECT_FALSE(toUnsigned(FormValOpt6).has_value()); + EXPECT_FALSE(toReference(FormValOpt6).has_value()); + EXPECT_FALSE(toSigned(FormValOpt6).has_value()); + EXPECT_FALSE(toAddress(FormValOpt6).has_value()); + EXPECT_FALSE(toSectionOffset(FormValOpt6).has_value()); auto BlockOpt = toBlock(FormValOpt6); - EXPECT_TRUE(BlockOpt.hasValue()); + EXPECT_TRUE(BlockOpt.has_value()); EXPECT_EQ(*BlockOpt, Array); EXPECT_EQ(nullptr, toString(FormValOpt6, nullptr)); EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt6, InvalidU64)); @@ -1799,24 +1799,24 @@ TEST(DWARFDebugInfo, TestFindAttrs) { auto FuncDie = FuncSpecDie.getSibling(); // Make sure that passing in an empty attribute list behave correctly. - EXPECT_FALSE(FuncDie.find(ArrayRef<dwarf::Attribute>()).hasValue()); + EXPECT_FALSE(FuncDie.find(ArrayRef<dwarf::Attribute>()).has_value()); // Make sure that passing in a list of attribute that are not contained // in the DIE returns nothing. - EXPECT_FALSE(FuncDie.find({DW_AT_low_pc, DW_AT_entry_pc}).hasValue()); + EXPECT_FALSE(FuncDie.find({DW_AT_low_pc, DW_AT_entry_pc}).has_value()); const dwarf::Attribute Attrs[] = {DW_AT_linkage_name, DW_AT_MIPS_linkage_name}; // Make sure we can't extract the linkage name attributes when using // DWARFDie::find() since it won't check the DW_AT_specification DIE. - EXPECT_FALSE(FuncDie.find(Attrs).hasValue()); + EXPECT_FALSE(FuncDie.find(Attrs).has_value()); // Make sure we can extract the name from the specification die when using // DWARFDie::findRecursively() since it should recurse through the // DW_AT_specification DIE. auto NameOpt = FuncDie.findRecursively(Attrs); - EXPECT_TRUE(NameOpt.hasValue()); + EXPECT_TRUE(NameOpt.has_value()); EXPECT_EQ(DieMangled, toString(NameOpt, "")); } diff --git a/llvm/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp b/llvm/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp index 9976777..c81059c 100644 --- a/llvm/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp +++ b/llvm/unittests/DebugInfo/DWARF/DWARFFormValueTest.cpp @@ -79,17 +79,17 @@ TEST(DWARFFormValue, SignedConstantForms) { auto Sign2 = createDataXFormValue<uint16_t>(DW_FORM_data2, -12345); auto Sign4 = createDataXFormValue<uint32_t>(DW_FORM_data4, -123456789); auto Sign8 = createDataXFormValue<uint64_t>(DW_FORM_data8, -1); - EXPECT_EQ(Sign1.getAsSignedConstant().getValue(), -123); - EXPECT_EQ(Sign2.getAsSignedConstant().getValue(), -12345); - EXPECT_EQ(Sign4.getAsSignedConstant().getValue(), -123456789); - EXPECT_EQ(Sign8.getAsSignedConstant().getValue(), -1); + EXPECT_EQ(Sign1.getAsSignedConstant().value(), -123); + EXPECT_EQ(Sign2.getAsSignedConstant().value(), -12345); + EXPECT_EQ(Sign4.getAsSignedConstant().value(), -123456789); + EXPECT_EQ(Sign8.getAsSignedConstant().value(), -1); // Check that we can handle big positive values, but that we return // an error just over the limit. auto UMax = createULEBFormValue(LLONG_MAX); auto TooBig = createULEBFormValue(uint64_t(LLONG_MAX) + 1); - EXPECT_EQ(UMax.getAsSignedConstant().getValue(), LLONG_MAX); - EXPECT_EQ(TooBig.getAsSignedConstant().hasValue(), false); + EXPECT_EQ(UMax.getAsSignedConstant().value(), LLONG_MAX); + EXPECT_EQ(TooBig.getAsSignedConstant().has_value(), false); // Sanity check some other forms. auto Data1 = createDataXFormValue<uint8_t>(DW_FORM_data1, 120); @@ -100,14 +100,14 @@ TEST(DWARFFormValue, SignedConstantForms) { auto LEBMax = createSLEBFormValue(LLONG_MAX); auto LEB1 = createSLEBFormValue(-42); auto LEB2 = createSLEBFormValue(42); - EXPECT_EQ(Data1.getAsSignedConstant().getValue(), 120); - EXPECT_EQ(Data2.getAsSignedConstant().getValue(), 32000); - EXPECT_EQ(Data4.getAsSignedConstant().getValue(), 2000000000); - EXPECT_EQ(Data8.getAsSignedConstant().getValue(), 0x1234567812345678LL); - EXPECT_EQ(LEBMin.getAsSignedConstant().getValue(), LLONG_MIN); - EXPECT_EQ(LEBMax.getAsSignedConstant().getValue(), LLONG_MAX); - EXPECT_EQ(LEB1.getAsSignedConstant().getValue(), -42); - EXPECT_EQ(LEB2.getAsSignedConstant().getValue(), 42); + EXPECT_EQ(Data1.getAsSignedConstant().value(), 120); + EXPECT_EQ(Data2.getAsSignedConstant().value(), 32000); + EXPECT_EQ(Data4.getAsSignedConstant().value(), 2000000000); + EXPECT_EQ(Data8.getAsSignedConstant().value(), 0x1234567812345678LL); + EXPECT_EQ(LEBMin.getAsSignedConstant().value(), LLONG_MIN); + EXPECT_EQ(LEBMax.getAsSignedConstant().value(), LLONG_MAX); + EXPECT_EQ(LEB1.getAsSignedConstant().value(), -42); + EXPECT_EQ(LEB2.getAsSignedConstant().value(), 42); // Data16 is a little tricky. char Cksum[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; diff --git a/llvm/unittests/DebugInfo/GSYM/GSYMTest.cpp b/llvm/unittests/DebugInfo/GSYM/GSYMTest.cpp index 977231d..bfe66f0 100644 --- a/llvm/unittests/DebugInfo/GSYM/GSYMTest.cpp +++ b/llvm/unittests/DebugInfo/GSYM/GSYMTest.cpp @@ -1349,8 +1349,8 @@ TEST(GSYMTest, TestDWARFFunctionWithAddresses) { auto ExpFI = GR->getFunctionInfo(0x1000); ASSERT_THAT_EXPECTED(ExpFI, Succeeded()); ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000)); - EXPECT_FALSE(ExpFI->OptLineTable.hasValue()); - EXPECT_FALSE(ExpFI->Inline.hasValue()); + EXPECT_FALSE(ExpFI->OptLineTable.has_value()); + EXPECT_FALSE(ExpFI->Inline.has_value()); } TEST(GSYMTest, TestDWARFFunctionWithAddressAndOffset) { @@ -1426,8 +1426,8 @@ TEST(GSYMTest, TestDWARFFunctionWithAddressAndOffset) { auto ExpFI = GR->getFunctionInfo(0x1000); ASSERT_THAT_EXPECTED(ExpFI, Succeeded()); ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000)); - EXPECT_FALSE(ExpFI->OptLineTable.hasValue()); - EXPECT_FALSE(ExpFI->Inline.hasValue()); + EXPECT_FALSE(ExpFI->OptLineTable.has_value()); + EXPECT_FALSE(ExpFI->Inline.has_value()); } TEST(GSYMTest, TestDWARFStructMethodNoMangled) { @@ -1533,8 +1533,8 @@ TEST(GSYMTest, TestDWARFStructMethodNoMangled) { auto ExpFI = GR->getFunctionInfo(0x1000); ASSERT_THAT_EXPECTED(ExpFI, Succeeded()); ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000)); - EXPECT_FALSE(ExpFI->OptLineTable.hasValue()); - EXPECT_FALSE(ExpFI->Inline.hasValue()); + EXPECT_FALSE(ExpFI->OptLineTable.has_value()); + EXPECT_FALSE(ExpFI->Inline.has_value()); StringRef MethodName = GR->getString(ExpFI->Name); EXPECT_EQ(MethodName, "Foo::dump"); } @@ -1638,8 +1638,8 @@ TEST(GSYMTest, TestDWARFTextRanges) { auto ExpFI = GR->getFunctionInfo(0x1000); ASSERT_THAT_EXPECTED(ExpFI, Succeeded()); ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000)); - EXPECT_FALSE(ExpFI->OptLineTable.hasValue()); - EXPECT_FALSE(ExpFI->Inline.hasValue()); + EXPECT_FALSE(ExpFI->OptLineTable.has_value()); + EXPECT_FALSE(ExpFI->Inline.has_value()); StringRef MethodName = GR->getString(ExpFI->Name); EXPECT_EQ(MethodName, "main"); } @@ -1667,8 +1667,8 @@ TEST(GSYMTest, TestEmptySymbolEndAddressOfTextRanges) { auto ExpFI = GR->getFunctionInfo(0x1500); ASSERT_THAT_EXPECTED(ExpFI, Succeeded()); ASSERT_EQ(ExpFI->Range, AddressRange(0x1500, 0x2000)); - EXPECT_FALSE(ExpFI->OptLineTable.hasValue()); - EXPECT_FALSE(ExpFI->Inline.hasValue()); + EXPECT_FALSE(ExpFI->OptLineTable.has_value()); + EXPECT_FALSE(ExpFI->Inline.has_value()); StringRef MethodName = GR->getString(ExpFI->Name); EXPECT_EQ(MethodName, "symbol"); } @@ -1836,8 +1836,8 @@ TEST(GSYMTest, TestDWARFInlineInfo) { auto ExpFI = GR->getFunctionInfo(0x1000); ASSERT_THAT_EXPECTED(ExpFI, Succeeded()); ASSERT_EQ(ExpFI->Range, AddressRange(0x1000, 0x2000)); - EXPECT_TRUE(ExpFI->OptLineTable.hasValue()); - EXPECT_TRUE(ExpFI->Inline.hasValue()); + EXPECT_TRUE(ExpFI->OptLineTable.has_value()); + EXPECT_TRUE(ExpFI->Inline.has_value()); StringRef MethodName = GR->getString(ExpFI->Name); EXPECT_EQ(MethodName, "main"); @@ -2122,14 +2122,14 @@ TEST(GSYMTest, TestDWARFNoLines) { ASSERT_THAT_EXPECTED(ExpFI, Succeeded()); ASSERT_EQ(ExpFI->Range, AddressRange(0x3000, 0x4000)); // Make sure we have no line table. - EXPECT_FALSE(ExpFI->OptLineTable.hasValue()); + EXPECT_FALSE(ExpFI->OptLineTable.has_value()); MethodName = GR->getString(ExpFI->Name); EXPECT_EQ(MethodName, "no_lines_no_decl"); ExpFI = GR->getFunctionInfo(0x4000); ASSERT_THAT_EXPECTED(ExpFI, Succeeded()); ASSERT_EQ(ExpFI->Range, AddressRange(0x4000, 0x5000)); - EXPECT_TRUE(ExpFI->OptLineTable.hasValue()); + EXPECT_TRUE(ExpFI->OptLineTable.has_value()); MethodName = GR->getString(ExpFI->Name); EXPECT_EQ(MethodName, "no_lines_with_decl"); // Make sure we have one line table entry that uses the DW_AT_decl_file/line diff --git a/llvm/unittests/FileCheck/FileCheckTest.cpp b/llvm/unittests/FileCheck/FileCheckTest.cpp index f3b5d3d..39230c4 100644 --- a/llvm/unittests/FileCheck/FileCheckTest.cpp +++ b/llvm/unittests/FileCheck/FileCheckTest.cpp @@ -766,8 +766,8 @@ TEST_F(FileCheckTest, NumericVariable) { ASSERT_TRUE(Value); EXPECT_EQ(925, cantFail(Value->getSignedValue())); // getStringValue should return the same memory not just the same characters. - EXPECT_EQ(StringValue.begin(), FooVar.getStringValue().getValue().begin()); - EXPECT_EQ(StringValue.end(), FooVar.getStringValue().getValue().end()); + EXPECT_EQ(StringValue.begin(), FooVar.getStringValue()->begin()); + EXPECT_EQ(StringValue.end(), FooVar.getStringValue()->end()); EvalResult = FooVarUse.eval(); ASSERT_THAT_EXPECTED(EvalResult, Succeeded()); EXPECT_EQ(925, cantFail(EvalResult->getSignedValue())); diff --git a/llvm/unittests/IR/MetadataTest.cpp b/llvm/unittests/IR/MetadataTest.cpp index 0c73aaa..a755dfa 100644 --- a/llvm/unittests/IR/MetadataTest.cpp +++ b/llvm/unittests/IR/MetadataTest.cpp @@ -1045,52 +1045,51 @@ TEST_F(DILocationTest, cloneTemporary) { } TEST_F(DILocationTest, discriminatorEncoding) { - EXPECT_EQ(0U, DILocation::encodeDiscriminator(0, 0, 0).getValue()); + EXPECT_EQ(0U, DILocation::encodeDiscriminator(0, 0, 0).value()); // Encode base discriminator as a component: lsb is 0, then the value. // The other components are all absent, so we leave all the other bits 0. - EXPECT_EQ(2U, DILocation::encodeDiscriminator(1, 0, 0).getValue()); + EXPECT_EQ(2U, DILocation::encodeDiscriminator(1, 0, 0).value()); // Base discriminator component is empty, so lsb is 1. Next component is not // empty, so its lsb is 0, then its value (1). Next component is empty. // So the bit pattern is 101. - EXPECT_EQ(5U, DILocation::encodeDiscriminator(0, 1, 0).getValue()); + EXPECT_EQ(5U, DILocation::encodeDiscriminator(0, 1, 0).value()); // First 2 components are empty, so the bit pattern is 11. Then the // next component - ending up with 1011. - EXPECT_EQ(0xbU, DILocation::encodeDiscriminator(0, 0, 1).getValue()); + EXPECT_EQ(0xbU, DILocation::encodeDiscriminator(0, 0, 1).value()); // The bit pattern for the first 2 components is 11. The next bit is 0, // because the last component is not empty. We have 29 bits usable for // encoding, but we cap it at 12 bits uniformously for all components. We // encode the last component over 14 bits. - EXPECT_EQ(0xfffbU, DILocation::encodeDiscriminator(0, 0, 0xfff).getValue()); + EXPECT_EQ(0xfffbU, DILocation::encodeDiscriminator(0, 0, 0xfff).value()); - EXPECT_EQ(0x102U, DILocation::encodeDiscriminator(1, 1, 0).getValue()); + EXPECT_EQ(0x102U, DILocation::encodeDiscriminator(1, 1, 0).value()); - EXPECT_EQ(0x13eU, DILocation::encodeDiscriminator(0x1f, 1, 0).getValue()); + EXPECT_EQ(0x13eU, DILocation::encodeDiscriminator(0x1f, 1, 0).value()); - EXPECT_EQ(0x87feU, DILocation::encodeDiscriminator(0x1ff, 1, 0).getValue()); + EXPECT_EQ(0x87feU, DILocation::encodeDiscriminator(0x1ff, 1, 0).value()); - EXPECT_EQ(0x1f3eU, DILocation::encodeDiscriminator(0x1f, 0x1f, 0).getValue()); + EXPECT_EQ(0x1f3eU, DILocation::encodeDiscriminator(0x1f, 0x1f, 0).value()); - EXPECT_EQ(0x3ff3eU, - DILocation::encodeDiscriminator(0x1f, 0x1ff, 0).getValue()); + EXPECT_EQ(0x3ff3eU, DILocation::encodeDiscriminator(0x1f, 0x1ff, 0).value()); EXPECT_EQ(0x1ff87feU, - DILocation::encodeDiscriminator(0x1ff, 0x1ff, 0).getValue()); + DILocation::encodeDiscriminator(0x1ff, 0x1ff, 0).value()); EXPECT_EQ(0xfff9f3eU, - DILocation::encodeDiscriminator(0x1f, 0x1f, 0xfff).getValue()); + DILocation::encodeDiscriminator(0x1f, 0x1f, 0xfff).value()); EXPECT_EQ(0xffc3ff3eU, - DILocation::encodeDiscriminator(0x1f, 0x1ff, 0x1ff).getValue()); + DILocation::encodeDiscriminator(0x1f, 0x1ff, 0x1ff).value()); EXPECT_EQ(0xffcf87feU, - DILocation::encodeDiscriminator(0x1ff, 0x1f, 0x1ff).getValue()); + DILocation::encodeDiscriminator(0x1ff, 0x1f, 0x1ff).value()); EXPECT_EQ(0xe1ff87feU, - DILocation::encodeDiscriminator(0x1ff, 0x1ff, 7).getValue()); + DILocation::encodeDiscriminator(0x1ff, 0x1ff, 7).value()); } TEST_F(DILocationTest, discriminatorEncodingNegativeTests) { @@ -1113,36 +1112,36 @@ TEST_F(DILocationTest, discriminatorSpecialCases) { EXPECT_EQ(0U, L1->getBaseDiscriminator()); EXPECT_EQ(1U, L1->getDuplicationFactor()); - EXPECT_EQ(L1, L1->cloneWithBaseDiscriminator(0).getValue()); - EXPECT_EQ(L1, L1->cloneByMultiplyingDuplicationFactor(0).getValue()); - EXPECT_EQ(L1, L1->cloneByMultiplyingDuplicationFactor(1).getValue()); + EXPECT_EQ(L1, L1->cloneWithBaseDiscriminator(0).value()); + EXPECT_EQ(L1, L1->cloneByMultiplyingDuplicationFactor(0).value()); + EXPECT_EQ(L1, L1->cloneByMultiplyingDuplicationFactor(1).value()); - auto L2 = L1->cloneWithBaseDiscriminator(1).getValue(); + auto L2 = L1->cloneWithBaseDiscriminator(1).value(); EXPECT_EQ(0U, L1->getBaseDiscriminator()); EXPECT_EQ(1U, L1->getDuplicationFactor()); EXPECT_EQ(1U, L2->getBaseDiscriminator()); EXPECT_EQ(1U, L2->getDuplicationFactor()); - auto L3 = L2->cloneByMultiplyingDuplicationFactor(2).getValue(); + auto L3 = L2->cloneByMultiplyingDuplicationFactor(2).value(); EXPECT_EQ(1U, L3->getBaseDiscriminator()); EXPECT_EQ(2U, L3->getDuplicationFactor()); - EXPECT_EQ(L2, L2->cloneByMultiplyingDuplicationFactor(1).getValue()); + EXPECT_EQ(L2, L2->cloneByMultiplyingDuplicationFactor(1).value()); - auto L4 = L3->cloneByMultiplyingDuplicationFactor(4).getValue(); + auto L4 = L3->cloneByMultiplyingDuplicationFactor(4).value(); EXPECT_EQ(1U, L4->getBaseDiscriminator()); EXPECT_EQ(8U, L4->getDuplicationFactor()); - auto L5 = L4->cloneWithBaseDiscriminator(2).getValue(); + auto L5 = L4->cloneWithBaseDiscriminator(2).value(); EXPECT_EQ(2U, L5->getBaseDiscriminator()); EXPECT_EQ(8U, L5->getDuplicationFactor()); // Check extreme cases - auto L6 = L1->cloneWithBaseDiscriminator(0xfff).getValue(); + auto L6 = L1->cloneWithBaseDiscriminator(0xfff).value(); EXPECT_EQ(0xfffU, L6->getBaseDiscriminator()); EXPECT_EQ(0xfffU, L6->cloneByMultiplyingDuplicationFactor(0xfff) - .getValue() + .value() ->getDuplicationFactor()); // Check we return None for unencodable cases. @@ -2933,22 +2932,24 @@ TEST_F(DIExpressionTest, createFragmentExpression) { #define EXPECT_VALID_FRAGMENT(Offset, Size, ...) \ do { \ uint64_t Elements[] = {__VA_ARGS__}; \ - DIExpression* Expression = DIExpression::get(Context, Elements); \ - EXPECT_TRUE(DIExpression::createFragmentExpression( \ - Expression, Offset, Size).hasValue()); \ + DIExpression *Expression = DIExpression::get(Context, Elements); \ + EXPECT_TRUE( \ + DIExpression::createFragmentExpression(Expression, Offset, Size) \ + .has_value()); \ } while (false) #define EXPECT_INVALID_FRAGMENT(Offset, Size, ...) \ do { \ uint64_t Elements[] = {__VA_ARGS__}; \ - DIExpression* Expression = DIExpression::get(Context, Elements); \ - EXPECT_FALSE(DIExpression::createFragmentExpression( \ - Expression, Offset, Size).hasValue()); \ + DIExpression *Expression = DIExpression::get(Context, Elements); \ + EXPECT_FALSE( \ + DIExpression::createFragmentExpression(Expression, Offset, Size) \ + .has_value()); \ } while (false) // createFragmentExpression adds correct ops. Optional<DIExpression*> R = DIExpression::createFragmentExpression( DIExpression::get(Context, {}), 0, 32); - EXPECT_EQ(R.hasValue(), true); + EXPECT_EQ(R.has_value(), true); EXPECT_EQ(3u, (*R)->getNumElements()); EXPECT_EQ(dwarf::DW_OP_LLVM_fragment, (*R)->getElement(0)); EXPECT_EQ(0u, (*R)->getElement(1)); @@ -3455,20 +3456,20 @@ TEST_F(FunctionAttachmentTest, Verifier) { TEST_F(FunctionAttachmentTest, RealEntryCount) { Function *F = getFunction("foo"); - EXPECT_FALSE(F->getEntryCount().hasValue()); + EXPECT_FALSE(F->getEntryCount().has_value()); F->setEntryCount(12304, Function::PCT_Real); auto Count = F->getEntryCount(); - EXPECT_TRUE(Count.hasValue()); + EXPECT_TRUE(Count.has_value()); EXPECT_EQ(12304u, Count->getCount()); EXPECT_EQ(Function::PCT_Real, Count->getType()); } TEST_F(FunctionAttachmentTest, SyntheticEntryCount) { Function *F = getFunction("bar"); - EXPECT_FALSE(F->getEntryCount().hasValue()); + EXPECT_FALSE(F->getEntryCount().has_value()); F->setEntryCount(123, Function::PCT_Synthetic); auto Count = F->getEntryCount(true /*allow synthetic*/); - EXPECT_TRUE(Count.hasValue()); + EXPECT_TRUE(Count.has_value()); EXPECT_EQ(123u, Count->getCount()); EXPECT_EQ(Function::PCT_Synthetic, Count->getType()); } diff --git a/llvm/unittests/IR/VPIntrinsicTest.cpp b/llvm/unittests/IR/VPIntrinsicTest.cpp index 62e16df..34123ef 100644 --- a/llvm/unittests/IR/VPIntrinsicTest.cpp +++ b/llvm/unittests/IR/VPIntrinsicTest.cpp @@ -128,25 +128,25 @@ protected: TEST_F(VPIntrinsicTest, VPIntrinsicsDefScopes) { Optional<Intrinsic::ID> ScopeVPID; #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) \ - ASSERT_FALSE(ScopeVPID.hasValue()); \ + ASSERT_FALSE(ScopeVPID.has_value()); \ ScopeVPID = Intrinsic::VPID; #define END_REGISTER_VP_INTRINSIC(VPID) \ - ASSERT_TRUE(ScopeVPID.hasValue()); \ - ASSERT_EQ(ScopeVPID.getValue(), Intrinsic::VPID); \ + ASSERT_TRUE(ScopeVPID.has_value()); \ + ASSERT_EQ(*ScopeVPID, Intrinsic::VPID); \ ScopeVPID = None; Optional<ISD::NodeType> ScopeOPC; #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \ - ASSERT_FALSE(ScopeOPC.hasValue()); \ + ASSERT_FALSE(ScopeOPC.has_value()); \ ScopeOPC = ISD::SDOPC; #define END_REGISTER_VP_SDNODE(SDOPC) \ - ASSERT_TRUE(ScopeOPC.hasValue()); \ - ASSERT_EQ(ScopeOPC.getValue(), ISD::SDOPC); \ + ASSERT_TRUE(ScopeOPC.has_value()); \ + ASSERT_EQ(*ScopeOPC, ISD::SDOPC); \ ScopeOPC = None; #include "llvm/IR/VPIntrinsics.def" - ASSERT_FALSE(ScopeVPID.hasValue()); - ASSERT_FALSE(ScopeOPC.hasValue()); + ASSERT_FALSE(ScopeVPID.has_value()); + ASSERT_FALSE(ScopeOPC.has_value()); } /// Check that every VP intrinsic in the test module is recognized as a VP @@ -233,8 +233,8 @@ TEST_F(VPIntrinsicTest, GetParamPos) { ASSERT_TRUE(F.isIntrinsic()); Optional<unsigned> MaskParamPos = VPIntrinsic::getMaskParamPos(F.getIntrinsicID()); - if (MaskParamPos.hasValue()) { - Type *MaskParamType = F.getArg(MaskParamPos.getValue())->getType(); + if (MaskParamPos) { + Type *MaskParamType = F.getArg(*MaskParamPos)->getType(); ASSERT_TRUE(MaskParamType->isVectorTy()); ASSERT_TRUE( cast<VectorType>(MaskParamType)->getElementType()->isIntegerTy(1)); @@ -242,8 +242,8 @@ TEST_F(VPIntrinsicTest, GetParamPos) { Optional<unsigned> VecLenParamPos = VPIntrinsic::getVectorLengthParamPos(F.getIntrinsicID()); - if (VecLenParamPos.hasValue()) { - Type *VecLenParamType = F.getArg(VecLenParamPos.getValue())->getType(); + if (VecLenParamPos) { + Type *VecLenParamType = F.getArg(*VecLenParamPos)->getType(); ASSERT_TRUE(VecLenParamType->isIntegerTy(32)); } } @@ -406,13 +406,13 @@ TEST_F(VPIntrinsicTest, VPReductions) { if (!VPReductionIntrinsic::isVPReduction(ID)) { EXPECT_EQ(VPRedI, nullptr); - EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID).hasValue(), false); - EXPECT_EQ(VPReductionIntrinsic::getVectorParamPos(ID).hasValue(), false); + EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID).has_value(), false); + EXPECT_EQ(VPReductionIntrinsic::getVectorParamPos(ID).has_value(), false); continue; } - EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID).hasValue(), true); - EXPECT_EQ(VPReductionIntrinsic::getVectorParamPos(ID).hasValue(), true); + EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID).has_value(), true); + EXPECT_EQ(VPReductionIntrinsic::getVectorParamPos(ID).has_value(), true); ASSERT_NE(VPRedI, nullptr); EXPECT_EQ(VPReductionIntrinsic::getStartParamPos(ID), VPRedI->getStartParamPos()); diff --git a/llvm/unittests/InterfaceStub/ELFYAMLTest.cpp b/llvm/unittests/InterfaceStub/ELFYAMLTest.cpp index 404dfd3..d347e17 100644 --- a/llvm/unittests/InterfaceStub/ELFYAMLTest.cpp +++ b/llvm/unittests/InterfaceStub/ELFYAMLTest.cpp @@ -47,9 +47,9 @@ TEST(ElfYamlTextAPI, YAMLReadableTBE) { ASSERT_THAT_ERROR(StubOrErr.takeError(), Succeeded()); std::unique_ptr<IFSStub> Stub = std::move(StubOrErr.get()); EXPECT_NE(Stub.get(), nullptr); - EXPECT_FALSE(Stub->SoName.hasValue()); - EXPECT_TRUE(Stub->Target.Arch.hasValue()); - EXPECT_EQ(Stub->Target.Arch.getValue(), (uint16_t)llvm::ELF::EM_X86_64); + EXPECT_FALSE(Stub->SoName.has_value()); + EXPECT_TRUE(Stub->Target.Arch.has_value()); + EXPECT_EQ(Stub->Target.Arch.value(), (uint16_t)llvm::ELF::EM_X86_64); EXPECT_EQ(Stub->NeededLibs.size(), 3u); EXPECT_STREQ(Stub->NeededLibs[0].c_str(), "libc.so"); EXPECT_STREQ(Stub->NeededLibs[1].c_str(), "libfoo.so"); @@ -94,24 +94,24 @@ TEST(ElfYamlTextAPI, YAMLReadsTBESymbols) { EXPECT_EQ(SymBaz.Type, IFSSymbolType::TLS); EXPECT_FALSE(SymBaz.Undefined); EXPECT_FALSE(SymBaz.Weak); - EXPECT_FALSE(SymBaz.Warning.hasValue()); + EXPECT_FALSE(SymBaz.Warning.has_value()); IFSSymbol const &SymFoo = *Iterator++; EXPECT_STREQ(SymFoo.Name.c_str(), "foo"); - EXPECT_FALSE(SymFoo.Size.hasValue()); + EXPECT_FALSE(SymFoo.Size.has_value()); EXPECT_EQ(SymFoo.Type, IFSSymbolType::Func); EXPECT_FALSE(SymFoo.Undefined); EXPECT_FALSE(SymFoo.Weak); - EXPECT_TRUE(SymFoo.Warning.hasValue()); + EXPECT_TRUE(SymFoo.Warning.has_value()); EXPECT_STREQ(SymFoo.Warning->c_str(), "Deprecated!"); IFSSymbol const &SymNor = *Iterator++; EXPECT_STREQ(SymNor.Name.c_str(), "nor"); - EXPECT_FALSE(SymNor.Size.hasValue()); + EXPECT_FALSE(SymNor.Size.has_value()); EXPECT_EQ(SymNor.Type, IFSSymbolType::NoType); EXPECT_TRUE(SymNor.Undefined); EXPECT_FALSE(SymNor.Weak); - EXPECT_FALSE(SymNor.Warning.hasValue()); + EXPECT_FALSE(SymNor.Warning.has_value()); IFSSymbol const &SymNot = *Iterator++; EXPECT_STREQ(SymNot.Name.c_str(), "not"); diff --git a/llvm/unittests/Object/XCOFFObjectFileTest.cpp b/llvm/unittests/Object/XCOFFObjectFileTest.cpp index 41662be..cf2be43 100644 --- a/llvm/unittests/Object/XCOFFObjectFileTest.cpp +++ b/llvm/unittests/Object/XCOFFObjectFileTest.cpp @@ -83,16 +83,16 @@ TEST(XCOFFObjectFileTest, XCOFFTracebackTableAPIGeneral) { EXPECT_TRUE(TT.hasParmsOnStack()); ASSERT_TRUE(TT.getParmsType()); - EXPECT_EQ(TT.getParmsType().getValue(), "i, f, d"); + EXPECT_EQ(TT.getParmsType().value(), "i, f, d"); ASSERT_TRUE(TT.getTraceBackTableOffset()); - EXPECT_EQ(TT.getTraceBackTableOffset().getValue(), 64u); + EXPECT_EQ(TT.getTraceBackTableOffset().value(), 64u); EXPECT_FALSE(TT.getHandlerMask()); ASSERT_TRUE(TT.getFunctionName()); - EXPECT_EQ(TT.getFunctionName().getValue(), "add_all"); - EXPECT_EQ(TT.getFunctionName().getValue().size(), 7u); + EXPECT_EQ(TT.getFunctionName().value(), "add_all"); + EXPECT_EQ(TT.getFunctionName()->size(), 7u); EXPECT_FALSE(TT.getAllocaRegister()); EXPECT_EQ(Size, 25u); @@ -171,11 +171,11 @@ TEST(XCOFFObjectFileTest, XCOFFTracebackTableAPIControlledStorageInfoDisp) { XCOFFTracebackTable TT = *TTOrErr; EXPECT_TRUE(TT.hasControlledStorage()); ASSERT_TRUE(TT.getNumOfCtlAnchors()); - EXPECT_EQ(TT.getNumOfCtlAnchors().getValue(), 2u); + EXPECT_EQ(TT.getNumOfCtlAnchors().value(), 2u); ASSERT_TRUE(TT.getControlledStorageInfoDisp()); - SmallVector<uint32_t, 8> Disp = TT.getControlledStorageInfoDisp().getValue(); + SmallVector<uint32_t, 8> Disp = TT.getControlledStorageInfoDisp().value(); ASSERT_EQ(Disp.size(), 2UL); EXPECT_EQ(Disp[0], 0x05050000u); @@ -207,10 +207,10 @@ TEST(XCOFFObjectFileTest, XCOFFTracebackTableAPIHasVectorInfo) { EXPECT_TRUE(TT.hasExtensionTable()); ASSERT_TRUE(TT.getParmsType()); - EXPECT_EQ(TT.getParmsType().getValue(), "v, i, f, i, d, i, v"); + EXPECT_EQ(TT.getParmsType().value(), "v, i, f, i, d, i, v"); ASSERT_TRUE(TT.getVectorExt()); - TBVectorExt VecExt = TT.getVectorExt().getValue(); + TBVectorExt VecExt = TT.getVectorExt().value(); EXPECT_EQ(VecExt.getNumberOfVRSaved(), 0); EXPECT_TRUE(VecExt.isVRSavedOnStack()); @@ -240,10 +240,10 @@ TEST(XCOFFObjectFileTest, XCOFFTracebackTableAPIHasVectorInfo1) { XCOFFTracebackTable TT = *TTOrErr; ASSERT_TRUE(TT.getParmsType()); - EXPECT_EQ(TT.getParmsType().getValue(), "v, i, f, i, d, i, v, v"); + EXPECT_EQ(TT.getParmsType().value(), "v, i, f, i, d, i, v, v"); ASSERT_TRUE(TT.getVectorExt()); - TBVectorExt VecExt = TT.getVectorExt().getValue(); + TBVectorExt VecExt = TT.getVectorExt().value(); EXPECT_EQ(VecExt.getNumberOfVRSaved(), 4); EXPECT_FALSE(VecExt.isVRSavedOnStack()); diff --git a/llvm/unittests/ObjectYAML/DWARFYAMLTest.cpp b/llvm/unittests/ObjectYAML/DWARFYAMLTest.cpp index 91febff..09c9e35 100644 --- a/llvm/unittests/ObjectYAML/DWARFYAMLTest.cpp +++ b/llvm/unittests/ObjectYAML/DWARFYAMLTest.cpp @@ -91,8 +91,8 @@ debug_pubtypes: DWARFYAML::Data Data; ASSERT_THAT_ERROR(parseDWARFYAML(Yaml, Data), Succeeded()); - ASSERT_TRUE(Data.PubNames.hasValue()); - DWARFYAML::PubSection PubNames = Data.PubNames.getValue(); + ASSERT_TRUE(Data.PubNames.has_value()); + DWARFYAML::PubSection PubNames = Data.PubNames.value(); ASSERT_EQ(PubNames.Entries.size(), 2u); EXPECT_EQ((uint32_t)PubNames.Entries[0].DieOffset, 0x1234u); @@ -100,8 +100,8 @@ debug_pubtypes: EXPECT_EQ((uint32_t)PubNames.Entries[1].DieOffset, 0x4321u); EXPECT_EQ(PubNames.Entries[1].Name, "def"); - ASSERT_TRUE(Data.PubTypes.hasValue()); - DWARFYAML::PubSection PubTypes = Data.PubTypes.getValue(); + ASSERT_TRUE(Data.PubTypes.has_value()); + DWARFYAML::PubSection PubTypes = Data.PubTypes.value(); ASSERT_EQ(PubTypes.Entries.size(), 2u); EXPECT_EQ((uint32_t)PubTypes.Entries[0].DieOffset, 0x1234u); @@ -157,8 +157,8 @@ debug_gnu_pubtypes: DWARFYAML::Data Data; ASSERT_THAT_ERROR(parseDWARFYAML(Yaml, Data), Succeeded()); - ASSERT_TRUE(Data.GNUPubNames.hasValue()); - DWARFYAML::PubSection GNUPubNames = Data.GNUPubNames.getValue(); + ASSERT_TRUE(Data.GNUPubNames.has_value()); + DWARFYAML::PubSection GNUPubNames = Data.GNUPubNames.value(); ASSERT_EQ(GNUPubNames.Entries.size(), 2u); EXPECT_EQ((uint32_t)GNUPubNames.Entries[0].DieOffset, 0x1234u); @@ -168,8 +168,8 @@ debug_gnu_pubtypes: EXPECT_EQ((uint8_t)GNUPubNames.Entries[1].Descriptor, 0x34); EXPECT_EQ(GNUPubNames.Entries[1].Name, "def"); - ASSERT_TRUE(Data.GNUPubTypes.hasValue()); - DWARFYAML::PubSection GNUPubTypes = Data.GNUPubTypes.getValue(); + ASSERT_TRUE(Data.GNUPubTypes.has_value()); + DWARFYAML::PubSection GNUPubTypes = Data.GNUPubTypes.value(); ASSERT_EQ(GNUPubTypes.Entries.size(), 2u); EXPECT_EQ((uint32_t)GNUPubTypes.Entries[0].DieOffset, 0x1234u); diff --git a/llvm/unittests/ProfileData/MemProfTest.cpp b/llvm/unittests/ProfileData/MemProfTest.cpp index 4808481..290d331 100644 --- a/llvm/unittests/ProfileData/MemProfTest.cpp +++ b/llvm/unittests/ProfileData/MemProfTest.cpp @@ -104,9 +104,9 @@ MATCHER_P4(FrameContains, FunctionName, LineOffset, Column, Inline, "") { *result_listener << "Hash mismatch"; return false; } - if (F.SymbolName.hasValue() && F.SymbolName.getValue() != FunctionName) { + if (F.SymbolName && F.SymbolName.value() != FunctionName) { *result_listener << "SymbolName mismatch\nWant: " << FunctionName - << "\nGot: " << F.SymbolName.getValue(); + << "\nGot: " << F.SymbolName.value(); return false; } if (F.LineOffset == LineOffset && F.Column == Column && diff --git a/llvm/unittests/Support/AlignmentTest.cpp b/llvm/unittests/Support/AlignmentTest.cpp index fa91997..fa26b60 100644 --- a/llvm/unittests/Support/AlignmentTest.cpp +++ b/llvm/unittests/Support/AlignmentTest.cpp @@ -63,11 +63,11 @@ TEST(AlignmentTest, ValidCTors) { TEST(AlignmentTest, CheckMaybeAlignHasValue) { EXPECT_TRUE(MaybeAlign(1)); - EXPECT_TRUE(MaybeAlign(1).hasValue()); + EXPECT_TRUE(MaybeAlign(1).has_value()); EXPECT_FALSE(MaybeAlign(0)); - EXPECT_FALSE(MaybeAlign(0).hasValue()); + EXPECT_FALSE(MaybeAlign(0).has_value()); EXPECT_FALSE(MaybeAlign()); - EXPECT_FALSE(MaybeAlign().hasValue()); + EXPECT_FALSE(MaybeAlign().has_value()); } TEST(AlignmentTest, Division) { @@ -165,8 +165,8 @@ TEST(AlignmentTest, isAligned_isAddrAligned) { MaybeAlign A(T.alignment); // Test Align if (A) { - EXPECT_EQ(isAligned(A.getValue(), T.offset), T.isAligned); - EXPECT_EQ(isAddrAligned(A.getValue(), T.forgedAddr()), T.isAligned); + EXPECT_EQ(isAligned(*A, T.offset), T.isAligned); + EXPECT_EQ(isAddrAligned(*A, T.forgedAddr()), T.isAligned); } } } diff --git a/llvm/unittests/Support/Casting.cpp b/llvm/unittests/Support/Casting.cpp index 311fefd..bebb36f 100644 --- a/llvm/unittests/Support/Casting.cpp +++ b/llvm/unittests/Support/Casting.cpp @@ -248,11 +248,11 @@ TEST(CastingTest, dyn_cast_value_types) { TEST(CastingTest, dyn_cast_if_present) { Optional<T1> empty{}; Optional<T2> F1 = dyn_cast_if_present<T2>(empty); - EXPECT_FALSE(F1.hasValue()); + EXPECT_FALSE(F1.has_value()); T1 t1; Optional<T2> F2 = dyn_cast_if_present<T2>(t1); - EXPECT_TRUE(F2.hasValue()); + EXPECT_TRUE(F2.has_value()); T1 *t1Null = nullptr; diff --git a/llvm/unittests/Support/KnownBitsTest.cpp b/llvm/unittests/Support/KnownBitsTest.cpp index 9ef62bb..1411c2e 100644 --- a/llvm/unittests/Support/KnownBitsTest.cpp +++ b/llvm/unittests/Support/KnownBitsTest.cpp @@ -358,38 +358,38 @@ TEST(KnownBitsTest, ICmpExhaustive) { Optional<bool> KnownSLT = KnownBits::slt(Known1, Known2); Optional<bool> KnownSLE = KnownBits::sle(Known1, Known2); - EXPECT_EQ(AllEQ || NoneEQ, KnownEQ.hasValue()); - EXPECT_EQ(AllNE || NoneNE, KnownNE.hasValue()); - EXPECT_EQ(AllUGT || NoneUGT, KnownUGT.hasValue()); - EXPECT_EQ(AllUGE || NoneUGE, KnownUGE.hasValue()); - EXPECT_EQ(AllULT || NoneULT, KnownULT.hasValue()); - EXPECT_EQ(AllULE || NoneULE, KnownULE.hasValue()); - EXPECT_EQ(AllSGT || NoneSGT, KnownSGT.hasValue()); - EXPECT_EQ(AllSGE || NoneSGE, KnownSGE.hasValue()); - EXPECT_EQ(AllSLT || NoneSLT, KnownSLT.hasValue()); - EXPECT_EQ(AllSLE || NoneSLE, KnownSLE.hasValue()); - - EXPECT_EQ(AllEQ, KnownEQ.hasValue() && KnownEQ.getValue()); - EXPECT_EQ(AllNE, KnownNE.hasValue() && KnownNE.getValue()); - EXPECT_EQ(AllUGT, KnownUGT.hasValue() && KnownUGT.getValue()); - EXPECT_EQ(AllUGE, KnownUGE.hasValue() && KnownUGE.getValue()); - EXPECT_EQ(AllULT, KnownULT.hasValue() && KnownULT.getValue()); - EXPECT_EQ(AllULE, KnownULE.hasValue() && KnownULE.getValue()); - EXPECT_EQ(AllSGT, KnownSGT.hasValue() && KnownSGT.getValue()); - EXPECT_EQ(AllSGE, KnownSGE.hasValue() && KnownSGE.getValue()); - EXPECT_EQ(AllSLT, KnownSLT.hasValue() && KnownSLT.getValue()); - EXPECT_EQ(AllSLE, KnownSLE.hasValue() && KnownSLE.getValue()); - - EXPECT_EQ(NoneEQ, KnownEQ.hasValue() && !KnownEQ.getValue()); - EXPECT_EQ(NoneNE, KnownNE.hasValue() && !KnownNE.getValue()); - EXPECT_EQ(NoneUGT, KnownUGT.hasValue() && !KnownUGT.getValue()); - EXPECT_EQ(NoneUGE, KnownUGE.hasValue() && !KnownUGE.getValue()); - EXPECT_EQ(NoneULT, KnownULT.hasValue() && !KnownULT.getValue()); - EXPECT_EQ(NoneULE, KnownULE.hasValue() && !KnownULE.getValue()); - EXPECT_EQ(NoneSGT, KnownSGT.hasValue() && !KnownSGT.getValue()); - EXPECT_EQ(NoneSGE, KnownSGE.hasValue() && !KnownSGE.getValue()); - EXPECT_EQ(NoneSLT, KnownSLT.hasValue() && !KnownSLT.getValue()); - EXPECT_EQ(NoneSLE, KnownSLE.hasValue() && !KnownSLE.getValue()); + EXPECT_EQ(AllEQ || NoneEQ, KnownEQ.has_value()); + EXPECT_EQ(AllNE || NoneNE, KnownNE.has_value()); + EXPECT_EQ(AllUGT || NoneUGT, KnownUGT.has_value()); + EXPECT_EQ(AllUGE || NoneUGE, KnownUGE.has_value()); + EXPECT_EQ(AllULT || NoneULT, KnownULT.has_value()); + EXPECT_EQ(AllULE || NoneULE, KnownULE.has_value()); + EXPECT_EQ(AllSGT || NoneSGT, KnownSGT.has_value()); + EXPECT_EQ(AllSGE || NoneSGE, KnownSGE.has_value()); + EXPECT_EQ(AllSLT || NoneSLT, KnownSLT.has_value()); + EXPECT_EQ(AllSLE || NoneSLE, KnownSLE.has_value()); + + EXPECT_EQ(AllEQ, KnownEQ && *KnownEQ); + EXPECT_EQ(AllNE, KnownNE && *KnownNE); + EXPECT_EQ(AllUGT, KnownUGT && *KnownUGT); + EXPECT_EQ(AllUGE, KnownUGE && *KnownUGE); + EXPECT_EQ(AllULT, KnownULT && *KnownULT); + EXPECT_EQ(AllULE, KnownULE && *KnownULE); + EXPECT_EQ(AllSGT, KnownSGT && *KnownSGT); + EXPECT_EQ(AllSGE, KnownSGE && *KnownSGE); + EXPECT_EQ(AllSLT, KnownSLT && *KnownSLT); + EXPECT_EQ(AllSLE, KnownSLE && *KnownSLE); + + EXPECT_EQ(NoneEQ, KnownEQ && !*KnownEQ); + EXPECT_EQ(NoneNE, KnownNE && !*KnownNE); + EXPECT_EQ(NoneUGT, KnownUGT && !*KnownUGT); + EXPECT_EQ(NoneUGE, KnownUGE && !*KnownUGE); + EXPECT_EQ(NoneULT, KnownULT && !*KnownULT); + EXPECT_EQ(NoneULE, KnownULE && !*KnownULE); + EXPECT_EQ(NoneSGT, KnownSGT && !*KnownSGT); + EXPECT_EQ(NoneSGE, KnownSGE && !*KnownSGE); + EXPECT_EQ(NoneSLT, KnownSLT && !*KnownSLT); + EXPECT_EQ(NoneSLE, KnownSLE && !*KnownSLE); }); }); } diff --git a/llvm/unittests/Support/YAMLParserTest.cpp b/llvm/unittests/Support/YAMLParserTest.cpp index 692d963..14def9c 100644 --- a/llvm/unittests/Support/YAMLParserTest.cpp +++ b/llvm/unittests/Support/YAMLParserTest.cpp @@ -344,12 +344,12 @@ TEST(YAMLParser, FlowSequenceTokensOutsideFlowSequence) { static void expectCanParseBool(StringRef S, bool Expected) { llvm::Optional<bool> Parsed = yaml::parseBool(S); - EXPECT_TRUE(Parsed.hasValue()); + EXPECT_TRUE(Parsed.has_value()); EXPECT_EQ(*Parsed, Expected); } static void expectCannotParseBool(StringRef S) { - EXPECT_FALSE(yaml::parseBool(S).hasValue()); + EXPECT_FALSE(yaml::parseBool(S).has_value()); } TEST(YAMLParser, ParsesBools) { diff --git a/llvm/unittests/TableGen/ParserEntryPointTest.cpp b/llvm/unittests/TableGen/ParserEntryPointTest.cpp index 23642b6..a227f3d 100644 --- a/llvm/unittests/TableGen/ParserEntryPointTest.cpp +++ b/llvm/unittests/TableGen/ParserEntryPointTest.cpp @@ -35,6 +35,6 @@ TEST(Parser, SanityTest) { Record *Foo = Records.getDef("Foo"); Optional<StringRef> Field = Foo->getValueAsOptionalString("strField"); - EXPECT_TRUE(Field.hasValue()); - EXPECT_EQ(Field.getValue(), "value"); + EXPECT_TRUE(Field.has_value()); + EXPECT_EQ(*Field, "value"); } diff --git a/llvm/utils/TableGen/GlobalISel/GIMatchTree.h b/llvm/utils/TableGen/GlobalISel/GIMatchTree.h index 56df377..55a8625 100644 --- a/llvm/utils/TableGen/GlobalISel/GIMatchTree.h +++ b/llvm/utils/TableGen/GlobalISel/GIMatchTree.h @@ -32,11 +32,11 @@ public: Optional<unsigned> OpIdx = None) : Name(Name), InstrID(InstrID), OpIdx(OpIdx) {} - bool isInstr() const { return !OpIdx.hasValue(); } + bool isInstr() const { return !OpIdx; } StringRef getName() const { return Name; } unsigned getInstrID() const { return InstrID; } unsigned getOpIdx() const { - assert(OpIdx.hasValue() && "Is not an operand binding"); + assert(OpIdx && "Is not an operand binding"); return *OpIdx; } }; diff --git a/llvm/utils/TableGen/GlobalISelEmitter.cpp b/llvm/utils/TableGen/GlobalISelEmitter.cpp index e4ea6da..e5e216b 100644 --- a/llvm/utils/TableGen/GlobalISelEmitter.cpp +++ b/llvm/utils/TableGen/GlobalISelEmitter.cpp @@ -2936,14 +2936,14 @@ public: } void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { - Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer" - : "GIR_ComplexRenderer") + Table << MatchTable::Opcode(SubOperand ? "GIR_ComplexSubOperandRenderer" + : "GIR_ComplexRenderer") << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) << MatchTable::Comment("RendererID") << MatchTable::IntValue(RendererID); - if (SubOperand.hasValue()) + if (SubOperand) Table << MatchTable::Comment("SubOperand") - << MatchTable::IntValue(SubOperand.getValue()); + << MatchTable::IntValue(*SubOperand); Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; } }; @@ -4946,8 +4946,8 @@ Error GlobalISelEmitter::importDefaultOperandRenderers( auto Def = DefaultDefOp->getDef(); if (Def->getName() == "undef_tied_input") { unsigned TempRegID = M.allocateTempRegID(); - M.insertAction<MakeTempRegisterAction>( - InsertPt, OpTyOrNone.getValue(), TempRegID); + M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTyOrNone, + TempRegID); InsertPt = M.insertAction<BuildMIAction>( InsertPt, M.allocateOutputInsnID(), &Target.getInstruction(RK.getDef("IMPLICIT_DEF"))); diff --git a/mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h b/mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h index b307f0d..d4f9414 100644 --- a/mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h +++ b/mlir/include/mlir/Dialect/Affine/Analysis/AffineStructures.h @@ -400,13 +400,13 @@ public: inline Value getValue(unsigned pos) const { assert(pos < getNumDimAndSymbolIds() && "Invalid position"); assert(hasValue(pos) && "identifier's Value not set"); - return values[pos].getValue(); + return values[pos].value(); } /// Returns true if the pos^th identifier has an associated Value. inline bool hasValue(unsigned pos) const { assert(pos < getNumDimAndSymbolIds() && "Invalid position"); - return values[pos].hasValue(); + return values[pos].has_value(); } /// Returns true if at least one identifier has an associated Value. diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td index 1b547bb..52a7ef3 100644 --- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td +++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td @@ -347,8 +347,8 @@ def LLVM_FNegOp : LLVM_UnaryFloatArithmeticOp< // of LLVM ops that accept such an attribute. class MemoryOpWithAlignmentBase { code setAlignmentCode = [{ - if ($alignment.hasValue()) { - auto align = $alignment.getValue(); + if ($alignment) { + auto align = *$alignment; if (align != 0) inst->setAlignment(llvm::Align(align)); } diff --git a/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td index 24287f1..e51460e 100644 --- a/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td +++ b/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td @@ -568,8 +568,8 @@ class MMA_SYNC_INTR { # op[1].ptx_elt_type # "\" == eltypeB && " # " \"" # op[2].ptx_elt_type # "\" == eltypeC && " # " \"" # op[3].ptx_elt_type # "\" == eltypeD " - # " && (sat.hasValue() ? " # sat # " == static_cast<int>(*sat) : true)" - # !if(!ne(b1op, ""), " && (b1Op.hasValue() ? MMAB1Op::" # b1op # " == b1Op.getValue() : true)", "") # ")\n" + # " && (sat ? " # sat # " == static_cast<int>(*sat) : true)" + # !if(!ne(b1op, ""), " && (b1Op ? MMAB1Op::" # b1op # " == *b1Op : true)", "") # ")\n" # " return " # MMA_SYNC_NAME<layoutA, layoutB, b1op, sat, op[0], op[1], op[2], op[3]>.id # ";", "") // if supported @@ -995,8 +995,8 @@ def NVVM_MmaOp : NVVM_Op<"mma.sync", [AttrSizedOperandSegments]> { $shape.getM(), $shape.getN(), $shape.getK(), $b1Op, $intOverflowBehavior, $layoutA, $layoutB, - $multiplicandAPtxType.getValue(), - $multiplicandBPtxType.getValue(), + *$multiplicandAPtxType, + *$multiplicandBPtxType, op.accumPtxType(), op.resultPtxType()); diff --git a/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h b/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h index ef891dd..2aea098 100644 --- a/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h +++ b/mlir/include/mlir/Dialect/Transform/IR/TransformInterfaces.h @@ -75,11 +75,11 @@ public: } /// Returns `true` if this is a silencable failure. - bool isSilenceableFailure() const { return diagnostic.hasValue(); } + bool isSilenceableFailure() const { return diagnostic.has_value(); } /// Returns `true` if this is a success. bool succeeded() const { - return !diagnostic.hasValue() && ::mlir::succeeded(result); + return !diagnostic.has_value() && ::mlir::succeeded(result); } /// Returns the diagnostic message without emitting it. Expects this object diff --git a/mlir/include/mlir/IR/OpDefinition.h b/mlir/include/mlir/IR/OpDefinition.h index 42eccde..6023172 100644 --- a/mlir/include/mlir/IR/OpDefinition.h +++ b/mlir/include/mlir/IR/OpDefinition.h @@ -44,11 +44,11 @@ public: OptionalParseResult(llvm::NoneType) : impl(llvm::None) {} /// Returns true if we contain a valid ParseResult value. - bool hasValue() const { return impl.hasValue(); } + bool has_value() const { return impl.has_value(); } /// Access the internal ParseResult value. - ParseResult getValue() const { return impl.getValue(); } - ParseResult operator*() const { return getValue(); } + ParseResult value() const { return impl.value(); } + ParseResult operator*() const { return value(); } private: Optional<ParseResult> impl; diff --git a/mlir/include/mlir/IR/OpImplementation.h b/mlir/include/mlir/IR/OpImplementation.h index 2acb2c7..af75fed 100644 --- a/mlir/include/mlir/IR/OpImplementation.h +++ b/mlir/include/mlir/IR/OpImplementation.h @@ -555,7 +555,7 @@ public: ParseResult parseInteger(IntT &result) { auto loc = getCurrentLocation(); OptionalParseResult parseResult = parseOptionalInteger(result); - if (!parseResult.hasValue()) + if (!parseResult.has_value()) return emitError(loc, "expected integer value"); return *parseResult; } @@ -570,7 +570,7 @@ public: // Parse the unsigned variant. APInt uintResult; OptionalParseResult parseResult = parseOptionalInteger(uintResult); - if (!parseResult.hasValue() || failed(*parseResult)) + if (!parseResult.has_value() || failed(*parseResult)) return parseResult; // Try to convert to the provided integer type. sextOrTrunc is correct even @@ -817,7 +817,7 @@ public: StringRef attrName, NamedAttrList &attrs) { OptionalParseResult parseResult = parseOptionalAttribute(result, type); - if (parseResult.hasValue() && succeeded(*parseResult)) + if (parseResult.has_value() && succeeded(*parseResult)) attrs.append(attrName, result); return parseResult; } @@ -1299,9 +1299,9 @@ public: ParseResult parseAssignmentList(SmallVectorImpl<Argument> &lhs, SmallVectorImpl<UnresolvedOperand> &rhs) { OptionalParseResult result = parseOptionalAssignmentList(lhs, rhs); - if (!result.hasValue()) + if (!result.has_value()) return emitError(getCurrentLocation(), "expected '('"); - return result.getValue(); + return result.value(); } virtual OptionalParseResult diff --git a/mlir/include/mlir/Support/LogicalResult.h b/mlir/include/mlir/Support/LogicalResult.h index 2940828..b2cf736 100644 --- a/mlir/include/mlir/Support/LogicalResult.h +++ b/mlir/include/mlir/Support/LogicalResult.h @@ -90,12 +90,12 @@ public: FailureOr(const FailureOr<U> &other) : Optional<T>(failed(other) ? Optional<T>() : Optional<T>(*other)) {} - operator LogicalResult() const { return success(this->hasValue()); } + operator LogicalResult() const { return success(this->has_value()); } private: /// Hide the bool conversion as it easily creates confusion. using Optional<T>::operator bool; - using Optional<T>::hasValue; + using Optional<T>::has_value; }; /// This class represents success/failure for parsing-like operations that find diff --git a/mlir/include/mlir/TableGen/Operator.h b/mlir/include/mlir/TableGen/Operator.h index 6bac850..ab03a1a 100644 --- a/mlir/include/mlir/TableGen/Operator.h +++ b/mlir/include/mlir/TableGen/Operator.h @@ -263,12 +263,12 @@ public: explicit ArgOrType(TypeConstraint constraint) : index(None), constraint(constraint) {} bool isArg() const { - assert(constraint.hasValue() ^ index.hasValue()); - return index.hasValue(); + assert(constraint.has_value() ^ index.has_value()); + return index.has_value(); } bool isType() const { - assert(constraint.hasValue() ^ index.hasValue()); - return constraint.hasValue(); + assert(constraint.has_value() ^ index.has_value()); + return constraint.has_value(); } int getArg() const { return *index; } diff --git a/mlir/include/mlir/Transforms/DialectConversion.h b/mlir/include/mlir/Transforms/DialectConversion.h index feac434..678bf02 100644 --- a/mlir/include/mlir/Transforms/DialectConversion.h +++ b/mlir/include/mlir/Transforms/DialectConversion.h @@ -251,9 +251,9 @@ private: [callback = std::forward<FnT>(callback)]( T type, SmallVectorImpl<Type> &results, ArrayRef<Type>) { if (Optional<Type> resultOpt = callback(type)) { - bool wasSuccess = static_cast<bool>(resultOpt.getValue()); + bool wasSuccess = static_cast<bool>(resultOpt.value()); if (wasSuccess) - results.push_back(resultOpt.getValue()); + results.push_back(resultOpt.value()); return Optional<LogicalResult>(success(wasSuccess)); } return Optional<LogicalResult>(); diff --git a/mlir/lib/Analysis/Presburger/IntegerRelation.cpp b/mlir/lib/Analysis/Presburger/IntegerRelation.cpp index 7376747..baeb467 100644 --- a/mlir/lib/Analysis/Presburger/IntegerRelation.cpp +++ b/mlir/lib/Analysis/Presburger/IntegerRelation.cpp @@ -2015,14 +2015,14 @@ IntegerRelation::unionBoundingBox(const IntegerRelation &otherCst) { int64_t lbFloorDivisor, otherLbFloorDivisor; for (unsigned d = 0, e = getNumDimIds(); d < e; ++d) { auto extent = getConstantBoundOnDimSize(d, &lb, &lbFloorDivisor, &ub); - if (!extent.hasValue()) + if (!extent.has_value()) // TODO: symbolic extents when necessary. // TODO: handle union if a dimension is unbounded. return failure(); auto otherExtent = otherCst.getConstantBoundOnDimSize( d, &otherLb, &otherLbFloorDivisor, &otherUb); - if (!otherExtent.hasValue() || lbFloorDivisor != otherLbFloorDivisor) + if (!otherExtent.has_value() || lbFloorDivisor != otherLbFloorDivisor) // TODO: symbolic extents when necessary. return failure(); @@ -2043,10 +2043,10 @@ IntegerRelation::unionBoundingBox(const IntegerRelation &otherCst) { // Uncomparable - check for constant lower/upper bounds. auto constLb = getConstantBound(BoundType::LB, d); auto constOtherLb = otherCst.getConstantBound(BoundType::LB, d); - if (!constLb.hasValue() || !constOtherLb.hasValue()) + if (!constLb.has_value() || !constOtherLb.has_value()) return failure(); std::fill(minLb.begin(), minLb.end(), 0); - minLb.back() = std::min(constLb.getValue(), constOtherLb.getValue()); + minLb.back() = std::min(*constLb, constOtherLb.value()); } // Do the same for ub's but max of upper bounds. Identify max. @@ -2059,10 +2059,10 @@ IntegerRelation::unionBoundingBox(const IntegerRelation &otherCst) { // Uncomparable - check for constant lower/upper bounds. auto constUb = getConstantBound(BoundType::UB, d); auto constOtherUb = otherCst.getConstantBound(BoundType::UB, d); - if (!constUb.hasValue() || !constOtherUb.hasValue()) + if (!constUb.has_value() || !constOtherUb.has_value()) return failure(); std::fill(maxUb.begin(), maxUb.end(), 0); - maxUb.back() = std::max(constUb.getValue(), constOtherUb.getValue()); + maxUb.back() = std::max(*constUb, constOtherUb.value()); } std::fill(newLb.begin(), newLb.end(), 0); diff --git a/mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp b/mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp index 6e0f007..3d2dae5 100644 --- a/mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp +++ b/mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp @@ -645,8 +645,8 @@ public: ModuleOp module = op->getParentOfType<ModuleOp>(); IntegerAttr executionModeAttr = op.execution_modeAttr(); std::string moduleName; - if (module.getName().hasValue()) - moduleName = "_" + module.getName().getValue().str(); + if (module.getName().has_value()) + moduleName = "_" + module.getName()->str(); else moduleName = ""; std::string executionModeInfoName = @@ -1585,10 +1585,10 @@ void mlir::encodeBindAttribute(ModuleOp module) { if (descriptorSet && binding) { // Encode these numbers into the variable's symbolic name. If the // SPIR-V module has a name, add it at the beginning. - auto moduleAndName = spvModule.getName().hasValue() - ? spvModule.getName().getValue().str() + "_" + - op.sym_name().str() - : op.sym_name().str(); + auto moduleAndName = + spvModule.getName().has_value() + ? spvModule.getName()->str() + "_" + op.sym_name().str() + : op.sym_name().str(); std::string name = llvm::formatv("{0}_descriptor_set{1}_binding{2}", moduleAndName, std::to_string(descriptorSet.getInt()), diff --git a/mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp b/mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp index 133a363..c7917a4 100644 --- a/mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp +++ b/mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp @@ -147,8 +147,8 @@ createLinalgBodyCalculationForElementwiseOp(Operation *op, ValueRange args, cast<tosa::NegateOp>(op).quantization_info()) { auto quantizationInfo = cast<tosa::NegateOp>(op).quantization_info(); int32_t inputBitWidth = elementTy.getIntOrFloatBitWidth(); - int64_t inZp = quantizationInfo.getValue().getInputZp(); - int64_t outZp = quantizationInfo.getValue().getOutputZp(); + int64_t inZp = quantizationInfo->getInputZp(); + int64_t outZp = quantizationInfo->getOutputZp(); // Compute the maximum value that can occur in the intermediate buffer. int64_t zpAdd = inZp + outZp; @@ -1153,9 +1153,9 @@ public: auto dynamicDimsOr = checkHasDynamicBatchDims(rewriter, op, {input, op.output()}); - if (!dynamicDimsOr.hasValue()) + if (!dynamicDimsOr.has_value()) return failure(); - SmallVector<Value> dynamicDims = dynamicDimsOr.getValue(); + SmallVector<Value> dynamicDims = dynamicDimsOr.value(); // The shift and multiplier values. SmallVector<int32_t> multiplierValues; @@ -1345,9 +1345,9 @@ public: auto dynamicDimsOr = checkHasDynamicBatchDims(rewriter, op, {input, op.output()}); - if (!dynamicDimsOr.hasValue()) + if (!dynamicDimsOr.has_value()) return failure(); - SmallVector<Value> dynamicDims = dynamicDimsOr.getValue(); + SmallVector<Value> dynamicDims = dynamicDimsOr.value(); if (op.mode() != "NEAREST_NEIGHBOR" && op.mode() != "BILINEAR") return failure(); @@ -2040,9 +2040,9 @@ public: auto dynamicDimsOr = checkHasDynamicBatchDims(rewriter, op, {input, indices, op.output()}); - if (!dynamicDimsOr.hasValue()) + if (!dynamicDimsOr.has_value()) return failure(); - SmallVector<Value> dynamicDims = dynamicDimsOr.getValue(); + SmallVector<Value> dynamicDims = dynamicDimsOr.value(); auto resultElementTy = resultTy.getElementType(); diff --git a/mlir/lib/Conversion/TosaToLinalg/TosaToLinalgNamed.cpp b/mlir/lib/Conversion/TosaToLinalg/TosaToLinalgNamed.cpp index 866fea8..531824c 100644 --- a/mlir/lib/Conversion/TosaToLinalg/TosaToLinalgNamed.cpp +++ b/mlir/lib/Conversion/TosaToLinalg/TosaToLinalgNamed.cpp @@ -694,9 +694,9 @@ public: auto dynamicDimsOr = checkHasDynamicBatchDims(rewriter, op, {input, op.output()}); - if (!dynamicDimsOr.hasValue()) + if (!dynamicDimsOr.has_value()) return failure(); - SmallVector<Value> dynamicDims = dynamicDimsOr.getValue(); + SmallVector<Value> dynamicDims = dynamicDimsOr.value(); // Determine what the initial value needs to be for the max pool op. Attribute initialAttr; @@ -771,9 +771,9 @@ public: auto dynamicDimsOr = checkHasDynamicBatchDims(rewriter, op, {input, op.output()}); - if (!dynamicDimsOr.hasValue()) + if (!dynamicDimsOr.has_value()) return failure(); - SmallVector<Value> dynamicDims = dynamicDimsOr.getValue(); + SmallVector<Value> dynamicDims = dynamicDimsOr.value(); // Apply padding as necessary. llvm::SmallVector<int64_t> pad; diff --git a/mlir/lib/Conversion/VectorToSCF/VectorToSCF.cpp b/mlir/lib/Conversion/VectorToSCF/VectorToSCF.cpp index 9ead9e2..2356136 100644 --- a/mlir/lib/Conversion/VectorToSCF/VectorToSCF.cpp +++ b/mlir/lib/Conversion/VectorToSCF/VectorToSCF.cpp @@ -90,12 +90,12 @@ static void getXferIndices(OpBuilder &b, OpTy xferOp, Value iv, indices.append(prevIndices.begin(), prevIndices.end()); Location loc = xferOp.getLoc(); - bool isBroadcast = !dim.hasValue(); + bool isBroadcast = !dim.has_value(); if (!isBroadcast) { AffineExpr d0, d1; bindDims(xferOp.getContext(), d0, d1); - Value offset = adaptor.getIndices()[dim.getValue()]; - indices[dim.getValue()] = + Value offset = adaptor.getIndices()[dim.value()]; + indices[dim.value()] = makeComposedAffineApply(b, loc, d0 + d1, {offset, iv}); } } diff --git a/mlir/lib/Dialect/Affine/Analysis/AffineStructures.cpp b/mlir/lib/Dialect/Affine/Analysis/AffineStructures.cpp index e1e6621..1ce9c3c 100644 --- a/mlir/lib/Dialect/Affine/Analysis/AffineStructures.cpp +++ b/mlir/lib/Dialect/Affine/Analysis/AffineStructures.cpp @@ -322,7 +322,7 @@ unsigned FlatAffineValueConstraints::insertId(IdKind kind, unsigned pos, bool FlatAffineValueConstraints::hasValues() const { return llvm::find_if(values, [](Optional<Value> id) { - return id.hasValue(); + return id.has_value(); }) != values.end(); } @@ -401,11 +401,11 @@ static void mergeAndAlignIds(unsigned offset, FlatAffineValueConstraints *a, assert(std::all_of(a->getMaybeValues().begin() + offset, a->getMaybeValues().end(), - [](Optional<Value> id) { return id.hasValue(); })); + [](Optional<Value> id) { return id.has_value(); })); assert(std::all_of(b->getMaybeValues().begin() + offset, b->getMaybeValues().end(), - [](Optional<Value> id) { return id.hasValue(); })); + [](Optional<Value> id) { return id.has_value(); })); SmallVector<Value, 4> aDimValues; a->getValues(offset, a->getNumDimIds(), &aDimValues); @@ -1008,18 +1008,18 @@ void FlatAffineValueConstraints::getSliceBounds( auto lbConst = getConstantBound(BoundType::LB, pos); auto ubConst = getConstantBound(BoundType::UB, pos); - if (lbConst.hasValue() && ubConst.hasValue()) { + if (lbConst.has_value() && ubConst.has_value()) { // Detect equality to a constant. - if (lbConst.getValue() == ubConst.getValue()) { - memo[pos] = getAffineConstantExpr(lbConst.getValue(), context); + if (lbConst.value() == ubConst.value()) { + memo[pos] = getAffineConstantExpr(*lbConst, context); changed = true; continue; } // Detect an identifier as modulo of another identifier w.r.t a // constant. - if (detectAsMod(*this, pos, lbConst.getValue(), ubConst.getValue(), - memo, context)) { + if (detectAsMod(*this, pos, lbConst.value(), ubConst.value(), memo, + context)) { changed = true; continue; } @@ -1119,21 +1119,19 @@ void FlatAffineValueConstraints::getSliceBounds( LLVM_DEBUG(llvm::dbgs() << "WARNING: Potentially over-approximating slice lb\n"); auto lbConst = getConstantBound(BoundType::LB, pos + offset); - if (lbConst.hasValue()) { - lbMap = AffineMap::get( - numMapDims, numMapSymbols, - getAffineConstantExpr(lbConst.getValue(), context)); + if (lbConst) { + lbMap = AffineMap::get(numMapDims, numMapSymbols, + getAffineConstantExpr(*lbConst, context)); } } if (!ubMap || ubMap.getNumResults() > 1) { LLVM_DEBUG(llvm::dbgs() << "WARNING: Potentially over-approximating slice ub\n"); auto ubConst = getConstantBound(BoundType::UB, pos + offset); - if (ubConst.hasValue()) { - ubMap = - AffineMap::get(numMapDims, numMapSymbols, - getAffineConstantExpr( - ubConst.getValue() + ubAdjustment, context)); + if (ubConst) { + ubMap = AffineMap::get( + numMapDims, numMapSymbols, + getAffineConstantExpr(ubConst.value() + ubAdjustment, context)); } } } @@ -1671,13 +1669,13 @@ void FlatAffineRelation::compose(const FlatAffineRelation &other) { // Add and match domain of `rel` to domain of `this`. for (unsigned i = 0, e = rel.getNumDomainDims(); i < e; ++i) - if (relMaybeValues[i].hasValue()) - setValue(i, relMaybeValues[i].getValue()); + if (relMaybeValues[i].has_value()) + setValue(i, relMaybeValues[i].value()); // Add and match range of `this` to range of `rel`. for (unsigned i = 0, e = getNumRangeDims(); i < e; ++i) { unsigned rangeIdx = rel.getNumDomainDims() + i; - if (thisMaybeValues[rangeIdx].hasValue()) - rel.setValue(rangeIdx, thisMaybeValues[rangeIdx].getValue()); + if (thisMaybeValues[rangeIdx].has_value()) + rel.setValue(rangeIdx, thisMaybeValues[rangeIdx].value()); } // Append `this` to `rel` and simplify constraints. diff --git a/mlir/lib/Dialect/Affine/Analysis/LoopAnalysis.cpp b/mlir/lib/Dialect/Affine/Analysis/LoopAnalysis.cpp index 0620a59..f8c43e7 100644 --- a/mlir/lib/Dialect/Affine/Analysis/LoopAnalysis.cpp +++ b/mlir/lib/Dialect/Affine/Analysis/LoopAnalysis.cpp @@ -92,9 +92,9 @@ Optional<uint64_t> mlir::getConstantTripCount(AffineForOp forOp) { Optional<uint64_t> tripCount; for (auto resultExpr : map.getResults()) { if (auto constExpr = resultExpr.dyn_cast<AffineConstantExpr>()) { - if (tripCount.hasValue()) - tripCount = std::min(tripCount.getValue(), - static_cast<uint64_t>(constExpr.getValue())); + if (tripCount) + tripCount = + std::min(*tripCount, static_cast<uint64_t>(constExpr.getValue())); else tripCount = constExpr.getValue(); } else @@ -132,13 +132,13 @@ uint64_t mlir::getLargestDivisorOfTripCount(AffineForOp forOp) { // Trip count is not a known constant; return its largest known divisor. thisGcd = resultExpr.getLargestKnownDivisor(); } - if (gcd.hasValue()) - gcd = llvm::GreatestCommonDivisor64(gcd.getValue(), thisGcd); + if (gcd) + gcd = llvm::GreatestCommonDivisor64(*gcd, thisGcd); else gcd = thisGcd; } - assert(gcd.hasValue() && "value expected per above logic"); - return gcd.getValue(); + assert(gcd.has_value() && "value expected per above logic"); + return gcd.value(); } /// Given an induction variable `iv` of type AffineForOp and an access `index` diff --git a/mlir/lib/Dialect/Affine/Analysis/Utils.cpp b/mlir/lib/Dialect/Affine/Analysis/Utils.cpp index 6a9a0388..5015706 100644 --- a/mlir/lib/Dialect/Affine/Analysis/Utils.cpp +++ b/mlir/lib/Dialect/Affine/Analysis/Utils.cpp @@ -375,8 +375,8 @@ Optional<int64_t> MemRefRegion::getConstantBoundingSizeAndShape( SmallVector<int64_t, 4> lb; Optional<int64_t> diff = cstWithShapeBounds.getConstantBoundOnDimSize(d, &lb, &lbDivisor); - if (diff.hasValue()) { - diffConstant = diff.getValue(); + if (diff) { + diffConstant = diff.value(); assert(diffConstant >= 0 && "Dim size bound can't be negative"); assert(lbDivisor > 0); } else { @@ -1012,17 +1012,17 @@ bool mlir::buildSliceTripCountMap( continue; } Optional<uint64_t> maybeConstTripCount = getConstantTripCount(forOp); - if (maybeConstTripCount.hasValue()) { - (*tripCountMap)[op] = maybeConstTripCount.getValue(); + if (maybeConstTripCount) { + (*tripCountMap)[op] = maybeConstTripCount.value(); continue; } return false; } Optional<uint64_t> tripCount = getConstDifference(lbMap, ubMap); // Slice bounds are created with a constant ub - lb difference. - if (!tripCount.hasValue()) + if (!tripCount.has_value()) return false; - (*tripCountMap)[op] = tripCount.getValue(); + (*tripCountMap)[op] = tripCount.value(); } return true; } @@ -1320,9 +1320,9 @@ static Optional<int64_t> getMemoryFootprintBytes(Block &block, int64_t totalSizeInBytes = 0; for (const auto ®ion : regions) { Optional<int64_t> size = region.second->getRegionSize(); - if (!size.hasValue()) + if (!size.has_value()) return None; - totalSizeInBytes += size.getValue(); + totalSizeInBytes += size.value(); } return totalSizeInBytes; } diff --git a/mlir/lib/Dialect/Affine/IR/AffineOps.cpp b/mlir/lib/Dialect/Affine/IR/AffineOps.cpp index 01f651d..6a6827c 100644 --- a/mlir/lib/Dialect/Affine/IR/AffineOps.cpp +++ b/mlir/lib/Dialect/Affine/IR/AffineOps.cpp @@ -336,9 +336,8 @@ static bool isDimOpValidSymbol(OpTy dimOp, Region *region) { // The dim op is also okay if its operand memref is a view/subview whose // corresponding size is a valid symbol. Optional<int64_t> index = dimOp.getConstantIndex(); - assert(index.hasValue() && - "expect only `dim` operations with a constant index"); - int64_t i = index.getValue(); + assert(index && "expect only `dim` operations with a constant index"); + int64_t i = *index; return TypeSwitch<Operation *, bool>(dimOp.source().getDefiningOp()) .Case<memref::ViewOp, memref::SubViewOp, memref::AllocOp>( [&](auto op) { return isMemRefSizeValidSymbol(op, i, region); }) @@ -1713,12 +1712,12 @@ struct AffineForEmptyLoopFolder : public OpRewritePattern<AffineForOp> { } // Bail out when the trip count is unknown and the loop returns any value // defined outside of the loop or any iterArg out of order. - if (!tripCount.hasValue() && + if (!tripCount.has_value() && (hasValDefinedOutsideLoop || iterArgsNotInOrder)) return failure(); // Bail out when the loop iterates more than once and it returns any iterArg // out of order. - if (tripCount.hasValue() && tripCount.getValue() >= 2 && iterArgsNotInOrder) + if (tripCount.has_value() && *tripCount >= 2 && iterArgsNotInOrder) return failure(); rewriter.replaceOp(forOp, replacements); return success(); @@ -1751,19 +1750,18 @@ OperandRange AffineForOp::getSuccessorEntryOperands(Optional<unsigned> index) { void AffineForOp::getSuccessorRegions( Optional<unsigned> index, ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> ®ions) { - assert((!index.hasValue() || index.getValue() == 0) && - "expected loop region"); + assert((!index || *index == 0) && "expected loop region"); // The loop may typically branch back to its body or to the parent operation. // If the predecessor is the parent op and the trip count is known to be at // least one, branch into the body using the iterator arguments. And in cases // we know the trip count is zero, it can only branch back to its parent. Optional<uint64_t> tripCount = getTrivialConstantTripCount(*this); - if (!index.hasValue() && tripCount.hasValue()) { - if (tripCount.getValue() > 0) { + if (!index && tripCount) { + if (tripCount.value() > 0) { regions.push_back(RegionSuccessor(&getLoopBody(), getRegionIterArgs())); return; } - if (tripCount.getValue() == 0) { + if (tripCount.value() == 0) { regions.push_back(RegionSuccessor(getResults())); return; } @@ -3590,8 +3588,8 @@ ParseResult AffineParallelOp::parse(OpAsmParser &parser, arith::symbolizeAtomicRMWKind(attrVal.getValue()); if (!reduction) return parser.emitError(loc, "invalid reduction value: ") << attrVal; - reductions.push_back(builder.getI64IntegerAttr( - static_cast<int64_t>(reduction.getValue()))); + reductions.push_back( + builder.getI64IntegerAttr(static_cast<int64_t>(reduction.value()))); // While we keep getting commas, keep parsing. return success(); }; diff --git a/mlir/lib/Dialect/Affine/Transforms/AffineDataCopyGeneration.cpp b/mlir/lib/Dialect/Affine/Transforms/AffineDataCopyGeneration.cpp index 864f109..18a10c4 100644 --- a/mlir/lib/Dialect/Affine/Transforms/AffineDataCopyGeneration.cpp +++ b/mlir/lib/Dialect/Affine/Transforms/AffineDataCopyGeneration.cpp @@ -142,9 +142,8 @@ void AffineDataCopyGeneration::runOnBlock(Block *block, Optional<int64_t> footprint = getMemoryFootprintBytes(forOp, /*memorySpace=*/0); - return (footprint.hasValue() && - static_cast<uint64_t>(footprint.getValue()) > - fastMemCapacityBytes); + return (footprint && + static_cast<uint64_t>(*footprint) > fastMemCapacityBytes); }; // If the memory footprint of the 'affine.for' loop is higher than fast diff --git a/mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp b/mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp index b77ef90..f686620 100644 --- a/mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp +++ b/mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp @@ -441,15 +441,15 @@ public: ++pos; } - if (firstSrcDepPos.hasValue()) { - if (lastDstDepPos.hasValue()) { - if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) { + if (firstSrcDepPos) { + if (lastDstDepPos) { + if (firstSrcDepPos.value() <= lastDstDepPos.value()) { // No valid insertion point exists which preserves dependences. return nullptr; } } // Return the insertion point at 'firstSrcDepPos'. - return depInsts[firstSrcDepPos.getValue()]; + return depInsts[firstSrcDepPos.value()]; } // No dependence targets in range (or only dst deps in range), return // 'dstNodInst' insertion point. @@ -942,10 +942,10 @@ static Value createPrivateMemRef(AffineForOp forOp, Operation *srcStoreOpInst, // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed // by 'srcStoreOpInst'. uint64_t bufSize = - getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue(); + getMemRefEltSizeInBytes(oldMemRefType) * numElements.value(); unsigned newMemSpace; - if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) { - newMemSpace = fastMemorySpace.getValue(); + if (bufSize <= localBufSizeThreshold && fastMemorySpace.has_value()) { + newMemSpace = fastMemorySpace.value(); } else { newMemSpace = oldMemRefType.getMemorySpaceAsInt(); } @@ -1141,9 +1141,9 @@ static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst, Optional<int64_t> maybeSrcWriteRegionSizeBytes = srcWriteRegion.getRegionSize(); - if (!maybeSrcWriteRegionSizeBytes.hasValue()) + if (!maybeSrcWriteRegionSizeBytes.has_value()) return false; - int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue(); + int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.value(); // Compute op instance count for the src loop nest. uint64_t dstLoopNestCost = getComputeCost(dstForOp, dstLoopNestStats); @@ -1183,15 +1183,14 @@ static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst, Optional<int64_t> maybeSliceWriteRegionSizeBytes = sliceWriteRegion.getRegionSize(); - if (!maybeSliceWriteRegionSizeBytes.hasValue() || - maybeSliceWriteRegionSizeBytes.getValue() == 0) { + if (!maybeSliceWriteRegionSizeBytes.has_value() || + *maybeSliceWriteRegionSizeBytes == 0) { LLVM_DEBUG(llvm::dbgs() << "Failed to get slice write region size at loopDepth: " << i << "\n"); continue; } - int64_t sliceWriteRegionSizeBytes = - maybeSliceWriteRegionSizeBytes.getValue(); + int64_t sliceWriteRegionSizeBytes = maybeSliceWriteRegionSizeBytes.value(); // If we are fusing for reuse, check that write regions remain the same. // TODO: Write region check should check sizes and offsets in @@ -1268,11 +1267,11 @@ static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst, return false; } - auto srcMemSizeVal = srcMemSize.getValue(); - auto dstMemSizeVal = dstMemSize.getValue(); + auto srcMemSizeVal = srcMemSize.value(); + auto dstMemSizeVal = dstMemSize.value(); assert(sliceMemEstimate && "expected value"); - auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue(); + auto fusedMem = dstMemSizeVal + sliceMemEstimate.value(); LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n" << " dst mem: " << dstMemSizeVal << "\n" diff --git a/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp b/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp index 09f11eb..04586c9 100644 --- a/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp +++ b/mlir/lib/Dialect/Affine/Utils/LoopUtils.cpp @@ -405,13 +405,13 @@ checkTilingLegalityImpl(MutableArrayRef<mlir::AffineForOp> origLoops) { LLVM_DEBUG(dstAccess.opInst->dump();); for (unsigned k = 0, e = depComps.size(); k < e; k++) { DependenceComponent depComp = depComps[k]; - if (depComp.lb.hasValue() && depComp.ub.hasValue() && - depComp.lb.getValue() < depComp.ub.getValue() && - depComp.ub.getValue() < 0) { + if (depComp.lb.has_value() && depComp.ub.has_value() && + depComp.lb.value() < depComp.ub.value() && + depComp.ub.value() < 0) { LLVM_DEBUG(llvm::dbgs() << "Dependence component lb = " - << Twine(depComp.lb.getValue()) - << " ub = " << Twine(depComp.ub.getValue()) + << Twine(depComp.lb.value()) + << " ub = " << Twine(depComp.ub.value()) << " is negative at depth: " << Twine(d) << " and thus violates the legality rule.\n"); return false; @@ -802,11 +802,11 @@ constructTiledIndexSetHyperRect(MutableArrayRef<AffineForOp> origLoops, newLoops[width + i].setStep(origLoops[i].getStep()); // Set the upper bound. - if (mayBeConstantCount && mayBeConstantCount.getValue() < tileSizes[i]) { + if (mayBeConstantCount && *mayBeConstantCount < tileSizes[i]) { // Trip count is less than the tile size: upper bound is lower bound + // trip count * stepSize. - AffineMap ubMap = b.getSingleDimShiftAffineMap( - mayBeConstantCount.getValue() * origLoops[i].getStep()); + AffineMap ubMap = b.getSingleDimShiftAffineMap(*mayBeConstantCount * + origLoops[i].getStep()); newLoops[width + i].setUpperBound( /*operands=*/newLoops[i].getInductionVar(), ubMap); } else if (largestDiv % tileSizes[i] != 0) { @@ -974,8 +974,8 @@ void mlir::getTileableBands(func::FuncOp f, /// Unrolls this loop completely. LogicalResult mlir::loopUnrollFull(AffineForOp forOp) { Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp); - if (mayBeConstantTripCount.hasValue()) { - uint64_t tripCount = mayBeConstantTripCount.getValue(); + if (mayBeConstantTripCount) { + uint64_t tripCount = mayBeConstantTripCount.value(); if (tripCount == 0) return success(); if (tripCount == 1) @@ -990,9 +990,8 @@ LogicalResult mlir::loopUnrollFull(AffineForOp forOp) { LogicalResult mlir::loopUnrollUpToFactor(AffineForOp forOp, uint64_t unrollFactor) { Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp); - if (mayBeConstantTripCount.hasValue() && - mayBeConstantTripCount.getValue() < unrollFactor) - return loopUnrollByFactor(forOp, mayBeConstantTripCount.getValue()); + if (mayBeConstantTripCount && *mayBeConstantTripCount < unrollFactor) + return loopUnrollByFactor(forOp, mayBeConstantTripCount.value()); return loopUnrollByFactor(forOp, unrollFactor); } @@ -1150,9 +1149,8 @@ LogicalResult mlir::loopUnrollByFactor( LogicalResult mlir::loopUnrollJamUpToFactor(AffineForOp forOp, uint64_t unrollJamFactor) { Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp); - if (mayBeConstantTripCount.hasValue() && - mayBeConstantTripCount.getValue() < unrollJamFactor) - return loopUnrollJamByFactor(forOp, mayBeConstantTripCount.getValue()); + if (mayBeConstantTripCount && *mayBeConstantTripCount < unrollJamFactor) + return loopUnrollJamByFactor(forOp, mayBeConstantTripCount.value()); return loopUnrollJamByFactor(forOp, unrollJamFactor); } @@ -1573,8 +1571,8 @@ AffineForOp mlir::sinkSequentialLoops(AffineForOp forOp) { assert(depComps.size() >= maxLoopDepth); for (unsigned j = 0; j < maxLoopDepth; ++j) { DependenceComponent &depComp = depComps[j]; - assert(depComp.lb.hasValue() && depComp.ub.hasValue()); - if (depComp.lb.getValue() != 0 || depComp.ub.getValue() != 0) + assert(depComp.lb.has_value() && depComp.ub.has_value()); + if (depComp.lb.value() != 0 || depComp.ub.value() != 0) isParallelLoop[j] = false; } } @@ -2406,12 +2404,12 @@ LogicalResult mlir::affineDataCopyGenerate(Block::iterator begin, block->walk(begin, end, [&](Operation *opInst) { // Gather regions to allocate to buffers in faster memory space. if (auto loadOp = dyn_cast<AffineLoadOp>(opInst)) { - if ((filterMemRef.hasValue() && filterMemRef != loadOp.getMemRef()) || + if ((filterMemRef.has_value() && filterMemRef != loadOp.getMemRef()) || (loadOp.getMemRefType().getMemorySpaceAsInt() != copyOptions.slowMemorySpace)) return; } else if (auto storeOp = dyn_cast<AffineStoreOp>(opInst)) { - if ((filterMemRef.hasValue() && filterMemRef != storeOp.getMemRef()) || + if ((filterMemRef.has_value() && filterMemRef != storeOp.getMemRef()) || storeOp.getMemRefType().getMemorySpaceAsInt() != copyOptions.slowMemorySpace) return; diff --git a/mlir/lib/Dialect/Affine/Utils/Utils.cpp b/mlir/lib/Dialect/Affine/Utils/Utils.cpp index 5f9eee5..5cfebeb 100644 --- a/mlir/lib/Dialect/Affine/Utils/Utils.cpp +++ b/mlir/lib/Dialect/Affine/Utils/Utils.cpp @@ -1792,11 +1792,11 @@ MemRefType mlir::normalizeMemRefType(MemRefType memrefType, OpBuilder b, // For a static memref and an affine map with no symbols, this is // always bounded. assert(ubConst && "should always have an upper bound"); - if (ubConst.getValue() < 0) + if (ubConst.value() < 0) // This is due to an invalid map that maps to a negative space. return memrefType; // If dimension of new memrefType is dynamic, the value is -1. - newShape[d] = ubConst.getValue() + 1; + newShape[d] = *ubConst + 1; } } diff --git a/mlir/lib/Dialect/Arithmetic/Transforms/UnsignedWhenEquivalent.cpp b/mlir/lib/Dialect/Arithmetic/Transforms/UnsignedWhenEquivalent.cpp index f84990d..f4e0415 100644 --- a/mlir/lib/Dialect/Arithmetic/Transforms/UnsignedWhenEquivalent.cpp +++ b/mlir/lib/Dialect/Arithmetic/Transforms/UnsignedWhenEquivalent.cpp @@ -23,9 +23,9 @@ using namespace mlir::arith; static LogicalResult staticallyNonNegative(IntRangeAnalysis &analysis, Value v) { Optional<ConstantIntRanges> result = analysis.getResult(v); - if (!result.hasValue()) + if (!result.has_value()) return failure(); - const ConstantIntRanges &range = result.getValue(); + const ConstantIntRanges &range = result.value(); return success(range.smin().isNonNegative()); } diff --git a/mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp b/mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp index 37ff8e9..20273c6 100644 --- a/mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp +++ b/mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp @@ -444,11 +444,11 @@ struct SimplifyClones : public OpRewritePattern<CloneOp> { llvm::Optional<Operation *> maybeCloneDeallocOp = memref::findDealloc(cloneOp.getOutput()); // Skip if either of them has > 1 deallocate operations. - if (!maybeCloneDeallocOp.hasValue()) + if (!maybeCloneDeallocOp.has_value()) return failure(); llvm::Optional<Operation *> maybeSourceDeallocOp = memref::findDealloc(source); - if (!maybeSourceDeallocOp.hasValue()) + if (!maybeSourceDeallocOp.has_value()) return failure(); Operation *cloneDeallocOp = *maybeCloneDeallocOp; Operation *sourceDeallocOp = *maybeSourceDeallocOp; diff --git a/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp b/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp index d631dc3..7240e5b 100644 --- a/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp +++ b/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp @@ -158,11 +158,11 @@ bufferization::getGlobalFor(arith::ConstantOp constantOp, uint64_t alignment) { auto globalOp = dyn_cast<memref::GlobalOp>(&op); if (!globalOp) continue; - if (!globalOp.initial_value().hasValue()) + if (!globalOp.initial_value().has_value()) continue; uint64_t opAlignment = - globalOp.alignment().hasValue() ? globalOp.alignment().getValue() : 0; - Attribute initialValue = globalOp.initial_value().getValue(); + globalOp.alignment().has_value() ? globalOp.alignment().value() : 0; + Attribute initialValue = globalOp.initial_value().value(); if (opAlignment == alignment && initialValue == constantOp.getValue()) return globalOp; } diff --git a/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp b/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp index 3689522..1cff6f9 100644 --- a/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp +++ b/mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp @@ -114,9 +114,9 @@ static FuncOpAnalysisState getFuncOpAnalysisState(const AnalysisState &state, Optional<const FuncAnalysisState *> maybeState = state.getDialectState<FuncAnalysisState>( func::FuncDialect::getDialectNamespace()); - if (!maybeState.hasValue()) + if (!maybeState.has_value()) return FuncOpAnalysisState::NotAnalyzed; - const auto &analyzedFuncOps = maybeState.getValue()->analyzedFuncOps; + const auto &analyzedFuncOps = maybeState.value()->analyzedFuncOps; auto it = analyzedFuncOps.find(funcOp); if (it == analyzedFuncOps.end()) return FuncOpAnalysisState::NotAnalyzed; diff --git a/mlir/lib/Dialect/DLTI/DLTI.cpp b/mlir/lib/Dialect/DLTI/DLTI.cpp index 046152a..eaf6f1e6 100644 --- a/mlir/lib/Dialect/DLTI/DLTI.cpp +++ b/mlir/lib/Dialect/DLTI/DLTI.cpp @@ -73,11 +73,11 @@ DataLayoutEntryAttr DataLayoutEntryAttr::parse(AsmParser &parser) { std::string identifier; SMLoc idLoc = parser.getCurrentLocation(); OptionalParseResult parsedType = parser.parseOptionalType(type); - if (parsedType.hasValue() && failed(parsedType.getValue())) + if (parsedType.has_value() && failed(parsedType.value())) return {}; - if (!parsedType.hasValue()) { + if (!parsedType.has_value()) { OptionalParseResult parsedString = parser.parseOptionalString(&identifier); - if (!parsedString.hasValue() || failed(parsedString.getValue())) { + if (!parsedString.has_value() || failed(parsedString.value())) { parser.emitError(idLoc) << "expected a type or a quoted string"; return {}; } diff --git a/mlir/lib/Dialect/EmitC/IR/EmitC.cpp b/mlir/lib/Dialect/EmitC/IR/EmitC.cpp index be6dd41..f2a19cd 100644 --- a/mlir/lib/Dialect/EmitC/IR/EmitC.cpp +++ b/mlir/lib/Dialect/EmitC/IR/EmitC.cpp @@ -151,7 +151,7 @@ ParseResult IncludeOp::parse(OpAsmParser &parser, OperationState &result) { StringAttr include; OptionalParseResult includeParseResult = parser.parseOptionalAttribute(include, "include", result.attributes); - if (!includeParseResult.hasValue()) + if (!includeParseResult.has_value()) return parser.emitError(parser.getNameLoc()) << "expected string attribute"; if (standardInclude && parser.parseOptionalGreater()) diff --git a/mlir/lib/Dialect/GPU/Transforms/SerializeToBlob.cpp b/mlir/lib/Dialect/GPU/Transforms/SerializeToBlob.cpp index 35bf594..29f2448 100644 --- a/mlir/lib/Dialect/GPU/Transforms/SerializeToBlob.cpp +++ b/mlir/lib/Dialect/GPU/Transforms/SerializeToBlob.cpp @@ -75,10 +75,10 @@ void gpu::SerializeToBlobPass::runOnOperation() { Optional<std::string> maybeTargetISA = translateToISA(*llvmModule, *targetMachine); - if (!maybeTargetISA.hasValue()) + if (!maybeTargetISA.has_value()) return signalPassFailure(); - std::string targetISA = std::move(maybeTargetISA.getValue()); + std::string targetISA = std::move(maybeTargetISA.value()); LLVM_DEBUG({ llvm::dbgs() << "ISA for module: " << getOperation().getNameAttr() << "\n"; diff --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp index 63a89d5..0cc2fca 100644 --- a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp +++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp @@ -237,9 +237,8 @@ ParseResult AllocaOp::parse(OpAsmParser &parser, OperationState &result) { Optional<NamedAttribute> alignmentAttr = result.attributes.getNamed("alignment"); - if (alignmentAttr.hasValue()) { - auto alignmentInt = - alignmentAttr.getValue().getValue().dyn_cast<IntegerAttr>(); + if (alignmentAttr.has_value()) { + auto alignmentInt = alignmentAttr->getValue().dyn_cast<IntegerAttr>(); if (!alignmentInt) return parser.emitError(parser.getNameLoc(), "expected integer alignment"); @@ -272,11 +271,11 @@ ParseResult AllocaOp::parse(OpAsmParser &parser, OperationState &result) { /// the attribute, but not both. static LogicalResult verifyOpaquePtr(Operation *op, LLVMPointerType ptrType, Optional<Type> ptrElementType) { - if (ptrType.isOpaque() && !ptrElementType.hasValue()) { + if (ptrType.isOpaque() && !ptrElementType.has_value()) { return op->emitOpError() << "expected '" << kElemTypeAttrName << "' attribute if opaque pointer type is used"; } - if (!ptrType.isOpaque() && ptrElementType.hasValue()) { + if (!ptrType.isOpaque() && ptrElementType.has_value()) { return op->emitOpError() << "unexpected '" << kElemTypeAttrName << "' attribute when non-opaque pointer type is used"; @@ -341,10 +340,10 @@ static ParseResult parseSwitchOpCases( do { int64_t value = 0; OptionalParseResult integerParseResult = parser.parseOptionalInteger(value); - if (values.empty() && !integerParseResult.hasValue()) + if (values.empty() && !integerParseResult.has_value()) return success(); - if (!integerParseResult.hasValue() || integerParseResult.getValue()) + if (!integerParseResult.has_value() || integerParseResult.value()) return failure(); values.push_back(APInt(bitWidth, value)); @@ -617,8 +616,8 @@ parseGEPIndices(OpAsmParser &parser, int32_t constantIndex; OptionalParseResult parsedInteger = parser.parseOptionalInteger(constantIndex); - if (parsedInteger.hasValue()) { - if (failed(parsedInteger.getValue())) + if (parsedInteger.has_value()) { + if (failed(parsedInteger.value())) return failure(); constantIndices.push_back(constantIndex); return success(); @@ -916,13 +915,13 @@ LogicalResult InvokeOp::verify() { void InvokeOp::print(OpAsmPrinter &p) { auto callee = getCallee(); - bool isDirect = callee.hasValue(); + bool isDirect = callee.has_value(); p << ' '; // Either function name or pointer if (isDirect) - p.printSymbolName(callee.getValue()); + p.printSymbolName(callee.value()); else p << getOperand(0); @@ -1209,13 +1208,13 @@ LogicalResult CallOp::verify() { void CallOp::print(OpAsmPrinter &p) { auto callee = getCallee(); - bool isDirect = callee.hasValue(); + bool isDirect = callee.has_value(); // Print the direct callee if present as a function attribute, or an indirect // callee (first operand) otherwise. p << ' '; if (isDirect) - p.printSymbolName(callee.getValue()); + p.printSymbolName(callee.value()); else p << getOperand(0); @@ -1927,7 +1926,7 @@ ParseResult GlobalOp::parse(OpAsmParser &parser, OperationState &result) { OptionalParseResult parseResult = parser.parseOptionalRegion(initRegion, /*arguments=*/{}, /*argTypes=*/{}); - if (parseResult.hasValue() && failed(*parseResult)) + if (parseResult.has_value() && failed(*parseResult)) return failure(); } @@ -1987,8 +1986,8 @@ LogicalResult GlobalOp::verify() { } Optional<uint64_t> alignAttr = getAlignment(); - if (alignAttr.hasValue()) { - uint64_t value = alignAttr.getValue(); + if (alignAttr.has_value()) { + uint64_t value = alignAttr.value(); if (!llvm::isPowerOf2_64(value)) return emitError() << "alignment attribute is not a power of 2"; } @@ -2261,7 +2260,7 @@ ParseResult LLVMFuncOp::parse(OpAsmParser &parser, OperationState &result) { auto *body = result.addRegion(); OptionalParseResult parseResult = parser.parseOptionalRegion(*body, entryArgs); - return failure(parseResult.hasValue() && failed(*parseResult)); + return failure(parseResult.has_value() && failed(*parseResult)); } // Print the LLVMFuncOp. Collects argument and result types and passes them to diff --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMTypeSyntax.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMTypeSyntax.cpp index 04015ef..295f59f 100644 --- a/mlir/lib/Dialect/LLVMIR/IR/LLVMTypeSyntax.cpp +++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMTypeSyntax.cpp @@ -232,7 +232,7 @@ static LLVMPointerType parsePointerType(AsmParser &parser) { unsigned addressSpace = 0; OptionalParseResult opr = parser.parseOptionalInteger(addressSpace); - if (opr.hasValue()) { + if (opr.has_value()) { if (failed(*opr) || parser.parseGreater()) return LLVMPointerType(); return parser.getChecked<LLVMPointerType>(loc, parser.getContext(), @@ -442,8 +442,8 @@ static Type dispatchParse(AsmParser &parser, bool allowAny = true) { // Try parsing any MLIR type. Type type; OptionalParseResult result = parser.parseOptionalType(type); - if (result.hasValue()) { - if (failed(result.getValue())) + if (result.has_value()) { + if (failed(result.value())) return nullptr; if (!allowAny) { parser.emitError(keyLoc) << "unexpected type, expected keyword"; diff --git a/mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp b/mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp index 7d4691a..d5d84bd 100644 --- a/mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp +++ b/mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp @@ -117,15 +117,15 @@ static bool isIntegerPtxType(MMATypes type) { MMATypes MmaOp::accumPtxType() { Optional<mlir::NVVM::MMATypes> val = inferOperandMMAType( getODSOperands(2).getTypes().front(), /*isAccum=*/true); - assert(val.hasValue() && "accumulator PTX type should always be inferrable"); - return val.getValue(); + assert(val && "accumulator PTX type should always be inferrable"); + return val.value(); } MMATypes MmaOp::resultPtxType() { Optional<mlir::NVVM::MMATypes> val = inferOperandMMAType(getResult().getType(), /*isAccum=*/true); - assert(val.hasValue() && "result PTX type should always be inferrable"); - return val.getValue(); + assert(val && "result PTX type should always be inferrable"); + return val.value(); } void MmaOp::print(OpAsmPrinter &p) { @@ -224,10 +224,10 @@ void MmaOp::build(OpBuilder &builder, OperationState &result, Type resultType, result.addAttribute("layoutB", MMALayoutAttr::get(ctx, MMALayout::col)); } - if (intOverflow.hasValue()) + if (intOverflow) result.addAttribute("intOverflowBehavior", MMAIntOverflowAttr::get(ctx, *intOverflow)); - if (b1Op.hasValue()) + if (b1Op) result.addAttribute("b1Op", MMAB1OpAttr::get(ctx, *b1Op)); result.addTypes(resultType); @@ -311,13 +311,13 @@ ParseResult MmaOp::parse(OpAsmParser &parser, OperationState &result) { for (unsigned idx = 0; idx < names.size(); idx++) { const auto &frag = frags[idx]; Optional<NamedAttribute> attr = namedAttributes.getNamed(names[idx]); - if (!frag.elemtype.hasValue() && !attr.hasValue()) { + if (!frag.elemtype.has_value() && !attr) { return parser.emitError( parser.getNameLoc(), "attribute " + names[idx] + " is not provided explicitly and cannot be inferred"); } - if (!attr.hasValue()) + if (!attr) result.addAttribute( names[idx], MMATypesAttr::get(parser.getContext(), *frag.elemtype)); } @@ -399,10 +399,10 @@ LogicalResult MmaOp::verify() { break; default: return emitError("invalid shape or multiplicand type: " + - stringifyEnum(getMultiplicandAPtxType().getValue())); + stringifyEnum(getMultiplicandAPtxType().value())); } - if (isIntegerPtxType(getMultiplicandAPtxType().getValue())) { + if (isIntegerPtxType(getMultiplicandAPtxType().value())) { expectedResult.push_back(s32x4StructTy); expectedC.emplace_back(4, i32Ty); multiplicandFragType = i32Ty; @@ -440,16 +440,16 @@ LogicalResult MmaOp::verify() { context, SmallVector<Type>(2, f64Ty))); allowedShapes.push_back({8, 8, 4}); } - if (isIntegerPtxType(getMultiplicandAPtxType().getValue())) { + if (isIntegerPtxType(getMultiplicandAPtxType().value())) { expectedA.push_back({i32Ty}); expectedB.push_back({i32Ty}); expectedC.push_back({i32Ty, i32Ty}); expectedResult.push_back(s32x2StructTy); - if (isInt4PtxType(getMultiplicandAPtxType().getValue())) + if (isInt4PtxType(getMultiplicandAPtxType().value())) allowedShapes.push_back({8, 8, 32}); - if (isInt8PtxType(getMultiplicandAPtxType().getValue())) + if (isInt8PtxType(getMultiplicandAPtxType().value())) allowedShapes.push_back({8, 8, 16}); - if (getMultiplicandAPtxType().getValue() == MMATypes::b1) + if (getMultiplicandAPtxType().value() == MMATypes::b1) allowedShapes.push_back({8, 8, 128}); } } diff --git a/mlir/lib/Dialect/Linalg/Transforms/Fusion.cpp b/mlir/lib/Dialect/Linalg/Transforms/Fusion.cpp index 2b783a8..8bff2c2 100644 --- a/mlir/lib/Dialect/Linalg/Transforms/Fusion.cpp +++ b/mlir/lib/Dialect/Linalg/Transforms/Fusion.cpp @@ -777,16 +777,14 @@ fuseOperations(OpBuilder &b, LinalgOp rootOp, TiledLinalgOp tiledLinalgOp, LinalgDependenceGraph::DependenceType::RAW) continue; - unsigned resultIndex = - dependence.getDependentOpViewResultNum().getValue(); + unsigned resultIndex = dependence.getDependentOpViewResultNum().value(); LinalgOp consumer = origOpToFusedOp.lookup(dependence.getIndexingOp()); if (!consumer) continue; Value replacementValue = fusedOp.getOperation()->getResult(resultIndex); consumer.getOperation()->setOperand( - dependence.getIndexingOpViewOperandNum().getValue(), - replacementValue); + dependence.getIndexingOpViewOperandNum().value(), replacementValue); } // At this point, all Linalg uses of the tensors produced by `origOp` have diff --git a/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp b/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp index 1f2ca25..88d986b 100644 --- a/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp +++ b/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp @@ -49,8 +49,8 @@ static Value allocBuffer(ImplicitLocOpBuilder &b, auto width = layout.getTypeSize(elementType); IntegerAttr alignmentAttr; - if (alignment.hasValue()) - alignmentAttr = b.getI64IntegerAttr(alignment.getValue()); + if (alignment) + alignmentAttr = b.getI64IntegerAttr(alignment.value()); // Static buffer. if (auto cst = allocSize.getDefiningOp<arith::ConstantIndexOp>()) { @@ -233,7 +233,7 @@ FailureOr<PromotionInfo> mlir::linalg::promoteSubviewAsNewBuffer( Value size = failed(upperBound) ? rangeValue.size - : b.create<arith::ConstantIndexOp>(loc, upperBound.getValue()); + : b.create<arith::ConstantIndexOp>(loc, upperBound.value()); LLVM_DEBUG(llvm::dbgs() << "Extracted tightest: " << size << "\n"); fullSizes.push_back(size); partialSizes.push_back( diff --git a/mlir/lib/Dialect/Linalg/Transforms/Transforms.cpp b/mlir/lib/Dialect/Linalg/Transforms/Transforms.cpp index a3b95b3..67ca94b9 100644 --- a/mlir/lib/Dialect/Linalg/Transforms/Transforms.cpp +++ b/mlir/lib/Dialect/Linalg/Transforms/Transforms.cpp @@ -102,9 +102,8 @@ LogicalResult mlir::linalg::LinalgTransformationFilter::checkAndNotify( void mlir::linalg::LinalgTransformationFilter:: replaceLinalgTransformationFilter(PatternRewriter &rewriter, Operation *op) const { - if (replacement.hasValue()) - op->setAttr(LinalgTransforms::kLinalgTransformMarker, - replacement.getValue()); + if (replacement) + op->setAttr(LinalgTransforms::kLinalgTransformMarker, replacement.value()); else op->removeAttr( rewriter.getStringAttr(LinalgTransforms::kLinalgTransformMarker)); @@ -441,10 +440,10 @@ LogicalResult mlir::linalg::LinalgBaseTileAndFusePattern::matchAndRewrite( if (failed(unfusedTiledOp)) return failure(); rewriter.replaceOp(tiledAndFusedOps->op, - getTiledOpResult(unfusedTiledOp.getValue())); + getTiledOpResult(unfusedTiledOp.value())); tiledAndFusedOps->op = unfusedTiledOp->op; } - op->replaceAllUsesWith(getTiledAndFusedOpResult(tiledAndFusedOps.getValue())); + op->replaceAllUsesWith(getTiledAndFusedOpResult(tiledAndFusedOps.value())); filter.replaceLinalgTransformationFilter(rewriter, tiledAndFusedOps->op.getOperation()); diff --git a/mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp b/mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp index 014c5be..85351c5 100644 --- a/mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp +++ b/mlir/lib/Dialect/MemRef/IR/MemRefOps.cpp @@ -1297,8 +1297,8 @@ LogicalResult GlobalOp::verify() { // Verify that the initial value, if present, is either a unit attribute or // an elements attribute. - if (initial_value().hasValue()) { - Attribute initValue = initial_value().getValue(); + if (initial_value().has_value()) { + Attribute initValue = initial_value().value(); if (!initValue.isa<UnitAttr>() && !initValue.isa<ElementsAttr>()) return emitOpError("initial value should be a unit or elements " "attribute, but got ") @@ -1329,8 +1329,8 @@ LogicalResult GlobalOp::verify() { ElementsAttr GlobalOp::getConstantInitValue() { auto initVal = initial_value(); - if (constant() && initVal.hasValue()) - return initVal.getValue().cast<ElementsAttr>(); + if (constant() && initVal.has_value()) + return initVal->cast<ElementsAttr>(); return {}; } @@ -2483,14 +2483,14 @@ static bool isTrivialSubViewOp(SubViewOp subViewOp) { // Check offsets are zero. if (llvm::any_of(mixedOffsets, [](OpFoldResult ofr) { Optional<int64_t> intValue = getConstantIntValue(ofr); - return !intValue || intValue.getValue() != 0; + return !intValue || *intValue != 0; })) return false; // Check strides are one. if (llvm::any_of(mixedStrides, [](OpFoldResult ofr) { Optional<int64_t> intValue = getConstantIntValue(ofr); - return !intValue || intValue.getValue() != 1; + return !intValue || *intValue != 1; })) return false; diff --git a/mlir/lib/Dialect/OpenACC/IR/OpenACC.cpp b/mlir/lib/Dialect/OpenACC/IR/OpenACC.cpp index ec1b6e9..b2960a6 100644 --- a/mlir/lib/Dialect/OpenACC/IR/OpenACC.cpp +++ b/mlir/lib/Dialect/OpenACC/IR/OpenACC.cpp @@ -243,7 +243,7 @@ ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &result) { // async()? async = parseOptionalOperandAndType(parser, ParallelOp::getAsyncKeyword(), result); - if (async.hasValue() && failed(*async)) + if (async.has_value() && failed(*async)) return failure(); // wait()? @@ -254,19 +254,19 @@ ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &result) { // num_gangs(value)? numGangs = parseOptionalOperandAndType( parser, ParallelOp::getNumGangsKeyword(), result); - if (numGangs.hasValue() && failed(*numGangs)) + if (numGangs.has_value() && failed(*numGangs)) return failure(); // num_workers(value)? numWorkers = parseOptionalOperandAndType( parser, ParallelOp::getNumWorkersKeyword(), result); - if (numWorkers.hasValue() && failed(*numWorkers)) + if (numWorkers.has_value() && failed(*numWorkers)) return failure(); // vector_length(value)? vectorLength = parseOptionalOperandAndType( parser, ParallelOp::getVectorLengthKeyword(), result); - if (vectorLength.hasValue() && failed(*vectorLength)) + if (vectorLength.has_value() && failed(*vectorLength)) return failure(); // if()? @@ -362,11 +362,11 @@ ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &result) { result.addAttribute( ParallelOp::getOperandSegmentSizeAttr(), builder.getI32VectorAttr( - {static_cast<int32_t>(async.hasValue() ? 1 : 0), + {static_cast<int32_t>(async.has_value() ? 1 : 0), static_cast<int32_t>(waitOperands.size()), - static_cast<int32_t>(numGangs.hasValue() ? 1 : 0), - static_cast<int32_t>(numWorkers.hasValue() ? 1 : 0), - static_cast<int32_t>(vectorLength.hasValue() ? 1 : 0), + static_cast<int32_t>(numGangs.has_value() ? 1 : 0), + static_cast<int32_t>(numWorkers.has_value() ? 1 : 0), + static_cast<int32_t>(vectorLength.has_value() ? 1 : 0), static_cast<int32_t>(hasIfCond ? 1 : 0), static_cast<int32_t>(hasSelfCond ? 1 : 0), static_cast<int32_t>(reductionOperands.size()), @@ -531,13 +531,13 @@ ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &result) { if (succeeded(parser.parseOptionalLParen())) { gangNum = parserOptionalOperandAndTypeWithPrefix( parser, result, LoopOp::getGangNumKeyword()); - if (gangNum.hasValue() && failed(*gangNum)) + if (gangNum.has_value() && failed(*gangNum)) return failure(); // FIXME: Comma should require subsequent operands. (void)parser.parseOptionalComma(); gangStatic = parserOptionalOperandAndTypeWithPrefix( parser, result, LoopOp::getGangStaticKeyword()); - if (gangStatic.hasValue() && failed(*gangStatic)) + if (gangStatic.has_value() && failed(*gangStatic)) return failure(); // FIXME: Why allow optional last commas? (void)parser.parseOptionalComma(); @@ -551,7 +551,7 @@ ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &result) { // optional worker operand worker = parseOptionalOperandAndType(parser, result); - if (worker.hasValue() && failed(*worker)) + if (worker.has_value() && failed(*worker)) return failure(); // vector? @@ -560,7 +560,7 @@ ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &result) { // optional vector operand vector = parseOptionalOperandAndType(parser, result); - if (vector.hasValue() && failed(*vector)) + if (vector.has_value() && failed(*vector)) return failure(); // tile()? @@ -591,10 +591,10 @@ ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &result) { result.addAttribute(LoopOp::getOperandSegmentSizeAttr(), builder.getI32VectorAttr( - {static_cast<int32_t>(gangNum.hasValue() ? 1 : 0), - static_cast<int32_t>(gangStatic.hasValue() ? 1 : 0), - static_cast<int32_t>(worker.hasValue() ? 1 : 0), - static_cast<int32_t>(vector.hasValue() ? 1 : 0), + {static_cast<int32_t>(gangNum.has_value() ? 1 : 0), + static_cast<int32_t>(gangStatic.has_value() ? 1 : 0), + static_cast<int32_t>(worker.has_value() ? 1 : 0), + static_cast<int32_t>(vector.has_value() ? 1 : 0), static_cast<int32_t>(tileOperands.size()), static_cast<int32_t>(privateOperands.size()), static_cast<int32_t>(reductionOperands.size())})); diff --git a/mlir/lib/Dialect/PDL/IR/PDLTypes.cpp b/mlir/lib/Dialect/PDL/IR/PDLTypes.cpp index 13e19d4..f3b1923 100644 --- a/mlir/lib/Dialect/PDL/IR/PDLTypes.cpp +++ b/mlir/lib/Dialect/PDL/IR/PDLTypes.cpp @@ -40,7 +40,7 @@ static Type parsePDLType(AsmParser &parser) { { Type genType; auto parseResult = generatedTypeParser(parser, typeTag, genType); - if (parseResult.hasValue()) + if (parseResult.has_value()) return genType; } diff --git a/mlir/lib/Dialect/Quant/IR/TypeParser.cpp b/mlir/lib/Dialect/Quant/IR/TypeParser.cpp index 951f62a..91e7ec7 100644 --- a/mlir/lib/Dialect/Quant/IR/TypeParser.cpp +++ b/mlir/lib/Dialect/Quant/IR/TypeParser.cpp @@ -30,7 +30,7 @@ static IntegerType parseStorageType(DialectAsmParser &parser, bool &isSigned) { StringRef identifier; unsigned storageTypeWidth = 0; OptionalParseResult result = parser.parseOptionalType(type); - if (result.hasValue()) { + if (result.has_value()) { if (!succeeded(*result)) return nullptr; isSigned = !type.isUnsigned(); diff --git a/mlir/lib/Dialect/SCF/IR/SCF.cpp b/mlir/lib/Dialect/SCF/IR/SCF.cpp index 293238e..503c36d 100644 --- a/mlir/lib/Dialect/SCF/IR/SCF.cpp +++ b/mlir/lib/Dialect/SCF/IR/SCF.cpp @@ -2711,7 +2711,7 @@ ParseResult scf::WhileOp::parse(OpAsmParser &parser, OperationState &result) { OptionalParseResult listResult = parser.parseOptionalAssignmentList(regionArgs, operands); - if (listResult.hasValue() && failed(listResult.getValue())) + if (listResult.has_value() && failed(listResult.value())) return failure(); FunctionType functionType; diff --git a/mlir/lib/Dialect/SCF/Transforms/TileUsingInterface.cpp b/mlir/lib/Dialect/SCF/Transforms/TileUsingInterface.cpp index 1bad67f..63d34e4 100644 --- a/mlir/lib/Dialect/SCF/Transforms/TileUsingInterface.cpp +++ b/mlir/lib/Dialect/SCF/Transforms/TileUsingInterface.cpp @@ -340,11 +340,11 @@ scf::TileConsumerAndFuseProducersUsingSCFForOp::returningMatchAndRewrite( // 2c. Generate the tiled implementation of the producer of the source rewriter.setInsertionPoint(candidateSliceOp); FailureOr<Value> fusedProducerValue = - tensor::replaceExtractSliceWithTiledProducer( - rewriter, candidateSliceOp, fusableProducer.getValue()); + tensor::replaceExtractSliceWithTiledProducer(rewriter, candidateSliceOp, + fusableProducer.value()); if (failed(fusedProducerValue)) continue; - rewriter.replaceOp(candidateSliceOp, fusedProducerValue.getValue()); + rewriter.replaceOp(candidateSliceOp, fusedProducerValue.value()); // 2d. The operands of the fused producer might themselved be slices of // values produced by operations that implement the `TilingInterface`. diff --git a/mlir/lib/Dialect/SCF/Utils/AffineCanonicalizationUtils.cpp b/mlir/lib/Dialect/SCF/Utils/AffineCanonicalizationUtils.cpp index 958b5a2..024731a 100644 --- a/mlir/lib/Dialect/SCF/Utils/AffineCanonicalizationUtils.cpp +++ b/mlir/lib/Dialect/SCF/Utils/AffineCanonicalizationUtils.cpp @@ -27,9 +27,8 @@ using namespace presburger; static void unpackOptionalValues(ArrayRef<Optional<Value>> source, SmallVector<Value> &target) { - target = llvm::to_vector<4>(llvm::map_range(source, [](Optional<Value> val) { - return val.hasValue() ? *val : Value(); - })); + target = llvm::to_vector<4>(llvm::map_range( + source, [](Optional<Value> val) { return val ? *val : Value(); })); } /// Bound an identifier `pos` in a given FlatAffineValueConstraints with diff --git a/mlir/lib/Dialect/SPIRV/IR/SPIRVAttributes.cpp b/mlir/lib/Dialect/SPIRV/IR/SPIRVAttributes.cpp index 4accfc1..7b7ff84 100644 --- a/mlir/lib/Dialect/SPIRV/IR/SPIRVAttributes.cpp +++ b/mlir/lib/Dialect/SPIRV/IR/SPIRVAttributes.cpp @@ -387,7 +387,7 @@ static Attribute parseInterfaceVarABIAttr(DialectAsmParser &parser) { uint32_t descriptorSet = 0; auto descriptorSetParseResult = parser.parseOptionalInteger(descriptorSet); - if (!descriptorSetParseResult.hasValue() || + if (!descriptorSetParseResult.has_value() || failed(*descriptorSetParseResult)) { parser.emitError(loc, "missing descriptor set"); return {}; @@ -404,7 +404,7 @@ static Attribute parseInterfaceVarABIAttr(DialectAsmParser &parser) { uint32_t binding = 0; auto bindingParseResult = parser.parseOptionalInteger(binding); - if (!bindingParseResult.hasValue() || failed(*bindingParseResult)) { + if (!bindingParseResult.has_value() || failed(*bindingParseResult)) { parser.emitError(loc, "missing binding"); return {}; } @@ -583,8 +583,8 @@ Attribute SPIRVDialect::parseAttribute(DialectAsmParser &parser, Attribute attr; OptionalParseResult result = generatedAttributeParser(parser, attrKind, type, attr); - if (result.hasValue()) { - if (failed(result.getValue())) + if (result.has_value()) { + if (failed(result.value())) return {}; return attr; } diff --git a/mlir/lib/Dialect/SPIRV/IR/SPIRVCanonicalization.cpp b/mlir/lib/Dialect/SPIRV/IR/SPIRVCanonicalization.cpp index aaa0fb3..9ca9c15 100644 --- a/mlir/lib/Dialect/SPIRV/IR/SPIRVCanonicalization.cpp +++ b/mlir/lib/Dialect/SPIRV/IR/SPIRVCanonicalization.cpp @@ -216,11 +216,11 @@ OpFoldResult spirv::LogicalAndOp::fold(ArrayRef<Attribute> operands) { if (Optional<bool> rhs = getScalarOrSplatBoolAttr(operands.back())) { // x && true = x - if (rhs.getValue()) + if (rhs.value()) return operand1(); // x && false = false - if (!rhs.getValue()) + if (!rhs.value()) return operands.back(); } @@ -247,12 +247,12 @@ OpFoldResult spirv::LogicalOrOp::fold(ArrayRef<Attribute> operands) { assert(operands.size() == 2 && "spv.LogicalOr should take two operands"); if (auto rhs = getScalarOrSplatBoolAttr(operands.back())) { - if (rhs.getValue()) + if (rhs.value()) // x || true = true return operands.back(); // x || false = x - if (!rhs.getValue()) + if (!rhs.value()) return operand1(); } diff --git a/mlir/lib/Dialect/SPIRV/IR/SPIRVDialect.cpp b/mlir/lib/Dialect/SPIRV/IR/SPIRVDialect.cpp index ee717d2..dff5971 100644 --- a/mlir/lib/Dialect/SPIRV/IR/SPIRVDialect.cpp +++ b/mlir/lib/Dialect/SPIRV/IR/SPIRVDialect.cpp @@ -496,8 +496,8 @@ template <typename ParseType, typename... Args> struct ParseCommaSeparatedList { auto remainingValues = ParseCommaSeparatedList<Args...>{}(dialect, parser); if (!remainingValues) return llvm::None; - return std::tuple_cat(std::tuple<ParseType>(parseVal.getValue()), - remainingValues.getValue()); + return std::tuple_cat(std::tuple<ParseType>(parseVal.value()), + remainingValues.value()); } }; @@ -571,7 +571,7 @@ static ParseResult parseStructMemberDecorations( SMLoc offsetLoc = parser.getCurrentLocation(); StructType::OffsetInfo offset = 0; OptionalParseResult offsetParseResult = parser.parseOptionalInteger(offset); - if (offsetParseResult.hasValue()) { + if (offsetParseResult.has_value()) { if (failed(*offsetParseResult)) return failure(); @@ -588,7 +588,7 @@ static ParseResult parseStructMemberDecorations( return success(); // If there was an offset, make sure to parse the comma. - if (offsetParseResult.hasValue() && parser.parseComma()) + if (offsetParseResult.has_value() && parser.parseComma()) return failure(); // Check for spirv::Decorations. @@ -607,11 +607,11 @@ static ParseResult parseStructMemberDecorations( memberDecorationInfo.emplace_back( static_cast<uint32_t>(memberTypes.size() - 1), 1, - memberDecoration.getValue(), memberDecorationValue.getValue()); + memberDecoration.value(), memberDecorationValue.value()); } else { memberDecorationInfo.emplace_back( static_cast<uint32_t>(memberTypes.size() - 1), 0, - memberDecoration.getValue(), 0); + memberDecoration.value(), 0); } return success(); }; diff --git a/mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp b/mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp index 4e7338f..4af79a1 100644 --- a/mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp +++ b/mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp @@ -2236,7 +2236,7 @@ ParseResult spirv::FuncOp::parse(OpAsmParser &parser, OperationState &state) { // Parse the optional function body. auto *body = state.addRegion(); OptionalParseResult result = parser.parseOptionalRegion(*body, entryArgs); - return failure(result.hasValue() && failed(*result)); + return failure(result.has_value() && failed(*result)); } void spirv::FuncOp::print(OpAsmPrinter &printer) { diff --git a/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp b/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp index 3ea2224..263f00e 100644 --- a/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp +++ b/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp @@ -131,8 +131,8 @@ static LogicalResult lowerEntryPointABIAttr(spirv::FuncOp funcOp, return funcOp.emitRemark("lower entry point failure: could not select " "execution model based on 'spv.target_env'"); - builder.create<spirv::EntryPointOp>( - funcOp.getLoc(), executionModel.getValue(), funcOp, interfaceVars); + builder.create<spirv::EntryPointOp>(funcOp.getLoc(), executionModel.value(), + funcOp, interfaceVars); // Specifies the spv.ExecutionModeOp. auto localSizeAttr = entryPointAttr.getLocalSize(); diff --git a/mlir/lib/Dialect/Shape/IR/Shape.cpp b/mlir/lib/Dialect/Shape/IR/Shape.cpp index b3f6c4c..6fd8fa6 100644 --- a/mlir/lib/Dialect/Shape/IR/Shape.cpp +++ b/mlir/lib/Dialect/Shape/IR/Shape.cpp @@ -1247,11 +1247,11 @@ OpFoldResult GetExtentOp::fold(ArrayRef<Attribute> operands) { if (!elements) return nullptr; Optional<int64_t> dim = getConstantDim(); - if (!dim.hasValue()) + if (!dim.has_value()) return nullptr; - if (dim.getValue() >= elements.getNumElements()) + if (dim.value() >= elements.getNumElements()) return nullptr; - return elements.getValues<Attribute>()[(uint64_t)dim.getValue()]; + return elements.getValues<Attribute>()[(uint64_t)dim.value()]; } void GetExtentOp::build(OpBuilder &builder, OperationState &result, Value shape, diff --git a/mlir/lib/Dialect/SparseTensor/Transforms/Sparsification.cpp b/mlir/lib/Dialect/SparseTensor/Transforms/Sparsification.cpp index 8c62290..0504ea0 100644 --- a/mlir/lib/Dialect/SparseTensor/Transforms/Sparsification.cpp +++ b/mlir/lib/Dialect/SparseTensor/Transforms/Sparsification.cpp @@ -1729,9 +1729,9 @@ public: // Builds the tensor expression for the Linalg operation in SSA form. Optional<unsigned> optExp = merger.buildTensorExpFromLinalg(op); - if (!optExp.hasValue()) + if (!optExp.has_value()) return failure(); - unsigned exp = optExp.getValue(); + unsigned exp = optExp.value(); // Rejects an inadmissable tensor expression. OpOperand *sparseOut = nullptr; diff --git a/mlir/lib/Dialect/SparseTensor/Utils/Merger.cpp b/mlir/lib/Dialect/SparseTensor/Utils/Merger.cpp index ed19cf7..9482e71 100644 --- a/mlir/lib/Dialect/SparseTensor/Utils/Merger.cpp +++ b/mlir/lib/Dialect/SparseTensor/Utils/Merger.cpp @@ -893,8 +893,8 @@ Optional<unsigned> Merger::buildTensorExp(linalg::GenericOp op, Value v) { // Construct unary operations if subexpression can be built. if (def->getNumOperands() == 1) { auto x = buildTensorExp(op, def->getOperand(0)); - if (x.hasValue()) { - unsigned e = x.getValue(); + if (x) { + unsigned e = x.value(); if (isa<math::AbsOp>(def)) return addExp(kAbsF, e); if (isa<complex::AbsOp>(def)) @@ -966,9 +966,9 @@ Optional<unsigned> Merger::buildTensorExp(linalg::GenericOp op, Value v) { if (def->getNumOperands() == 2) { auto x = buildTensorExp(op, def->getOperand(0)); auto y = buildTensorExp(op, def->getOperand(1)); - if (x.hasValue() && y.hasValue()) { - unsigned e0 = x.getValue(); - unsigned e1 = y.getValue(); + if (x.has_value() && y.has_value()) { + unsigned e0 = x.value(); + unsigned e1 = y.value(); if (isa<arith::MulFOp>(def)) return addExp(kMulF, e0, e1); if (isa<complex::MulOp>(def)) diff --git a/mlir/lib/Dialect/Tensor/Transforms/SwapExtractSliceWithProducer.cpp b/mlir/lib/Dialect/Tensor/Transforms/SwapExtractSliceWithProducer.cpp index 8d570cf..8798164 100644 --- a/mlir/lib/Dialect/Tensor/Transforms/SwapExtractSliceWithProducer.cpp +++ b/mlir/lib/Dialect/Tensor/Transforms/SwapExtractSliceWithProducer.cpp @@ -39,5 +39,5 @@ FailureOr<Value> tensor::replaceExtractSliceWithTiledProducer( if (failed(tiledResult)) return failure(); - return tiledResult.getValue(); + return tiledResult.value(); } diff --git a/mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeTransposeConv.cpp b/mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeTransposeConv.cpp index 120e502..a0a9262 100644 --- a/mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeTransposeConv.cpp +++ b/mlir/lib/Dialect/Tosa/Transforms/TosaDecomposeTransposeConv.cpp @@ -208,8 +208,8 @@ public: Value weightPaddingVal = createOpAndInfer<tosa::ConstOp>( rewriter, loc, weightPaddingAttr.getType(), weightPaddingAttr); - if (op.quantization_info().hasValue()) { - auto quantInfo = op.quantization_info().getValue(); + if (op.quantization_info().has_value()) { + auto quantInfo = op.quantization_info().value(); weight = createOpAndInfer<tosa::PadOp>( rewriter, loc, UnrankedTensorType::get(weightETy), weight, weightPaddingVal, nullptr, @@ -272,8 +272,8 @@ public: Value inputPaddingVal = createOpAndInfer<tosa::ConstOp>( rewriter, loc, inputPaddingAttr.getType(), inputPaddingAttr); - if (op.quantization_info().hasValue()) { - auto quantInfo = op.quantization_info().getValue(); + if (op.quantization_info().has_value()) { + auto quantInfo = op.quantization_info().value(); input = createOpAndInfer<tosa::PadOp>( rewriter, loc, UnrankedTensorType::get(inputETy), input, inputPaddingVal, nullptr, diff --git a/mlir/lib/Dialect/Transform/IR/TransformOps.cpp b/mlir/lib/Dialect/Transform/IR/TransformOps.cpp index d83a9de..23e7b5d 100644 --- a/mlir/lib/Dialect/Transform/IR/TransformOps.cpp +++ b/mlir/lib/Dialect/Transform/IR/TransformOps.cpp @@ -134,12 +134,12 @@ void transform::AlternativesOp::getSuccessorRegions( Optional<unsigned> index, ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> ®ions) { for (Region &alternative : - llvm::drop_begin(getAlternatives(), index.hasValue() ? *index + 1 : 0)) { + llvm::drop_begin(getAlternatives(), index ? *index + 1 : 0)) { regions.emplace_back(&alternative, !getOperands().empty() ? alternative.getArguments() : Block::BlockArgListType()); } - if (index.hasValue()) + if (index) regions.emplace_back(getOperation()->getResults()); } diff --git a/mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp b/mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp index 64937be..b26b3d9 100644 --- a/mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp +++ b/mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp @@ -238,7 +238,7 @@ LogicalResult mlir::reshapeLikeShapesAreCompatible( return emitError("invalid to have a single dimension (" + Twine(map.index()) + ") expanded into multiple dynamic dims (" + - Twine(expandedDimStart + dynamicShape.getValue()) + + Twine(expandedDimStart + dynamicShape.value()) + "," + Twine(expandedDimStart + dim.index()) + ")"); } dynamicShape = dim.index(); diff --git a/mlir/lib/Dialect/Vector/IR/VectorOps.cpp b/mlir/lib/Dialect/Vector/IR/VectorOps.cpp index ebf3662..387e5f1 100644 --- a/mlir/lib/Dialect/Vector/IR/VectorOps.cpp +++ b/mlir/lib/Dialect/Vector/IR/VectorOps.cpp @@ -2677,8 +2677,8 @@ void TransferReadOp::build(OpBuilder &builder, OperationState &result, ValueRange indices, AffineMap permutationMap, Optional<ArrayRef<bool>> inBounds) { auto permutationMapAttr = AffineMapAttr::get(permutationMap); - auto inBoundsAttr = (inBounds && !inBounds.getValue().empty()) - ? builder.getBoolArrayAttr(inBounds.getValue()) + auto inBoundsAttr = (inBounds && !inBounds->empty()) + ? builder.getBoolArrayAttr(inBounds.value()) : ArrayAttr(); build(builder, result, vectorType, source, indices, permutationMapAttr, inBoundsAttr); @@ -2692,8 +2692,8 @@ void TransferReadOp::build(OpBuilder &builder, OperationState &result, AffineMap permutationMap = getTransferMinorIdentityMap( source.getType().cast<ShapedType>(), vectorType); auto permutationMapAttr = AffineMapAttr::get(permutationMap); - auto inBoundsAttr = (inBounds && !inBounds.getValue().empty()) - ? builder.getBoolArrayAttr(inBounds.getValue()) + auto inBoundsAttr = (inBounds && !inBounds->empty()) + ? builder.getBoolArrayAttr(inBounds.value()) : ArrayAttr(); build(builder, result, vectorType, source, indices, permutationMapAttr, padding, @@ -3216,8 +3216,8 @@ void TransferWriteOp::build(OpBuilder &builder, OperationState &result, AffineMap permutationMap, Optional<ArrayRef<bool>> inBounds) { auto permutationMapAttr = AffineMapAttr::get(permutationMap); - auto inBoundsAttr = (inBounds && !inBounds.getValue().empty()) - ? builder.getBoolArrayAttr(inBounds.getValue()) + auto inBoundsAttr = (inBounds && !inBounds->empty()) + ? builder.getBoolArrayAttr(inBounds.value()) : ArrayAttr(); build(builder, result, vector, dest, indices, permutationMapAttr, /*mask=*/Value(), inBoundsAttr); diff --git a/mlir/lib/Dialect/Vector/Transforms/VectorTransferPermutationMapRewritePatterns.cpp b/mlir/lib/Dialect/Vector/Transforms/VectorTransferPermutationMapRewritePatterns.cpp index 9488145..e419fc2 100644 --- a/mlir/lib/Dialect/Vector/Transforms/VectorTransferPermutationMapRewritePatterns.cpp +++ b/mlir/lib/Dialect/Vector/Transforms/VectorTransferPermutationMapRewritePatterns.cpp @@ -105,10 +105,9 @@ struct TransferReadPermutationLowering // Transpose in_bounds attribute. ArrayAttr newInBoundsAttr = - op.getInBounds() - ? transposeInBoundsAttr(rewriter, op.getInBounds().getValue(), - permutation) - : ArrayAttr(); + op.getInBounds() ? transposeInBoundsAttr( + rewriter, op.getInBounds().value(), permutation) + : ArrayAttr(); // Generate new transfer_read operation. VectorType newReadType = @@ -176,10 +175,9 @@ struct TransferWritePermutationLowering // Transpose in_bounds attribute. ArrayAttr newInBoundsAttr = - op.getInBounds() - ? transposeInBoundsAttr(rewriter, op.getInBounds().getValue(), - permutation) - : ArrayAttr(); + op.getInBounds() ? transposeInBoundsAttr( + rewriter, op.getInBounds().value(), permutation) + : ArrayAttr(); // Generate new transfer_write operation. Value newVec = rewriter.create<vector::TransposeOp>( diff --git a/mlir/lib/Dialect/Vector/Transforms/VectorTransforms.cpp b/mlir/lib/Dialect/Vector/Transforms/VectorTransforms.cpp index 67635d6..26e4cac 100644 --- a/mlir/lib/Dialect/Vector/Transforms/VectorTransforms.cpp +++ b/mlir/lib/Dialect/Vector/Transforms/VectorTransforms.cpp @@ -553,9 +553,9 @@ public: Value b = rewriter.create<vector::BroadcastOp>(loc, lhsType, op.getRhs()); Optional<Value> mult = createContractArithOp(loc, op.getLhs(), b, acc, kind, rewriter, isInt); - if (!mult.hasValue()) + if (!mult.has_value()) return failure(); - rewriter.replaceOp(op, mult.getValue()); + rewriter.replaceOp(op, mult.value()); return success(); } @@ -571,9 +571,9 @@ public: r = rewriter.create<vector::ExtractOp>(loc, rhsType, acc, pos); Optional<Value> m = createContractArithOp(loc, a, op.getRhs(), r, kind, rewriter, isInt); - if (!m.hasValue()) + if (!m.has_value()) return failure(); - result = rewriter.create<vector::InsertOp>(loc, resType, m.getValue(), + result = rewriter.create<vector::InsertOp>(loc, resType, m.value(), result, pos); } rewriter.replaceOp(op, result); @@ -1824,8 +1824,8 @@ Value ContractionOpLowering::lowerParallel(vector::ContractionOp op, } assert(iterIndex >= 0 && "parallel index not listed in operand mapping"); Optional<int64_t> lookup = getResultIndex(iMap[2], iterIndex); - assert(lookup.hasValue() && "parallel index not listed in reduction"); - int64_t resIndex = lookup.getValue(); + assert(lookup && "parallel index not listed in reduction"); + int64_t resIndex = lookup.value(); // Construct new iterator types and affine map array attribute. std::array<AffineMap, 3> lowIndexingMaps = { adjustMap(iMap[0], iterIndex, rewriter), @@ -1864,10 +1864,10 @@ Value ContractionOpLowering::lowerReduction(vector::ContractionOp op, SmallVector<AffineMap, 4> iMap = op.getIndexingMaps(); Optional<int64_t> lookupLhs = getResultIndex(iMap[0], iterIndex); Optional<int64_t> lookupRhs = getResultIndex(iMap[1], iterIndex); - assert(lookupLhs.hasValue() && "missing LHS parallel index"); - assert(lookupRhs.hasValue() && "missing RHS parallel index"); - int64_t lhsIndex = lookupLhs.getValue(); - int64_t rhsIndex = lookupRhs.getValue(); + assert(lookupLhs && "missing LHS parallel index"); + assert(lookupRhs && "missing RHS parallel index"); + int64_t lhsIndex = lookupLhs.value(); + int64_t rhsIndex = lookupRhs.value(); int64_t dimSize = lhsType.getDimSize(lhsIndex); assert(dimSize == rhsType.getDimSize(rhsIndex) && "corrupt shape"); // Base case. diff --git a/mlir/lib/IR/FunctionImplementation.cpp b/mlir/lib/IR/FunctionImplementation.cpp index a9160a9..9481e4a 100644 --- a/mlir/lib/IR/FunctionImplementation.cpp +++ b/mlir/lib/IR/FunctionImplementation.cpp @@ -41,8 +41,8 @@ parseFunctionArgumentList(OpAsmParser &parser, bool allowVariadic, OpAsmParser::Argument argument; auto argPresent = parser.parseOptionalArgument( argument, /*allowType=*/true, /*allowAttrs=*/true); - if (argPresent.hasValue()) { - if (failed(argPresent.getValue())) + if (argPresent.has_value()) { + if (failed(argPresent.value())) return failure(); // Present but malformed. // Reject this if the preceding argument was missing a name. @@ -229,7 +229,7 @@ ParseResult mlir::function_interface_impl::parseFunctionOp( OptionalParseResult parseResult = parser.parseOptionalRegion(*body, entryArgs, /*enableNameShadowing=*/false); - if (parseResult.hasValue()) { + if (parseResult.has_value()) { if (failed(*parseResult)) return failure(); // Function body was parsed, make sure its not empty. diff --git a/mlir/lib/Interfaces/ControlFlowInterfaces.cpp b/mlir/lib/Interfaces/ControlFlowInterfaces.cpp index 991f16e..d84218c 100644 --- a/mlir/lib/Interfaces/ControlFlowInterfaces.cpp +++ b/mlir/lib/Interfaces/ControlFlowInterfaces.cpp @@ -107,20 +107,20 @@ verifyTypesAlongAllEdges(Operation *op, Optional<unsigned> sourceNo, auto printEdgeName = [&](InFlightDiagnostic &diag) -> InFlightDiagnostic & { diag << "from "; if (sourceNo) - diag << "Region #" << sourceNo.getValue(); + diag << "Region #" << sourceNo.value(); else diag << "parent operands"; diag << " to "; if (succRegionNo) - diag << "Region #" << succRegionNo.getValue(); + diag << "Region #" << succRegionNo.value(); else diag << "parent results"; return diag; }; Optional<TypeRange> sourceTypes = getInputsTypesForRegion(succRegionNo); - if (!sourceTypes.hasValue()) + if (!sourceTypes.has_value()) continue; TypeRange succInputsTypes = succ.getSuccessorInputs().getTypes(); diff --git a/mlir/lib/Interfaces/ViewLikeInterface.cpp b/mlir/lib/Interfaces/ViewLikeInterface.cpp index 4ecf539..36489d4 100644 --- a/mlir/lib/Interfaces/ViewLikeInterface.cpp +++ b/mlir/lib/Interfaces/ViewLikeInterface.cpp @@ -121,7 +121,7 @@ static ParseResult parseOperandsOrIntegersImpl( while (true) { OpAsmParser::UnresolvedOperand operand; auto res = parser.parseOptionalOperand(operand); - if (res.hasValue() && succeeded(res.getValue())) { + if (res.has_value() && succeeded(res.value())) { values.push_back(operand); attrVals.push_back(dynVal); } else { diff --git a/mlir/lib/Parser/AffineParser.cpp b/mlir/lib/Parser/AffineParser.cpp index f62455c..eb65dde 100644 --- a/mlir/lib/Parser/AffineParser.cpp +++ b/mlir/lib/Parser/AffineParser.cpp @@ -324,11 +324,11 @@ AffineExpr AffineParser::parseSymbolSSAIdExpr() { /// affine-expr ::= integer-literal AffineExpr AffineParser::parseIntegerExpr() { auto val = getToken().getUInt64IntegerValue(); - if (!val.hasValue() || (int64_t)val.getValue() < 0) + if (!val.has_value() || (int64_t)val.value() < 0) return emitError("constant too large for index"), nullptr; consumeToken(Token::integer); - return builder.getAffineConstantExpr((int64_t)val.getValue()); + return builder.getAffineConstantExpr((int64_t)val.value()); } /// Parses an expression that can be a valid operand of an affine expression. diff --git a/mlir/lib/Parser/AttributeParser.cpp b/mlir/lib/Parser/AttributeParser.cpp index efc1c22..eafebe9 100644 --- a/mlir/lib/Parser/AttributeParser.cpp +++ b/mlir/lib/Parser/AttributeParser.cpp @@ -211,7 +211,7 @@ Attribute Parser::parseAttribute(Type type) { // better error message. Type type; OptionalParseResult result = parseOptionalType(type); - if (!result.hasValue()) + if (!result.has_value()) return emitWrongTokenError("expected attribute value"), Attribute(); return failed(*result) ? Attribute() : TypeAttr::get(type); } @@ -245,7 +245,7 @@ OptionalParseResult Parser::parseOptionalAttribute(Attribute &attribute, // Parse an optional type attribute. Type type; OptionalParseResult result = parseOptionalType(type); - if (result.hasValue() && succeeded(*result)) + if (result.has_value() && succeeded(*result)) attribute = TypeAttr::get(type); return result; } @@ -666,8 +666,8 @@ TensorLiteralParser::getFloatAttrElements(SMLoc loc, FloatType eltTy, DenseElementsAttr TensorLiteralParser::getStringAttr(SMLoc loc, ShapedType type, Type eltTy) { - if (hexStorage.hasValue()) { - auto stringValue = hexStorage.getValue().getStringValue(); + if (hexStorage) { + auto stringValue = hexStorage->getStringValue(); return DenseStringElementsAttr::get(type, {stringValue}); } diff --git a/mlir/lib/Parser/LocationParser.cpp b/mlir/lib/Parser/LocationParser.cpp index 4749c16..cf1e8af 100644 --- a/mlir/lib/Parser/LocationParser.cpp +++ b/mlir/lib/Parser/LocationParser.cpp @@ -118,11 +118,11 @@ ParseResult Parser::parseNameOrFileLineColLocation(LocationAttr &loc) { return emitWrongTokenError( "expected integer column number in FileLineColLoc"); auto column = getToken().getUnsignedIntegerValue(); - if (!column.hasValue()) + if (!column.has_value()) return emitError("expected integer column number in FileLineColLoc"); consumeToken(Token::integer); - loc = FileLineColLoc::get(ctx, str, line.getValue(), column.getValue()); + loc = FileLineColLoc::get(ctx, str, line.value(), column.value()); return success(); } diff --git a/mlir/lib/Parser/Parser.cpp b/mlir/lib/Parser/Parser.cpp index 170d571..6100134 100644 --- a/mlir/lib/Parser/Parser.cpp +++ b/mlir/lib/Parser/Parser.cpp @@ -1857,8 +1857,8 @@ ParseResult OperationParser::parseRegionBody(Region ®ion, SMLoc startLoc, .attachNote(getEncodedSourceLocation(*defLoc)) << "previously referenced here"; } - Location loc = entryArg.sourceLoc.hasValue() - ? entryArg.sourceLoc.getValue() + Location loc = entryArg.sourceLoc.has_value() + ? entryArg.sourceLoc.value() : getEncodedSourceLocation(argInfo.location); BlockArgument arg = block->addArgument(entryArg.type, loc); diff --git a/mlir/lib/Parser/TypeParser.cpp b/mlir/lib/Parser/TypeParser.cpp index 52fae4b..5c69ad2 100644 --- a/mlir/lib/Parser/TypeParser.cpp +++ b/mlir/lib/Parser/TypeParser.cpp @@ -310,9 +310,9 @@ Type Parser::parseNonFunctionType() { // integer-type case Token::inttype: { auto width = getToken().getIntTypeBitwidth(); - if (!width.hasValue()) + if (!width.has_value()) return (emitError("invalid integer width"), nullptr); - if (width.getValue() > IntegerType::kMaxWidth) { + if (width.value() > IntegerType::kMaxWidth) { emitError(getToken().getLoc(), "integer bitwidth is limited to ") << IntegerType::kMaxWidth << " bits"; return nullptr; diff --git a/mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp b/mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp index 32237bd..1b1a18f 100644 --- a/mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp +++ b/mlir/lib/Target/LLVMIR/ConvertFromLLVMIR.cpp @@ -432,8 +432,8 @@ GlobalOp Importer::processGlobal(llvm::GlobalVariable *gv) { uint64_t alignment = 0; llvm::MaybeAlign maybeAlign = gv->getAlign(); - if (maybeAlign.hasValue()) { - llvm::Align align = maybeAlign.getValue(); + if (maybeAlign) { + llvm::Align align = maybeAlign.value(); alignment = align.value(); } diff --git a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp index d0cb2d3..fac9b64 100644 --- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp +++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp @@ -28,9 +28,9 @@ using namespace mlir; namespace { static llvm::omp::ScheduleKind convertToScheduleKind(Optional<omp::ClauseScheduleKind> schedKind) { - if (!schedKind.hasValue()) + if (!schedKind.has_value()) return llvm::omp::OMP_SCHEDULE_Default; - switch (schedKind.getValue()) { + switch (schedKind.value()) { case omp::ClauseScheduleKind::Static: return llvm::omp::OMP_SCHEDULE_Static; case omp::ClauseScheduleKind::Dynamic: diff --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp index 923cffc1..93498c7 100644 --- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp +++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp @@ -666,17 +666,17 @@ LogicalResult ModuleTranslation::convertGlobals() { : llvm::GlobalValue::NotThreadLocal, addrSpace); - if (op.getUnnamedAddr().hasValue()) + if (op.getUnnamedAddr().has_value()) var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr())); - if (op.getSection().hasValue()) + if (op.getSection().has_value()) var->setSection(*op.getSection()); addRuntimePreemptionSpecifier(op.getDsoLocal(), var); Optional<uint64_t> alignment = op.getAlignment(); - if (alignment.hasValue()) - var->setAlignment(llvm::MaybeAlign(alignment.getValue())); + if (alignment) + var->setAlignment(llvm::MaybeAlign(alignment.value())); globalsMapping.try_emplace(op, var); } diff --git a/mlir/lib/Target/SPIRV/Deserialization/Deserializer.cpp b/mlir/lib/Target/SPIRV/Deserialization/Deserializer.cpp index 361413e..383bdc4 100644 --- a/mlir/lib/Target/SPIRV/Deserialization/Deserializer.cpp +++ b/mlir/lib/Target/SPIRV/Deserialization/Deserializer.cpp @@ -377,7 +377,7 @@ spirv::Deserializer::processFunction(ArrayRef<uint32_t> operands) { std::string fnName = getFunctionSymbol(fnID); auto funcOp = opBuilder.create<spirv::FuncOp>( - unknownLoc, fnName, functionType, fnControl.getValue()); + unknownLoc, fnName, functionType, fnControl.value()); curFunction = funcMap[fnID] = funcOp; auto *entryBlock = funcOp.addEntryBlock(); LLVM_DEBUG({ @@ -883,7 +883,7 @@ spirv::Deserializer::processCooperativeMatrixType(ArrayRef<uint32_t> operands) { unsigned columns = getConstantInt(operands[4]).getInt(); typeMap[operands[0]] = spirv::CooperativeMatrixNVType::get( - elementTy, scope.getValue(), rows, columns); + elementTy, scope.value(), rows, columns); return success(); } @@ -1067,8 +1067,8 @@ spirv::Deserializer::processImageType(ArrayRef<uint32_t> operands) { << operands[7]; typeMap[operands[0]] = spirv::ImageType::get( - elementTy, dim.getValue(), depthInfo.getValue(), arrayedInfo.getValue(), - samplingInfo.getValue(), samplerUseInfo.getValue(), format.getValue()); + elementTy, dim.value(), depthInfo.value(), arrayedInfo.value(), + samplingInfo.value(), samplerUseInfo.value(), format.value()); return success(); } diff --git a/mlir/test/lib/Analysis/TestMemRefDependenceCheck.cpp b/mlir/test/lib/Analysis/TestMemRefDependenceCheck.cpp index eebd9e3..a45e21a 100644 --- a/mlir/test/lib/Analysis/TestMemRefDependenceCheck.cpp +++ b/mlir/test/lib/Analysis/TestMemRefDependenceCheck.cpp @@ -52,16 +52,14 @@ getDirectionVectorStr(bool ret, unsigned numCommonLoops, unsigned loopNestDepth, std::string result; for (const auto &dependenceComponent : dependenceComponents) { std::string lbStr = "-inf"; - if (dependenceComponent.lb.hasValue() && - dependenceComponent.lb.getValue() != - std::numeric_limits<int64_t>::min()) - lbStr = std::to_string(dependenceComponent.lb.getValue()); + if (dependenceComponent.lb.has_value() && + dependenceComponent.lb.value() != std::numeric_limits<int64_t>::min()) + lbStr = std::to_string(dependenceComponent.lb.value()); std::string ubStr = "+inf"; - if (dependenceComponent.ub.hasValue() && - dependenceComponent.ub.getValue() != - std::numeric_limits<int64_t>::max()) - ubStr = std::to_string(dependenceComponent.ub.getValue()); + if (dependenceComponent.ub.has_value() && + dependenceComponent.ub.value() != std::numeric_limits<int64_t>::max()) + ubStr = std::to_string(dependenceComponent.ub.value()); result += "[" + lbStr + ", " + ubStr + "]"; } diff --git a/mlir/test/lib/Dialect/Test/TestDialect.cpp b/mlir/test/lib/Dialect/Test/TestDialect.cpp index 45d345e..64cf476 100644 --- a/mlir/test/lib/Dialect/Test/TestDialect.cpp +++ b/mlir/test/lib/Dialect/Test/TestDialect.cpp @@ -1310,8 +1310,8 @@ void RegionIfOp::getSuccessorRegions( Optional<unsigned> index, ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> ®ions) { // We always branch to the join region. - if (index.hasValue()) { - if (index.getValue() < 2) + if (index) { + if (index.value() < 2) regions.push_back(RegionSuccessor(&getJoinRegion(), getJoinArgs())); else regions.push_back(RegionSuccessor(getResults())); diff --git a/mlir/test/lib/Dialect/Test/TestTypeDefs.td b/mlir/test/lib/Dialect/Test/TestTypeDefs.td index fd50dd3..9853b4a 100644 --- a/mlir/test/lib/Dialect/Test/TestTypeDefs.td +++ b/mlir/test/lib/Dialect/Test/TestTypeDefs.td @@ -292,9 +292,9 @@ class DefaultValuedAPFloat<string value> let parser = [{ [&]() -> mlir::FailureOr<llvm::Optional<llvm::APFloat>> { mlir::FloatAttr attr; auto result = $_parser.parseOptionalAttribute(attr); - if (result.hasValue() && mlir::succeeded(*result)) + if (result.has_value() && mlir::succeeded(*result)) return {attr.getValue()}; - if (!result.hasValue()) + if (!result.has_value()) return llvm::Optional<llvm::APFloat>(); return mlir::failure(); }() }]; diff --git a/mlir/test/lib/Dialect/Test/TestTypes.cpp b/mlir/test/lib/Dialect/Test/TestTypes.cpp index 5418025..76e67ed 100644 --- a/mlir/test/lib/Dialect/Test/TestTypes.cpp +++ b/mlir/test/lib/Dialect/Test/TestTypes.cpp @@ -414,15 +414,15 @@ Type TestDialect::parseTestType(AsmParser &parser, { Type genType; auto parseResult = generatedTypeParser(parser, typeTag, genType); - if (parseResult.hasValue()) + if (parseResult.has_value()) return genType; } { Type dynType; auto parseResult = parseOptionalDynamicType(typeTag, parser, dynType); - if (parseResult.hasValue()) { - if (succeeded(parseResult.getValue())) + if (parseResult.has_value()) { + if (succeeded(parseResult.value())) return dynType; return Type(); } diff --git a/mlir/test/lib/Dialect/Test/TestTypes.h b/mlir/test/lib/Dialect/Test/TestTypes.h index bd6421d..654600b 100644 --- a/mlir/test/lib/Dialect/Test/TestTypes.h +++ b/mlir/test/lib/Dialect/Test/TestTypes.h @@ -77,7 +77,7 @@ struct FieldParser<Optional<int>> { Optional<int> value; value.emplace(); OptionalParseResult result = parser.parseOptionalInteger(*value); - if (result.hasValue()) { + if (result.has_value()) { if (succeeded(*result)) return value; return failure(); diff --git a/mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp b/mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp index 9242a51..a81090b 100644 --- a/mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp +++ b/mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp @@ -52,12 +52,12 @@ public: static ParseResult parse(OpAsmParser &parser, OperationState &state) { StringAttr message; OptionalParseResult result = parser.parseOptionalAttribute(message); - if (!result.hasValue()) + if (!result.has_value()) return success(); - if (result.getValue().succeeded()) + if (result.value().succeeded()) state.addAttribute("message", message); - return result.getValue(); + return result.value(); } void print(OpAsmPrinter &printer) { diff --git a/mlir/test/lib/Transforms/TestIntRangeInference.cpp b/mlir/test/lib/Transforms/TestIntRangeInference.cpp index 1bd2a24..f9f8db4 100644 --- a/mlir/test/lib/Transforms/TestIntRangeInference.cpp +++ b/mlir/test/lib/Transforms/TestIntRangeInference.cpp @@ -25,9 +25,9 @@ static LogicalResult replaceWithConstant(IntRangeAnalysis &analysis, Optional<ConstantIntRanges> maybeInferredRange = analysis.getResult(value); if (!maybeInferredRange) return failure(); - const ConstantIntRanges &inferredRange = maybeInferredRange.getValue(); + const ConstantIntRanges &inferredRange = maybeInferredRange.value(); Optional<APInt> maybeConstValue = inferredRange.getConstantValue(); - if (!maybeConstValue.hasValue()) + if (!maybeConstValue.has_value()) return failure(); Operation *maybeDefiningOp = value.getDefiningOp(); diff --git a/mlir/test/mlir-tblgen/default-type-attr-print-parser.td b/mlir/test/mlir-tblgen/default-type-attr-print-parser.td index ac898a9..88328fd 100644 --- a/mlir/test/mlir-tblgen/default-type-attr-print-parser.td +++ b/mlir/test/mlir-tblgen/default-type-attr-print-parser.td @@ -32,7 +32,7 @@ def AttrA : TestAttr<"AttrA"> { // ATTR: { // ATTR: ::mlir::Attribute attr; // ATTR: auto parseResult = generatedAttributeParser(parser, attrTag, type, attr); -// ATTR: if (parseResult.hasValue()) +// ATTR: if (parseResult.has_value()) // ATTR: return attr; // ATTR: } // ATTR: parser.emitError(typeLoc) << "unknown attribute `" @@ -61,7 +61,7 @@ def TypeA : TestType<"TypeA"> { // TYPE: return ::mlir::Type(); // TYPE: ::mlir::Type genType; // TYPE: auto parseResult = generatedTypeParser(parser, mnemonic, genType); -// TYPE: if (parseResult.hasValue()) +// TYPE: if (parseResult.has_value()) // TYPE: return genType; // TYPE: parser.emitError(typeLoc) << "unknown type `" // TYPE: << mnemonic << "` in dialect `" << getNamespace() << "`"; diff --git a/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-yaml-gen.cpp b/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-yaml-gen.cpp index 9140c53..2c28d0e 100644 --- a/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-yaml-gen.cpp +++ b/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-yaml-gen.cpp @@ -730,16 +730,16 @@ static LogicalResult generateNamedGenericOpOds(LinalgOpConfig &opConfig, } // Add the index attributes to the op definition and builders. if (arg.kind == LinalgOperandDefKind::IndexAttr) { - assert(arg.indexAttrMap.hasValue()); - assert(arg.defaultIndices.hasValue()); + assert(arg.indexAttrMap.has_value()); + assert(arg.defaultIndices.has_value()); size_t size = arg.indexAttrMap->affineMap().getNumResults(); - assert(arg.defaultIndices.getValue().size() == size); + assert(arg.defaultIndices->size() == size); static const char typeFmt[] = "RankedI64ElementsAttr<[{0}]>"; static const char defFmt[] = "DefaultValuedAttr<{0}, \"{ {1} }\">:${2}"; std::string defaultVals; llvm::raw_string_ostream ss(defaultVals); llvm::interleave( - arg.defaultIndices.getValue(), ss, + arg.defaultIndices.value(), ss, [&](int64_t val) { ss << "static_cast<int64_t>(" << val << ")"; }, ", "); attrDefs.push_back(llvm::formatv(defFmt, llvm::formatv(typeFmt, size), @@ -1088,11 +1088,11 @@ if ({1}Iter != attrs.end()) {{ if (expression.scalarFn->attrName) { if (llvm::none_of(args, [&](LinalgOperandDef &arg) { return isFunctionAttribute(arg.kind) && - arg.name == expression.scalarFn->attrName.getValue(); + arg.name == expression.scalarFn->attrName.value(); })) { emitError(genContext.getLoc()) << "missing function attribute " - << expression.scalarFn->attrName.getValue(); + << expression.scalarFn->attrName.value(); } funcType = llvm::formatv("{0}Val", *expression.scalarFn->attrName); } @@ -1101,17 +1101,17 @@ if ({1}Iter != attrs.end()) {{ // Add the optional type parameter to the operands. SmallVector<std::string> operandCppValues; if (expression.scalarFn->kind == ScalarFnKind::Type) { - assert(expression.scalarFn->typeVar.hasValue()); + assert(expression.scalarFn->typeVar.has_value()); Optional<std::string> typeCppValue = - findTypeValue(expression.scalarFn->typeVar.getValue(), args); + findTypeValue(expression.scalarFn->typeVar.value(), args); if (!typeCppValue) { emitError(genContext.getLoc()) - << "type variable " << expression.scalarFn->typeVar.getValue() + << "type variable " << expression.scalarFn->typeVar.value() << ", used in a type conversion, must map to a predefined or " << "an argument type but it does not"; return None; } - operandCppValues.push_back(typeCppValue.getValue()); + operandCppValues.push_back(typeCppValue.value()); } // Collect the scalar operands. diff --git a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp index 759143d..53cc698 100644 --- a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp +++ b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp @@ -678,7 +678,7 @@ static const char *const dialectDefaultAttrPrinterParserDispatch = R"( {{ ::mlir::Attribute attr; auto parseResult = generatedAttributeParser(parser, attrTag, type, attr); - if (parseResult.hasValue()) + if (parseResult.has_value()) return attr; } {1} @@ -700,8 +700,8 @@ static const char *const dialectDynamicAttrParserDispatch = R"( { ::mlir::Attribute genAttr; auto parseResult = parseOptionalDynamicAttr(attrTag, parser, genAttr); - if (parseResult.hasValue()) { - if (::mlir::succeeded(parseResult.getValue())) + if (parseResult.has_value()) { + if (::mlir::succeeded(*parseResult)) return genAttr; return Attribute(); } @@ -727,7 +727,7 @@ static const char *const dialectDefaultTypePrinterParserDispatch = R"( return ::mlir::Type(); ::mlir::Type genType; auto parseResult = generatedTypeParser(parser, mnemonic, genType); - if (parseResult.hasValue()) + if (parseResult.has_value()) return genType; {1} parser.emitError(typeLoc) << "unknown type `" @@ -747,7 +747,7 @@ void {0}::printType(::mlir::Type type, static const char *const dialectDynamicTypeParserDispatch = R"( { auto parseResult = parseOptionalDynamicType(mnemonic, parser, genType); - if (parseResult.hasValue()) { + if (parseResult.has_value()) { if (::mlir::succeeded(parseResult.getValue())) return genType; return Type(); diff --git a/mlir/tools/mlir-tblgen/OpFormatGen.cpp b/mlir/tools/mlir-tblgen/OpFormatGen.cpp index 212fe0e..1269622 100644 --- a/mlir/tools/mlir-tblgen/OpFormatGen.cpp +++ b/mlir/tools/mlir-tblgen/OpFormatGen.cpp @@ -408,7 +408,7 @@ const char *const optionalAttrParserCode = R"( { ::mlir::OptionalParseResult parseResult = parser.parseOptionalAttribute({0}Attr, {1}, "{0}", result.attributes); - if (parseResult.hasValue() && failed(*parseResult)) + if (parseResult.has_value() && failed(*parseResult)) return ::mlir::failure(); } )"; @@ -445,7 +445,7 @@ const char *const enumAttrParserCode = R"( parser.parseOptionalAttribute(attrVal, parser.getBuilder().getNoneType(), "{0}", attrStorage); - if (parseResult.hasValue()) {{ + if (parseResult.has_value()) {{ if (failed(*parseResult)) return ::mlir::failure(); attrStr = attrVal.getValue(); @@ -479,7 +479,7 @@ const char *const optionalOperandParserCode = R"( ::mlir::OpAsmParser::UnresolvedOperand operand; ::mlir::OptionalParseResult parseResult = parser.parseOptionalOperand(operand); - if (parseResult.hasValue()) { + if (parseResult.has_value()) { if (failed(*parseResult)) return ::mlir::failure(); {0}Operands.push_back(operand); @@ -532,7 +532,7 @@ const char *const optionalTypeParserCode = R"( ::mlir::Type optionalType; ::mlir::OptionalParseResult parseResult = parser.parseOptionalType(optionalType); - if (parseResult.hasValue()) { + if (parseResult.has_value()) { if (failed(*parseResult)) return ::mlir::failure(); {0}Types.push_back(optionalType); @@ -584,7 +584,7 @@ const char *regionListParserCode = R"( { std::unique_ptr<::mlir::Region> region; auto firstRegionResult = parser.parseOptionalRegion(region); - if (firstRegionResult.hasValue()) { + if (firstRegionResult.has_value()) { if (failed(*firstRegionResult)) return ::mlir::failure(); {0}Regions.emplace_back(std::move(region)); @@ -622,7 +622,7 @@ const char *regionListEnsureSingleBlockParserCode = R"( const char *optionalRegionParserCode = R"( { auto parseResult = parser.parseOptionalRegion(*{0}Region); - if (parseResult.hasValue() && failed(*parseResult)) + if (parseResult.has_value() && failed(*parseResult)) return ::mlir::failure(); } )"; @@ -656,7 +656,7 @@ const char *successorListParserCode = R"( { ::mlir::Block *succ; auto firstSucc = parser.parseOptionalSuccessor(succ); - if (firstSucc.hasValue()) { + if (firstSucc.has_value()) { if (failed(*firstSucc)) return ::mlir::failure(); {0}Successors.emplace_back(succ); diff --git a/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp b/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp index f69b4ee..5929e92 100644 --- a/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp +++ b/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp @@ -66,8 +66,8 @@ static void checkSample(bool hasSample, const IntegerPolyhedron &poly, maybeLexMin = poly.findIntegerLexMin(); if (!hasSample) { - EXPECT_FALSE(maybeSample.hasValue()); - if (maybeSample.hasValue()) { + EXPECT_FALSE(maybeSample.has_value()); + if (maybeSample.has_value()) { llvm::errs() << "findIntegerSample gave sample: "; dump(*maybeSample); } @@ -78,7 +78,7 @@ static void checkSample(bool hasSample, const IntegerPolyhedron &poly, dump(*maybeLexMin); } } else { - ASSERT_TRUE(maybeSample.hasValue()); + ASSERT_TRUE(maybeSample.has_value()); EXPECT_TRUE(poly.containsPoint(*maybeSample)); ASSERT_FALSE(maybeLexMin.isEmpty()); diff --git a/mlir/unittests/Analysis/Presburger/PWMAFunctionTest.cpp b/mlir/unittests/Analysis/Presburger/PWMAFunctionTest.cpp index 27d0252..1c959c6 100644 --- a/mlir/unittests/Analysis/Presburger/PWMAFunctionTest.cpp +++ b/mlir/unittests/Analysis/Presburger/PWMAFunctionTest.cpp @@ -138,7 +138,7 @@ TEST(PWMAFunction, valueAt) { EXPECT_THAT(*nonNegPWMAF.valueAt({2, 3}), ElementsAre(11, 23)); EXPECT_THAT(*nonNegPWMAF.valueAt({-2, 3}), ElementsAre(11, 23)); EXPECT_THAT(*nonNegPWMAF.valueAt({2, -3}), ElementsAre(-1, -1)); - EXPECT_FALSE(nonNegPWMAF.valueAt({-2, -3}).hasValue()); + EXPECT_FALSE(nonNegPWMAF.valueAt({-2, -3}).has_value()); PWMAFunction divPWMAF = parsePWMAF( /*numInputs=*/2, /*numOutputs=*/2, @@ -149,11 +149,11 @@ TEST(PWMAFunction, valueAt) { }); EXPECT_THAT(*divPWMAF.valueAt({4, 3}), ElementsAre(11, 23)); EXPECT_THAT(*divPWMAF.valueAt({4, -3}), ElementsAre(-1, -1)); - EXPECT_FALSE(divPWMAF.valueAt({3, 3}).hasValue()); - EXPECT_FALSE(divPWMAF.valueAt({3, -3}).hasValue()); + EXPECT_FALSE(divPWMAF.valueAt({3, 3}).has_value()); + EXPECT_FALSE(divPWMAF.valueAt({3, -3}).has_value()); EXPECT_THAT(*divPWMAF.valueAt({-2, 3}), ElementsAre(11, 23)); - EXPECT_FALSE(divPWMAF.valueAt({-2, -3}).hasValue()); + EXPECT_FALSE(divPWMAF.valueAt({-2, -3}).has_value()); } TEST(PWMAFunction, removeIdRangeRegressionTest) { diff --git a/mlir/unittests/Analysis/Presburger/PresburgerSetTest.cpp b/mlir/unittests/Analysis/Presburger/PresburgerSetTest.cpp index 0c98f48..aa71825 100644 --- a/mlir/unittests/Analysis/Presburger/PresburgerSetTest.cpp +++ b/mlir/unittests/Analysis/Presburger/PresburgerSetTest.cpp @@ -762,7 +762,7 @@ void testComputeReprAtPoints(IntegerPolyhedron poly, EXPECT_TRUE(repr.hasOnlyDivLocals()); EXPECT_TRUE(repr.getSpace().isCompatible(poly.getSpace())); for (const SmallVector<int64_t, 4> &point : points) { - EXPECT_EQ(poly.containsPointNoLocal(point).hasValue(), + EXPECT_EQ(poly.containsPointNoLocal(point).has_value(), repr.containsPoint(point)); } } diff --git a/mlir/unittests/Analysis/Presburger/SimplexTest.cpp b/mlir/unittests/Analysis/Presburger/SimplexTest.cpp index 4c55c92..df03935e 100644 --- a/mlir/unittests/Analysis/Presburger/SimplexTest.cpp +++ b/mlir/unittests/Analysis/Presburger/SimplexTest.cpp @@ -196,7 +196,7 @@ TEST(SimplexTest, getSamplePointIfIntegral) { }, {}) .getSamplePointIfIntegral() - .hasValue()); + .has_value()); auto maybeSample = simplexFromConstraints(2, {// x = y - 2. @@ -208,7 +208,7 @@ TEST(SimplexTest, getSamplePointIfIntegral) { {}) .getSamplePointIfIntegral(); - EXPECT_TRUE(maybeSample.hasValue()); + EXPECT_TRUE(maybeSample.has_value()); EXPECT_THAT(*maybeSample, testing::ElementsAre(0, 2)); auto maybeSample2 = simplexFromConstraints(2, @@ -220,7 +220,7 @@ TEST(SimplexTest, getSamplePointIfIntegral) { {0, 1, -2} // y = 2. }) .getSamplePointIfIntegral(); - EXPECT_TRUE(maybeSample2.hasValue()); + EXPECT_TRUE(maybeSample2.has_value()); EXPECT_THAT(*maybeSample2, testing::ElementsAre(0, 2)); EXPECT_FALSE(simplexFromConstraints(1, @@ -229,7 +229,7 @@ TEST(SimplexTest, getSamplePointIfIntegral) { {-2, +1}}, {}) .getSamplePointIfIntegral() - .hasValue()); + .has_value()); } /// Some basic sanity checks involving zero or one variables. @@ -545,7 +545,7 @@ TEST(SimplexTest, addDivisionVariable) { simplex.addInequality({1, 0, -3}); // x >= 3. simplex.addInequality({-1, 0, 9}); // x <= 9. Optional<SmallVector<int64_t, 8>> sample = simplex.findIntegerSample(); - ASSERT_TRUE(sample.hasValue()); + ASSERT_TRUE(sample.has_value()); EXPECT_EQ((*sample)[0] / 2, (*sample)[1]); } diff --git a/mlir/unittests/IR/OperationSupportTest.cpp b/mlir/unittests/IR/OperationSupportTest.cpp index 2511a5d3..4f6a98d 100644 --- a/mlir/unittests/IR/OperationSupportTest.cpp +++ b/mlir/unittests/IR/OperationSupportTest.cpp @@ -247,7 +247,7 @@ TEST(NamedAttrListTest, TestAppendAssign) { attrs.append("foo", b.getStringAttr("zoo")); { auto dup = attrs.findDuplicate(); - ASSERT_TRUE(dup.hasValue()); + ASSERT_TRUE(dup.has_value()); } SmallVector<NamedAttribute> newAttrs = { @@ -257,7 +257,7 @@ TEST(NamedAttrListTest, TestAppendAssign) { attrs.assign(newAttrs); auto dup = attrs.findDuplicate(); - ASSERT_FALSE(dup.hasValue()); + ASSERT_FALSE(dup.has_value()); { auto *it = attrs.begin(); diff --git a/mlir/unittests/Interfaces/ControlFlowInterfacesTest.cpp b/mlir/unittests/Interfaces/ControlFlowInterfacesTest.cpp index b92f319..af02a45 100644 --- a/mlir/unittests/Interfaces/ControlFlowInterfacesTest.cpp +++ b/mlir/unittests/Interfaces/ControlFlowInterfacesTest.cpp @@ -79,7 +79,7 @@ struct DoubleLoopRegionsOp void getSuccessorRegions(Optional<unsigned> index, ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> ®ions) { - if (index.hasValue()) { + if (index.has_value()) { regions.push_back(RegionSuccessor()); regions.push_back(RegionSuccessor(&getOperation()->getRegion(*index))); } diff --git a/mlir/unittests/Pass/AnalysisManagerTest.cpp b/mlir/unittests/Pass/AnalysisManagerTest.cpp index cef8da7..5fa17f3 100644 --- a/mlir/unittests/Pass/AnalysisManagerTest.cpp +++ b/mlir/unittests/Pass/AnalysisManagerTest.cpp @@ -52,8 +52,8 @@ TEST(AnalysisManagerTest, FineGrainModuleAnalysisPreservation) { am.invalidate(pa); // Check that only MyAnalysis is preserved. - EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().hasValue()); - EXPECT_FALSE(am.getCachedAnalysis<OtherAnalysis>().hasValue()); + EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().has_value()); + EXPECT_FALSE(am.getCachedAnalysis<OtherAnalysis>().has_value()); } TEST(AnalysisManagerTest, FineGrainFunctionAnalysisPreservation) { @@ -83,8 +83,8 @@ TEST(AnalysisManagerTest, FineGrainFunctionAnalysisPreservation) { fam.invalidate(pa); // Check that only MyAnalysis is preserved. - EXPECT_TRUE(fam.getCachedAnalysis<MyAnalysis>().hasValue()); - EXPECT_FALSE(fam.getCachedAnalysis<OtherAnalysis>().hasValue()); + EXPECT_TRUE(fam.getCachedAnalysis<MyAnalysis>().has_value()); + EXPECT_FALSE(fam.getCachedAnalysis<OtherAnalysis>().has_value()); } TEST(AnalysisManagerTest, FineGrainChildFunctionAnalysisPreservation) { @@ -106,7 +106,7 @@ TEST(AnalysisManagerTest, FineGrainChildFunctionAnalysisPreservation) { AnalysisManager am = mam; // Check that the analysis cache is initially empty. - EXPECT_FALSE(am.getCachedChildAnalysis<MyAnalysis>(func1).hasValue()); + EXPECT_FALSE(am.getCachedChildAnalysis<MyAnalysis>(func1).has_value()); // Query two different analyses, but only preserve one before invalidating. am.getChildAnalysis<MyAnalysis>(func1); @@ -117,8 +117,8 @@ TEST(AnalysisManagerTest, FineGrainChildFunctionAnalysisPreservation) { am.invalidate(pa); // Check that only MyAnalysis is preserved. - EXPECT_TRUE(am.getCachedChildAnalysis<MyAnalysis>(func1).hasValue()); - EXPECT_FALSE(am.getCachedChildAnalysis<OtherAnalysis>(func1).hasValue()); + EXPECT_TRUE(am.getCachedChildAnalysis<MyAnalysis>(func1).has_value()); + EXPECT_FALSE(am.getCachedChildAnalysis<OtherAnalysis>(func1).has_value()); } /// Test analyses with custom invalidation logic. @@ -150,13 +150,13 @@ TEST(AnalysisManagerTest, CustomInvalidation) { // Check that the analysis is invalidated properly. am.getAnalysis<CustomInvalidatingAnalysis>(); am.invalidate(pa); - EXPECT_FALSE(am.getCachedAnalysis<CustomInvalidatingAnalysis>().hasValue()); + EXPECT_FALSE(am.getCachedAnalysis<CustomInvalidatingAnalysis>().has_value()); // Check that the analysis is preserved properly. am.getAnalysis<CustomInvalidatingAnalysis>(); pa.preserve<TestAnalysisSet>(); am.invalidate(pa); - EXPECT_TRUE(am.getCachedAnalysis<CustomInvalidatingAnalysis>().hasValue()); + EXPECT_TRUE(am.getCachedAnalysis<CustomInvalidatingAnalysis>().has_value()); } TEST(AnalysisManagerTest, OpSpecificAnalysis) { @@ -169,7 +169,7 @@ TEST(AnalysisManagerTest, OpSpecificAnalysis) { // Query the op specific analysis for the module and verify that its cached. am.getAnalysis<OpSpecificAnalysis, ModuleOp>(); - EXPECT_TRUE(am.getCachedAnalysis<OpSpecificAnalysis>().hasValue()); + EXPECT_TRUE(am.getCachedAnalysis<OpSpecificAnalysis>().has_value()); } struct AnalysisWithDependency { @@ -194,15 +194,15 @@ TEST(AnalysisManagerTest, DependentAnalysis) { AnalysisManager am = mam; am.getAnalysis<AnalysisWithDependency>(); - EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithDependency>().hasValue()); - EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().hasValue()); + EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithDependency>().has_value()); + EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().has_value()); detail::PreservedAnalyses pa; pa.preserve<AnalysisWithDependency>(); am.invalidate(pa); - EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithDependency>().hasValue()); - EXPECT_FALSE(am.getCachedAnalysis<MyAnalysis>().hasValue()); + EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithDependency>().has_value()); + EXPECT_FALSE(am.getCachedAnalysis<MyAnalysis>().has_value()); } struct AnalysisWithNestedDependency { @@ -227,18 +227,19 @@ TEST(AnalysisManagerTest, NestedDependentAnalysis) { AnalysisManager am = mam; am.getAnalysis<AnalysisWithNestedDependency>(); - EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithNestedDependency>().hasValue()); - EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithDependency>().hasValue()); - EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().hasValue()); + EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithNestedDependency>().has_value()); + EXPECT_TRUE(am.getCachedAnalysis<AnalysisWithDependency>().has_value()); + EXPECT_TRUE(am.getCachedAnalysis<MyAnalysis>().has_value()); detail::PreservedAnalyses pa; pa.preserve<AnalysisWithDependency>(); pa.preserve<AnalysisWithNestedDependency>(); am.invalidate(pa); - EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithNestedDependency>().hasValue()); - EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithDependency>().hasValue()); - EXPECT_FALSE(am.getCachedAnalysis<MyAnalysis>().hasValue()); + EXPECT_FALSE( + am.getCachedAnalysis<AnalysisWithNestedDependency>().has_value()); + EXPECT_FALSE(am.getCachedAnalysis<AnalysisWithDependency>().has_value()); + EXPECT_FALSE(am.getCachedAnalysis<MyAnalysis>().has_value()); } struct AnalysisWith2Ctors { diff --git a/polly/lib/Exchange/JSONExporter.cpp b/polly/lib/Exchange/JSONExporter.cpp index e92055b..d882ea6 100644 --- a/polly/lib/Exchange/JSONExporter.cpp +++ b/polly/lib/Exchange/JSONExporter.cpp @@ -218,8 +218,8 @@ static bool importContext(Scop &S, const json::Object &JScop) { return false; } - isl::set NewContext = isl::set{S.getIslCtx().get(), - JScop.getString("context").getValue().str()}; + isl::set NewContext = + isl::set{S.getIslCtx().get(), JScop.getString("context")->str()}; // Check whether the context was parsed successfully. if (NewContext.is_null()) { @@ -290,10 +290,10 @@ static bool importSchedule(Scop &S, const json::Object &JScop, } Optional<StringRef> Schedule = statements[Index].getAsObject()->getString("schedule"); - assert(Schedule.hasValue() && + assert(Schedule && "Schedules that contain extension nodes require special handling."); - isl_map *Map = isl_map_read_from_str(S.getIslCtx().get(), - Schedule.getValue().str().c_str()); + isl_map *Map = + isl_map_read_from_str(S.getIslCtx().get(), Schedule->str().c_str()); // Check whether the schedule was parsed successfully if (!Map) { @@ -575,14 +575,14 @@ static bool areArraysEqual(ScopArrayInfo *SAI, const json::Object &Array) { for (unsigned i = 1; i < Array.getArray("sizes")->size(); i++) { SAI->getDimensionSize(i)->print(RawStringOstream); const json::Array &SizesArray = *Array.getArray("sizes"); - if (RawStringOstream.str() != SizesArray[i].getAsString().getValue()) + if (RawStringOstream.str() != SizesArray[i].getAsString().value()) return false; Buffer.clear(); } // Check if key 'type' differs from the current one or is not valid. SAI->getElementType()->print(RawStringOstream); - if (RawStringOstream.str() != Array.getString("type").getValue()) { + if (RawStringOstream.str() != Array.getString("type").value()) { errs() << "Array has not a valid type.\n"; return false; } @@ -652,9 +652,8 @@ static bool importArrays(Scop &S, const json::Object &JScop) { for (; ArrayIdx < Arrays.size(); ArrayIdx++) { const json::Object &Array = *Arrays[ArrayIdx].getAsObject(); - auto *ElementType = - parseTextType(Array.get("type")->getAsString().getValue().str(), - S.getSE()->getContext()); + auto *ElementType = parseTextType(Array.get("type")->getAsString()->str(), + S.getSE()->getContext()); if (!ElementType) { errs() << "Error while parsing element type for new array.\n"; return false; @@ -674,10 +673,10 @@ static bool importArrays(Scop &S, const json::Object &JScop) { } auto NewSAI = S.createScopArrayInfo( - ElementType, Array.getString("name").getValue().str(), DimSizes); + ElementType, Array.getString("name")->str(), DimSizes); if (Array.get("allocation")) { - NewSAI->setIsOnHeap(Array.getString("allocation").getValue() == "heap"); + NewSAI->setIsOnHeap(Array.getString("allocation").value() == "heap"); } } diff --git a/polly/lib/Transform/ManualOptimizer.cpp b/polly/lib/Transform/ManualOptimizer.cpp index ef705ec..21d83d9 100644 --- a/polly/lib/Transform/ManualOptimizer.cpp +++ b/polly/lib/Transform/ManualOptimizer.cpp @@ -42,8 +42,8 @@ static TransformationMode hasUnrollTransformation(MDNode *LoopID) { Optional<int> Count = getOptionalIntLoopAttribute(LoopID, "llvm.loop.unroll.count"); - if (Count.hasValue()) - return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser; + if (Count) + return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser; if (getBooleanLoopAttribute(LoopID, "llvm.loop.unroll.enable")) return TM_ForcedByUser; diff --git a/polly/lib/Transform/MatmulOptimizer.cpp b/polly/lib/Transform/MatmulOptimizer.cpp index 4a40fac..d7418d3 100644 --- a/polly/lib/Transform/MatmulOptimizer.cpp +++ b/polly/lib/Transform/MatmulOptimizer.cpp @@ -570,29 +570,29 @@ static void getTargetCacheParameters(const llvm::TargetTransformInfo *TTI) { auto L1DCache = llvm::TargetTransformInfo::CacheLevel::L1D; auto L2DCache = llvm::TargetTransformInfo::CacheLevel::L2D; if (FirstCacheLevelSize == -1) { - if (TTI->getCacheSize(L1DCache).hasValue()) - FirstCacheLevelSize = TTI->getCacheSize(L1DCache).getValue(); + if (TTI->getCacheSize(L1DCache).has_value()) + FirstCacheLevelSize = TTI->getCacheSize(L1DCache).value(); else FirstCacheLevelSize = static_cast<int>(FirstCacheLevelDefaultSize); } if (SecondCacheLevelSize == -1) { - if (TTI->getCacheSize(L2DCache).hasValue()) - SecondCacheLevelSize = TTI->getCacheSize(L2DCache).getValue(); + if (TTI->getCacheSize(L2DCache).has_value()) + SecondCacheLevelSize = TTI->getCacheSize(L2DCache).value(); else SecondCacheLevelSize = static_cast<int>(SecondCacheLevelDefaultSize); } if (FirstCacheLevelAssociativity == -1) { - if (TTI->getCacheAssociativity(L1DCache).hasValue()) + if (TTI->getCacheAssociativity(L1DCache).has_value()) FirstCacheLevelAssociativity = - TTI->getCacheAssociativity(L1DCache).getValue(); + TTI->getCacheAssociativity(L1DCache).value(); else FirstCacheLevelAssociativity = static_cast<int>(FirstCacheLevelDefaultAssociativity); } if (SecondCacheLevelAssociativity == -1) { - if (TTI->getCacheAssociativity(L2DCache).hasValue()) + if (TTI->getCacheAssociativity(L2DCache).has_value()) SecondCacheLevelAssociativity = - TTI->getCacheAssociativity(L2DCache).getValue(); + TTI->getCacheAssociativity(L2DCache).value(); else SecondCacheLevelAssociativity = static_cast<int>(SecondCacheLevelDefaultAssociativity); |