[PATCH] D48522: [analyzer] Highlight c_str() call in DanglingInternalBuffer checker
rnkovacs updated this revision to Diff 152627. rnkovacs marked an inline comment as done. rnkovacs added a comment. Fixed variable name inside the visitor. I also clang-formatted the file, sorry for any line number shifting. https://reviews.llvm.org/D48522 Files: lib/StaticAnalyzer/Checkers/AllocationState.h lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp lib/StaticAnalyzer/Checkers/MallocChecker.cpp test/Analysis/dangling-internal-buffer.cpp Index: test/Analysis/dangling-internal-buffer.cpp === --- test/Analysis/dangling-internal-buffer.cpp +++ test/Analysis/dangling-internal-buffer.cpp @@ -25,17 +25,29 @@ const char *c; { std::string s; -c = s.c_str(); +c = s.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} + } // expected-note {{Internal buffer is released because the object was destroyed}} + consume(c); // expected-warning {{Use of memory after it is freed}} + // expected-note@-1 {{Use of memory after it is freed}} +} + +void deref_after_scope_char2() { + const char *c; + { +std::string s; +c = s.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::string s; + const char *c2 = s.c_str(); consume(c); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } void deref_after_scope_wchar_t() { const wchar_t *w; { std::wstring ws; -w = ws.c_str(); +w = ws.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} consume(w); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} @@ -45,7 +57,7 @@ const char16_t *c16; { std::u16string s16; -c16 = s16.c_str(); +c16 = s16.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} consume(c16); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} @@ -55,7 +67,7 @@ const char32_t *c32; { std::u32string s32; -c32 = s32.c_str(); +c32 = s32.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} consume(c32); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} Index: lib/StaticAnalyzer/Checkers/MallocChecker.cpp === --- lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -1994,6 +1994,11 @@ R->markInteresting(Sym); R->addRange(Range); R->addVisitor(llvm::make_unique(Sym)); + +const RefState *RS = C.getState()->get(Sym); +if (RS->getAllocationFamily() == AF_InternalBuffer) + R->addVisitor(allocation_state::getDanglingBufferBRVisitor(Sym)); + C.emitReport(std::move(R)); } } Index: lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp === --- lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp +++ lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp @@ -7,30 +7,67 @@ // //===--===// // -// This file defines a check that marks a raw pointer to a C++ standard library -// container's inner buffer released when the object is destroyed. This -// information can be used by MallocChecker to detect use-after-free problems. +// This file defines a check that marks a raw pointer to a C++ container's +// inner buffer released when the object is destroyed. This information can +// be used by MallocChecker to detect use-after-free problems. // //===--===// +#include "AllocationState.h" #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" -#include "AllocationState.h" using namespace clang; using namespace ento; +// FIXME: c_str() may be called on a string object many times, so it should +// have a list of symbols associated with it. +REGISTER_MAP_WITH_PROGRAMSTATE(RawPtrMap, const MemRegion *, SymbolRef) + namespace { -class DanglingInternalBufferChecker : public Checker { +class DanglingInternalBufferChecker +: public Checker {
[PATCH] D48532: [analyzer] Add support for std::basic_string::data() in DanglingInternalBufferChecker
rnkovacs created this revision. rnkovacs added reviewers: NoQ, xazax.hun, george.karpenkov, dcoughlin. Herald added subscribers: mikhail.ramalho, a.sidorin, dkrupp, szepet, baloghadamsoftware, whisperity. + Cleaned up test file a bit. Repository: rC Clang https://reviews.llvm.org/D48532 Files: lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp test/Analysis/dangling-internal-buffer.cpp Index: test/Analysis/dangling-internal-buffer.cpp === --- test/Analysis/dangling-internal-buffer.cpp +++ test/Analysis/dangling-internal-buffer.cpp @@ -7,6 +7,7 @@ public: ~basic_string(); const CharT *c_str(); + const CharT *data(); }; typedef basic_string string; @@ -21,63 +22,92 @@ void consume(const char16_t *) {} void consume(const char32_t *) {} -void deref_after_scope_char() { +void deref_after_scope_char_cstr() { const char *c; { std::string s; c = s.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::string s; + const char *c2 = s.c_str(); consume(c); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_char2() { +void deref_after_scope_char_data() { const char *c; { std::string s; -c = s.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} +c = s.data(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} std::string s; - const char *c2 = s.c_str(); + const char *c2 = s.data(); consume(c); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_wchar_t() { +void deref_after_scope_wchar_t_cstr() { const wchar_t *w; { std::wstring ws; w = ws.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::wstring ws; + const wchar_t *w2 = ws.c_str(); consume(w); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_char16_t() { +void deref_after_scope_wchar_t_data() { + const wchar_t *w; + { +std::wstring ws; +w = ws.data(); // expected-note {{Pointer to dangling buffer was obtained here}} + } // expected-note {{Internal buffer is released because the object was destroyed}} + std::wstring ws; + const wchar_t *w2 = ws.data(); + consume(w); // expected-warning {{Use of memory after it is freed}} + // expected-note@-1 {{Use of memory after it is freed}} +} + +void deref_after_scope_char16_t_cstr() { const char16_t *c16; { std::u16string s16; c16 = s16.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::u16string s16; + const char16_t *c16_2 = s16.c_str(); consume(c16); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_char32_t() { +void deref_after_scope_char32_t_data() { const char32_t *c32; { std::u32string s32; -c32 = s32.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} +c32 = s32.data(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::u32string s32; + const char32_t *c32_2 = s32.data(); consume(c32); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_ok() { +void deref_after_scope_cstr_ok() { const char *c; std::string s; { c = s.c_str(); } consume(c); // no-warning } + +void deref_after_scope_data_ok() { + const char *c; + std::string s; + { +c = s.data(); + } + consume(c); // no-warning +} Index: lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp === --- lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp +++ lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp @@ -24,15 +24,16 @@ using namespace clang; using namespace ento; -// FIXME: c_str() may be called on a string object many times, so it should -// have a list of symbols associated with it. +// FIXME: member functions that return a pointer to the container's internal +// buffer may be called on the object many times, so the object's memory +// region should have a list of pointer symbols associated with it. REGISTER_MAP_WITH_PROGRAMSTATE(RawPtrMap, const MemRegion *, S
[PATCH] D47459: [ASTImporter] Eliminated some unittest warnings.
balazske updated this revision to Diff 152632. balazske added a comment. [ASTImporter] Fixed test code in ASTImporter tests. Reformatted some test code, changed to use isDescendant. Repository: rC Clang https://reviews.llvm.org/D47459 Files: unittests/AST/ASTImporterTest.cpp Index: unittests/AST/ASTImporterTest.cpp === --- unittests/AST/ASTImporterTest.cpp +++ unittests/AST/ASTImporterTest.cpp @@ -427,138 +427,110 @@ TEST(ImportExpr, ImportStringLiteral) { MatchVerifier Verifier; - testImport("void declToImport() { \"foo\"; }", - Lang_CXX, "", Lang_CXX, Verifier, - functionDecl( - hasBody( - compoundStmt( - has( - stringLiteral( - hasType( - asString("const char [4]"; - testImport("void declToImport() { L\"foo\"; }", - Lang_CXX, "", Lang_CXX, Verifier, - functionDecl( - hasBody( - compoundStmt( - has( - stringLiteral( - hasType( -asString("const wchar_t [4]"; - testImport("void declToImport() { \"foo\" \"bar\"; }", - Lang_CXX, "", Lang_CXX, Verifier, - functionDecl( - hasBody( - compoundStmt( - has( - stringLiteral( - hasType( - asString("const char [7]"; + testImport( + "void declToImport() { (void)\"foo\"; }", + Lang_CXX, "", Lang_CXX, Verifier, + functionDecl(hasDescendant( + stringLiteral(hasType(asString("const char [4]")); + testImport( + "void declToImport() { (void)L\"foo\"; }", + Lang_CXX, "", Lang_CXX, Verifier, + functionDecl(hasDescendant( + stringLiteral(hasType(asString("const wchar_t [4]")); + testImport( + "void declToImport() { (void) \"foo\" \"bar\"; }", + Lang_CXX, "", Lang_CXX, Verifier, + functionDecl(hasDescendant( + stringLiteral(hasType(asString("const char [7]")); } TEST(ImportExpr, ImportGNUNullExpr) { MatchVerifier Verifier; - testImport("void declToImport() { __null; }", - Lang_CXX, "", Lang_CXX, Verifier, - functionDecl( - hasBody( - compoundStmt( - has( - gnuNullExpr( - hasType(isInteger(; + testImport( + "void declToImport() { (void)__null; }", + Lang_CXX, "", Lang_CXX, Verifier, + functionDecl(hasDescendant(gnuNullExpr(hasType(isInteger()); } TEST(ImportExpr, ImportCXXNullPtrLiteralExpr) { MatchVerifier Verifier; - testImport("void declToImport() { nullptr; }", - Lang_CXX11, "", Lang_CXX11, Verifier, - functionDecl( - hasBody( - compoundStmt( - has( - cxxNullPtrLiteralExpr()); + testImport( + "void declToImport() { (void)nullptr; }", + Lang_CXX11, "", Lang_CXX11, Verifier, + functionDecl(hasDescendant(cxxNullPtrLiteralExpr(; } TEST(ImportExpr, ImportFloatinglLiteralExpr) { MatchVerifier Verifier; - testImport("void declToImport() { 1.0; }", - Lang_C, "", Lang_C, Verifier, - functionDecl( - hasBody( - compoundStmt( - has( - floatLiteral( - equals(1.0), - hasType(asString("double"; - testImport("void declToImport() { 1.0e-5f; }", - Lang_C, "", Lang_C, Verifier, - functionDecl( -hasBody( - compoundStmt( -has( - floatLiteral( -equals(1.0e-5f), -hasType(asString("float"; + testImport( + "void declToImport() { (void)1.0; }", + Lang_C, "", Lang_C, Verifier, + functionDecl(hasDescendant( + floatLiteral(equals(1.0), hasType(asString("double")); + testImport( + "void declToImport() { (void)1.0e-5f; }", + Lang_C, "", Lang_C, Verifier, + functionDecl(hasDescendant( + floatLiteral(equals(1.0e-5f), hasType(asString("float")); } TEST(ImportExpr, ImportCompoundLiteralExpr) { MatchVerifier Verifier; - testImport("void declToImport() {" - " struct s { int x; long y; unsigned z; }; " - " (struct s){ 42, 0L, 1U }; }", - Lang_CXX, "", Lang_CXX, Verifier, - functionDecl( - hasBody( - compoundStmt( - has( - compoundLiteralExpr( - hasType(asString("struct s")), - has(initListExpr( -
[PATCH] D47459: [ASTImporter] Eliminated some unittest warnings.
balazske marked 2 inline comments as done. balazske added a comment. Some of the source code was reformatted for more consistency. At least a part of the code is now better formatted. Repository: rC Clang https://reviews.llvm.org/D47459 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47698: [ASTImporter] import macro source locations
r.stahl updated this revision to Diff 152633. r.stahl marked 5 inline comments as done. r.stahl added a comment. improved code quality; added nested macro test. it "works", but is disabled because it revealed another bug: the function end location is not imported. will send a patch Repository: rC Clang https://reviews.llvm.org/D47698 Files: lib/AST/ASTImporter.cpp unittests/AST/ASTImporterTest.cpp Index: unittests/AST/ASTImporterTest.cpp === --- unittests/AST/ASTImporterTest.cpp +++ unittests/AST/ASTImporterTest.cpp @@ -1518,6 +1518,66 @@ ToTU, cxxRecordDecl(unless(isImplicit(); } +static void CompareSourceLocs(FullSourceLoc Loc1, FullSourceLoc Loc2) { + EXPECT_EQ(Loc1.getExpansionLineNumber(), Loc2.getExpansionLineNumber()); + EXPECT_EQ(Loc1.getExpansionColumnNumber(), Loc2.getExpansionColumnNumber()); + EXPECT_EQ(Loc1.getSpellingLineNumber(), Loc2.getSpellingLineNumber()); + EXPECT_EQ(Loc1.getSpellingColumnNumber(), Loc2.getSpellingColumnNumber()); +} +static void CompareSourceRanges(SourceRange Range1, SourceRange Range2, +SourceManager &SM1, SourceManager &SM2) { + CompareSourceLocs(FullSourceLoc{ Range1.getBegin(), SM1 }, +FullSourceLoc{ Range2.getBegin(), SM2 }); + CompareSourceLocs(FullSourceLoc{ Range1.getEnd(), SM1 }, +FullSourceLoc{ Range2.getEnd(), SM2 }); +} +TEST_P(ASTImporterTestBase, ImportSourceLocs) { + Decl *FromTU = getTuDecl( + R"( + #define MFOO(arg) arg = arg + 1 + + void foo() { +int a = 5; +MFOO(a); + } + )", + Lang_CXX); + auto FromD = FirstDeclMatcher().match(FromTU, functionDecl()); + auto ToD = Import(FromD, Lang_CXX); + + auto ToLHS = LastDeclMatcher().match(ToD, declRefExpr()); + auto FromLHS = LastDeclMatcher().match(FromTU, declRefExpr()); + auto ToRHS = LastDeclMatcher().match(ToD, integerLiteral()); + auto FromRHS = + LastDeclMatcher().match(FromTU, integerLiteral()); + + SourceManager &ToSM = ToAST->getASTContext().getSourceManager(); + SourceManager &FromSM = FromD->getASTContext().getSourceManager(); + CompareSourceRanges(ToD->getSourceRange(), FromD->getSourceRange(), ToSM, + FromSM); + CompareSourceRanges(ToLHS->getSourceRange(), FromLHS->getSourceRange(), ToSM, + FromSM); + CompareSourceRanges(ToRHS->getSourceRange(), FromRHS->getSourceRange(), ToSM, + FromSM); +} + +TEST_P(ASTImporterTestBase, DISABLED_ImportNestedMacro) { + Decl *FromTU = getTuDecl( + R"( + #define FUNC_INT void declToImport + #define FUNC FUNC_INT + FUNC(int a); + )", + Lang_CXX); + auto FromD = FirstDeclMatcher().match(FromTU, functionDecl()); + auto ToD = Import(FromD, Lang_CXX); + + SourceManager &ToSM = ToAST->getASTContext().getSourceManager(); + SourceManager &FromSM = FromD->getASTContext().getSourceManager(); + CompareSourceRanges(ToD->getSourceRange(), FromD->getSourceRange(), ToSM, + FromSM); +} + TEST_P( ASTImporterTestBase, ImportDefinitionOfClassTemplateSpecIfThereIsAnExistingFwdDeclAndDefinition) Index: lib/AST/ASTImporter.cpp === --- lib/AST/ASTImporter.cpp +++ lib/AST/ASTImporter.cpp @@ -7029,61 +7029,70 @@ return {}; SourceManager &FromSM = FromContext.getSourceManager(); - - // For now, map everything down to its file location, so that we - // don't have to import macro expansions. - // FIXME: Import macro expansions! - FromLoc = FromSM.getFileLoc(FromLoc); + std::pair Decomposed = FromSM.getDecomposedLoc(FromLoc); - SourceManager &ToSM = ToContext.getSourceManager(); FileID ToFileID = Import(Decomposed.first); if (ToFileID.isInvalid()) return {}; - SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID) - .getLocWithOffset(Decomposed.second); - return ret; + SourceManager &ToSM = ToContext.getSourceManager(); + return ToSM.getComposedLoc(ToFileID, Decomposed.second); } SourceRange ASTImporter::Import(SourceRange FromRange) { return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd())); } FileID ASTImporter::Import(FileID FromID) { - llvm::DenseMap::iterator Pos -= ImportedFileIDs.find(FromID); + llvm::DenseMap::iterator Pos = ImportedFileIDs.find(FromID); if (Pos != ImportedFileIDs.end()) return Pos->second; - + SourceManager &FromSM = FromContext.getSourceManager(); SourceManager &ToSM = ToContext.getSourceManager(); const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID); - assert(FromSLoc.isFile() && "Cannot handle macro expansions yet"); - - // Include location of this file. - SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc()); - - // Map the FileID for to the "to" source manager. + + // Map
[PATCH] D47698: [ASTImporter] import macro source locations
r.stahl marked an inline comment as done. r.stahl added inline comments. Comment at: lib/AST/ASTImporter.cpp:7058 +const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion(); +SourceLocation ToSpLoc = Import(FromEx.getSpellingLoc()); +SourceLocation ToExLocS = Import(FromEx.getExpansionLocStart()); a.sidorin wrote: > r.stahl wrote: > > martong wrote: > > > Let's say we import a `SourceLocation` with > > > `ASTImporter::Import(SourceLocation FromLoc)`. > > > That calls into `ASTImporter::Import(FileID FromID)` where we again > > > import other source locations. > > > Could the initial `FromLoc` be equal with any of these locations > > > (`FromEx.getSpellingLoc()`, `FromEx.getExpansionLocStart()`) ? > > > My understanding is that this is not possible because we cannot have > > > recursive macros, but please confirm. > > Yes, that was my understanding as well. If some compiler error is a macro > > expansion it eventually stops at some point while walking this chain. > If we have a macro referring another macro in the same file, will we import > their FileID twice? First, during `Import(getSpellingLoc())` and then in this > caller? That is taken care of by the ImportedFileIDs check. Repository: rC Clang https://reviews.llvm.org/D47698 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47450: [ASTImporter] Use InjectedClassNameType at import of templated record.
balazske updated this revision to Diff 152634. balazske added a comment. Small fixes. Repository: rC Clang https://reviews.llvm.org/D47450 Files: lib/AST/ASTImporter.cpp test/ASTMerge/injected-class-name-decl/Inputs/inject1.cpp test/ASTMerge/injected-class-name-decl/Inputs/inject2.cpp test/ASTMerge/injected-class-name-decl/test.cpp Index: test/ASTMerge/injected-class-name-decl/test.cpp === --- /dev/null +++ test/ASTMerge/injected-class-name-decl/test.cpp @@ -0,0 +1,3 @@ +// RUN: %clang_cc1 -std=c++1z -emit-pch -o %t.ast %S/Inputs/inject1.cpp +// RUN: %clang_cc1 -std=c++1z -emit-obj -o /dev/null -ast-merge %t.ast %S/Inputs/inject2.cpp +// expected-no-diagnostics Index: test/ASTMerge/injected-class-name-decl/Inputs/inject2.cpp === --- /dev/null +++ test/ASTMerge/injected-class-name-decl/Inputs/inject2.cpp @@ -0,0 +1,2 @@ +template +X C::x; Index: test/ASTMerge/injected-class-name-decl/Inputs/inject1.cpp === --- /dev/null +++ test/ASTMerge/injected-class-name-decl/Inputs/inject1.cpp @@ -0,0 +1,2 @@ +template +class C { static X x; }; Index: lib/AST/ASTImporter.cpp === --- lib/AST/ASTImporter.cpp +++ lib/AST/ASTImporter.cpp @@ -2128,6 +2128,29 @@ if (!ToDescribed) return nullptr; D2CXX->setDescribedClassTemplate(ToDescribed); +if (!DCXX->isInjectedClassName()) { + // In a record describing a template the type should be an + // InjectedClassNameType (see Sema::CheckClassTemplate). Update the + // previously set type to the correct value here (ToDescribed is not + // available at record create). + // FIXME: The previous type is cleared but not removed from + // ASTContext's internal storage. + CXXRecordDecl *Injected = nullptr; + for (NamedDecl *Found : D2CXX->noload_lookup(Name)) { +auto *Record = dyn_cast(Found); +if (Record && Record->isInjectedClassName()) { + Injected = Record; + break; +} + } + D2CXX->setTypeForDecl(nullptr); + Importer.getToContext().getInjectedClassNameType(D2CXX, + ToDescribed->getInjectedClassNameSpecialization()); + if (Injected) { +Injected->setTypeForDecl(nullptr); +Importer.getToContext().getTypeDeclType(Injected, D2CXX); + } +} } else if (MemberSpecializationInfo *MemberInfo = DCXX->getMemberSpecializationInfo()) { TemplateSpecializationKind SK = Index: test/ASTMerge/injected-class-name-decl/test.cpp === --- /dev/null +++ test/ASTMerge/injected-class-name-decl/test.cpp @@ -0,0 +1,3 @@ +// RUN: %clang_cc1 -std=c++1z -emit-pch -o %t.ast %S/Inputs/inject1.cpp +// RUN: %clang_cc1 -std=c++1z -emit-obj -o /dev/null -ast-merge %t.ast %S/Inputs/inject2.cpp +// expected-no-diagnostics Index: test/ASTMerge/injected-class-name-decl/Inputs/inject2.cpp === --- /dev/null +++ test/ASTMerge/injected-class-name-decl/Inputs/inject2.cpp @@ -0,0 +1,2 @@ +template +X C::x; Index: test/ASTMerge/injected-class-name-decl/Inputs/inject1.cpp === --- /dev/null +++ test/ASTMerge/injected-class-name-decl/Inputs/inject1.cpp @@ -0,0 +1,2 @@ +template +class C { static X x; }; Index: lib/AST/ASTImporter.cpp === --- lib/AST/ASTImporter.cpp +++ lib/AST/ASTImporter.cpp @@ -2128,6 +2128,29 @@ if (!ToDescribed) return nullptr; D2CXX->setDescribedClassTemplate(ToDescribed); +if (!DCXX->isInjectedClassName()) { + // In a record describing a template the type should be an + // InjectedClassNameType (see Sema::CheckClassTemplate). Update the + // previously set type to the correct value here (ToDescribed is not + // available at record create). + // FIXME: The previous type is cleared but not removed from + // ASTContext's internal storage. + CXXRecordDecl *Injected = nullptr; + for (NamedDecl *Found : D2CXX->noload_lookup(Name)) { +auto *Record = dyn_cast(Found); +if (Record && Record->isInjectedClassName()) { + Injected = Record; + break; +} + } + D2CXX->setTypeForDecl(nullptr); + Importer.getToContext().getInjectedClassNameType(D2CXX, + ToDescribed->getInjectedClassNameSpecialization()); + if (Injected) { +Injected->setTypeForDecl(nullptr); +Importer.getToContex
[PATCH] D48492: [clang-format] Add a default format style that can be used by users of `getStyle`
ioeric updated this revision to Diff 152636. ioeric marked an inline comment as done. ioeric added a comment. - Add DefaultFallbackStyle Repository: rC Clang https://reviews.llvm.org/D48492 Files: include/clang/Format/Format.h lib/Format/Format.cpp tools/clang-format/ClangFormat.cpp Index: tools/clang-format/ClangFormat.cpp === --- tools/clang-format/ClangFormat.cpp +++ tools/clang-format/ClangFormat.cpp @@ -60,17 +60,18 @@ "Can only be used with one input file."), cl::cat(ClangFormatCategory)); static cl::opt -Style("style", - cl::desc(clang::format::StyleOptionHelpDescription), - cl::init("file"), cl::cat(ClangFormatCategory)); +Style("style", cl::desc(clang::format::StyleOptionHelpDescription), + cl::init(clang::format::DefaultFormatStyle), + cl::cat(ClangFormatCategory)); static cl::opt -FallbackStyle("fallback-style", - cl::desc("The name of the predefined style used as a\n" - "fallback in case clang-format is invoked with\n" - "-style=file, but can not find the .clang-format\n" - "file to use.\n" - "Use -fallback-style=none to skip formatting."), - cl::init("LLVM"), cl::cat(ClangFormatCategory)); +FallbackStyle("fallback-style", + cl::desc("The name of the predefined style used as a\n" + "fallback in case clang-format is invoked with\n" + "-style=file, but can not find the .clang-format\n" + "file to use.\n" + "Use -fallback-style=none to skip formatting."), + cl::init(clang::format::DefaultFallbackStyle), + cl::cat(ClangFormatCategory)); static cl::opt AssumeFileName("assume-filename", Index: lib/Format/Format.cpp === --- lib/Format/Format.cpp +++ lib/Format/Format.cpp @@ -2144,6 +2144,10 @@ return GuessedLanguage; } +const char *DefaultFormatStyle = "file"; + +const char *DefaultFallbackStyle = "LLVM"; + llvm::Expected getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName, StringRef Code, vfs::FileSystem *FS) { Index: include/clang/Format/Format.h === --- include/clang/Format/Format.h +++ include/clang/Format/Format.h @@ -1963,6 +1963,15 @@ /// of ``getStyle()``. extern const char *StyleOptionHelpDescription; +/// The suggested format style to use by default. This allows tools using +/// `getStyle` to have a consistent default style. +/// Different builds can modify the value to the preferred styles. +extern const char *DefaultFormatStyle; + +/// The suggested predefined style to use as the fallback style in `getStyle`. +/// Different builds can modify the value to the preferred styles. +extern const char *DefaultFallbackStyle; + /// Construct a FormatStyle based on ``StyleName``. /// /// ``StyleName`` can take several forms: Index: tools/clang-format/ClangFormat.cpp === --- tools/clang-format/ClangFormat.cpp +++ tools/clang-format/ClangFormat.cpp @@ -60,17 +60,18 @@ "Can only be used with one input file."), cl::cat(ClangFormatCategory)); static cl::opt -Style("style", - cl::desc(clang::format::StyleOptionHelpDescription), - cl::init("file"), cl::cat(ClangFormatCategory)); +Style("style", cl::desc(clang::format::StyleOptionHelpDescription), + cl::init(clang::format::DefaultFormatStyle), + cl::cat(ClangFormatCategory)); static cl::opt -FallbackStyle("fallback-style", - cl::desc("The name of the predefined style used as a\n" - "fallback in case clang-format is invoked with\n" - "-style=file, but can not find the .clang-format\n" - "file to use.\n" - "Use -fallback-style=none to skip formatting."), - cl::init("LLVM"), cl::cat(ClangFormatCategory)); +FallbackStyle("fallback-style", + cl::desc("The name of the predefined style used as a\n" + "fallback in case clang-format is invoked with\n" + "-style=file, but can not find the .clang-format\n" + "file to use.\n" + "Use -fallback-style=none to skip formatting."), + cl::init(clang::format::DefaultFallbackStyle), + cl::cat(ClangFormatCategory)); static cl::opt AssumeFileName("assume-filename", Index: lib/Format/Format.cpp ===
[PATCH] D48492: [clang-format] Add a default format style that can be used by users of `getStyle`
ioeric added inline comments. Comment at: tools/clang-format/ClangFormat.cpp:67 static cl::opt FallbackStyle("fallback-style", cl::desc("The name of the predefined style used as a\n" sammccall wrote: > My only question is if we want to do the same with DefaultFallbackStyle. > > Not because we have a use case for changing it right now, but because it's > another string that callers of getStyle() have to hard-code. In our internal > codebase, some pass "LLVM", some pass "Google", and some make it an option. Can't see a reason not to. This should help get rid of more hardcode. Repository: rC Clang https://reviews.llvm.org/D48492 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D46013: [ARM] Conform to AAPCS when passing overaligned composites as arguments
chill added a comment. In https://reviews.llvm.org/D46013#1140336, @t.p.northover wrote: > I'm fine with the ABI changes, but I'm not very convinced by the > "NaturalAlignment" name. I'd rather not put target names in API functions. The meaning of that field is pretty target independent ("alignment of type, before alignment adjustments") If we use it only in ARM/AArch64 we can put a comment in that sense and maybe rename it to `UnadjustedAlignement` or something else more descriptive than `NaturalAlignement` ? https://reviews.llvm.org/D46013 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D46013: [ARM] Conform to AAPCS when passing overaligned composites as arguments
chill added inline comments. Comment at: lib/CodeGen/TargetInfo.cpp:5055 + Alignment = getContext().getTypeNaturalAlign(Ty); + Alignment = std::min(std::max(Alignment, 64u), 128u); +} else { t.p.northover wrote: > I think the max/min logic is more confusing here than the alternative: > > Alignment = Alignment < 128 ? 64 : 128; I'll change it. https://reviews.llvm.org/D46013 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D46013: [ARM] Conform to AAPCS when passing overaligned composites as arguments
t.p.northover added a comment. > I'd rather not put target names in API functions. The meaning of that field > is pretty target independent ("alignment of type, before alignment > adjustments") Except that rule only applies to aggregates. Scalar types get their alignment adjusted anyway I believe. The definition is ridiculously arbitrary. > If we use it only in ARM/AArch64 we can put a comment in that sense and maybe > rename it to `UnadjustedAlignement` or something else more descriptive than > `NaturalAlignement`? I could just about live with that (or `UnnaturalAlignment`, though perhaps best not). https://reviews.llvm.org/D46013 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48539: [clang-format] Fix end-of-file comments text proto formatting
krasimir created this revision. Herald added a subscriber: cfe-commits. The case of end-of-file comments was formatted badly: key: value # end-of-file comment This patch fixes that formatting: key: value # end-of-file comment Repository: rC Clang https://reviews.llvm.org/D48539 Files: lib/Format/UnwrappedLineParser.cpp unittests/Format/FormatTestTextProto.cpp Index: unittests/Format/FormatTestTextProto.cpp === --- unittests/Format/FormatTestTextProto.cpp +++ unittests/Format/FormatTestTextProto.cpp @@ -700,5 +700,22 @@ "}"); } +TEST_F(FormatTestTextProto, FormatsCommentsAtEndOfFile) { + verifyFormat("key: value\n" + "# endfile comment"); + verifyFormat("key: value\n" + "// endfile comment"); + verifyFormat("key: value\n" + "// endfile comment 1\n" + "// endfile comment 2"); + verifyFormat("submessage { key: value }\n" + "# endfile comment"); + verifyFormat("submessage <\n" + " key: value\n" + " item {}\n" + ">\n" + "# endfile comment"); +} + } // end namespace tooling } // end namespace clang Index: lib/Format/UnwrappedLineParser.cpp === --- lib/Format/UnwrappedLineParser.cpp +++ lib/Format/UnwrappedLineParser.cpp @@ -303,6 +303,18 @@ else parseLevel(/*HasOpeningBrace=*/false); // Make sure to format the remaining tokens. + // + // LK_TextProto is special since its top-level is parsed as the body of a + // braced list, which does not necessarily have natural line separators such + // as a semicolon. Comments after the last entry that have been determined to + // not belong to that line, as in: + // key: value + // // endfile comment + // do not have a chance to be put on a line of their own until this point. + // Here we add this newline before end-of-file comments. + if (Style.Language == FormatStyle::LK_TextProto && + !CommentsBeforeNextToken.empty()) +addUnwrappedLine(); flushComments(true); addUnwrappedLine(); } Index: unittests/Format/FormatTestTextProto.cpp === --- unittests/Format/FormatTestTextProto.cpp +++ unittests/Format/FormatTestTextProto.cpp @@ -700,5 +700,22 @@ "}"); } +TEST_F(FormatTestTextProto, FormatsCommentsAtEndOfFile) { + verifyFormat("key: value\n" + "# endfile comment"); + verifyFormat("key: value\n" + "// endfile comment"); + verifyFormat("key: value\n" + "// endfile comment 1\n" + "// endfile comment 2"); + verifyFormat("submessage { key: value }\n" + "# endfile comment"); + verifyFormat("submessage <\n" + " key: value\n" + " item {}\n" + ">\n" + "# endfile comment"); +} + } // end namespace tooling } // end namespace clang Index: lib/Format/UnwrappedLineParser.cpp === --- lib/Format/UnwrappedLineParser.cpp +++ lib/Format/UnwrappedLineParser.cpp @@ -303,6 +303,18 @@ else parseLevel(/*HasOpeningBrace=*/false); // Make sure to format the remaining tokens. + // + // LK_TextProto is special since its top-level is parsed as the body of a + // braced list, which does not necessarily have natural line separators such + // as a semicolon. Comments after the last entry that have been determined to + // not belong to that line, as in: + // key: value + // // endfile comment + // do not have a chance to be put on a line of their own until this point. + // Here we add this newline before end-of-file comments. + if (Style.Language == FormatStyle::LK_TextProto && + !CommentsBeforeNextToken.empty()) +addUnwrappedLine(); flushComments(true); addUnwrappedLine(); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D45719: [clang-Format] Fix indentation of member call after block
ank added a comment. Is there any chance to get this change or a similar one in so we get same behaviour as in release_40, even though it does not correct all of the problems? Repository: rC Clang https://reviews.llvm.org/D45719 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r335449 - [clang-format] Fix end-of-file comments text proto formatting
Author: krasimir Date: Mon Jun 25 04:08:24 2018 New Revision: 335449 URL: http://llvm.org/viewvc/llvm-project?rev=335449&view=rev Log: [clang-format] Fix end-of-file comments text proto formatting Summary: The case of end-of-file comments was formatted badly: ``` key: value # end-of-file comment ``` This patch fixes that formatting: ``` key: value # end-of-file comment ``` Subscribers: cfe-commits Differential Revision: https://reviews.llvm.org/D48539 Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp cfe/trunk/unittests/Format/FormatTestTextProto.cpp Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=335449&r1=335448&r2=335449&view=diff == --- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original) +++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Mon Jun 25 04:08:24 2018 @@ -303,6 +303,18 @@ void UnwrappedLineParser::parseFile() { else parseLevel(/*HasOpeningBrace=*/false); // Make sure to format the remaining tokens. + // + // LK_TextProto is special since its top-level is parsed as the body of a + // braced list, which does not necessarily have natural line separators such + // as a semicolon. Comments after the last entry that have been determined to + // not belong to that line, as in: + // key: value + // // endfile comment + // do not have a chance to be put on a line of their own until this point. + // Here we add this newline before end-of-file comments. + if (Style.Language == FormatStyle::LK_TextProto && + !CommentsBeforeNextToken.empty()) +addUnwrappedLine(); flushComments(true); addUnwrappedLine(); } Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=335449&r1=335448&r2=335449&view=diff == --- cfe/trunk/unittests/Format/FormatTestTextProto.cpp (original) +++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp Mon Jun 25 04:08:24 2018 @@ -700,5 +700,22 @@ TEST_F(FormatTestTextProto, PreventBreak "}"); } +TEST_F(FormatTestTextProto, FormatsCommentsAtEndOfFile) { + verifyFormat("key: value\n" + "# endfile comment"); + verifyFormat("key: value\n" + "// endfile comment"); + verifyFormat("key: value\n" + "// endfile comment 1\n" + "// endfile comment 2"); + verifyFormat("submessage { key: value }\n" + "# endfile comment"); + verifyFormat("submessage <\n" + " key: value\n" + " item {}\n" + ">\n" + "# endfile comment"); +} + } // end namespace tooling } // end namespace clang ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48539: [clang-format] Fix end-of-file comments text proto formatting
This revision was not accepted when it landed; it landed in state "Needs Review". This revision was automatically updated to reflect the committed changes. Closed by commit rL335449: [clang-format] Fix end-of-file comments text proto formatting (authored by krasimir, committed by ). Herald added a subscriber: llvm-commits. Repository: rL LLVM https://reviews.llvm.org/D48539 Files: cfe/trunk/lib/Format/UnwrappedLineParser.cpp cfe/trunk/unittests/Format/FormatTestTextProto.cpp Index: cfe/trunk/lib/Format/UnwrappedLineParser.cpp === --- cfe/trunk/lib/Format/UnwrappedLineParser.cpp +++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp @@ -303,6 +303,18 @@ else parseLevel(/*HasOpeningBrace=*/false); // Make sure to format the remaining tokens. + // + // LK_TextProto is special since its top-level is parsed as the body of a + // braced list, which does not necessarily have natural line separators such + // as a semicolon. Comments after the last entry that have been determined to + // not belong to that line, as in: + // key: value + // // endfile comment + // do not have a chance to be put on a line of their own until this point. + // Here we add this newline before end-of-file comments. + if (Style.Language == FormatStyle::LK_TextProto && + !CommentsBeforeNextToken.empty()) +addUnwrappedLine(); flushComments(true); addUnwrappedLine(); } Index: cfe/trunk/unittests/Format/FormatTestTextProto.cpp === --- cfe/trunk/unittests/Format/FormatTestTextProto.cpp +++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp @@ -700,5 +700,22 @@ "}"); } +TEST_F(FormatTestTextProto, FormatsCommentsAtEndOfFile) { + verifyFormat("key: value\n" + "# endfile comment"); + verifyFormat("key: value\n" + "// endfile comment"); + verifyFormat("key: value\n" + "// endfile comment 1\n" + "// endfile comment 2"); + verifyFormat("submessage { key: value }\n" + "# endfile comment"); + verifyFormat("submessage <\n" + " key: value\n" + " item {}\n" + ">\n" + "# endfile comment"); +} + } // end namespace tooling } // end namespace clang Index: cfe/trunk/lib/Format/UnwrappedLineParser.cpp === --- cfe/trunk/lib/Format/UnwrappedLineParser.cpp +++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp @@ -303,6 +303,18 @@ else parseLevel(/*HasOpeningBrace=*/false); // Make sure to format the remaining tokens. + // + // LK_TextProto is special since its top-level is parsed as the body of a + // braced list, which does not necessarily have natural line separators such + // as a semicolon. Comments after the last entry that have been determined to + // not belong to that line, as in: + // key: value + // // endfile comment + // do not have a chance to be put on a line of their own until this point. + // Here we add this newline before end-of-file comments. + if (Style.Language == FormatStyle::LK_TextProto && + !CommentsBeforeNextToken.empty()) +addUnwrappedLine(); flushComments(true); addUnwrappedLine(); } Index: cfe/trunk/unittests/Format/FormatTestTextProto.cpp === --- cfe/trunk/unittests/Format/FormatTestTextProto.cpp +++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp @@ -700,5 +700,22 @@ "}"); } +TEST_F(FormatTestTextProto, FormatsCommentsAtEndOfFile) { + verifyFormat("key: value\n" + "# endfile comment"); + verifyFormat("key: value\n" + "// endfile comment"); + verifyFormat("key: value\n" + "// endfile comment 1\n" + "// endfile comment 2"); + verifyFormat("submessage { key: value }\n" + "# endfile comment"); + verifyFormat("submessage <\n" + " key: value\n" + " item {}\n" + ">\n" + "# endfile comment"); +} + } // end namespace tooling } // end namespace clang ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D45719: [clang-Format] Fix indentation of member call after block
klimek added inline comments. Comment at: unittests/Format/FormatTest.cpp:4359 + "return 3;\n" + " }).as("");\n" + "}"); ank wrote: > klimek wrote: > > What would be interesting is tests that: > > a) have another value after the closing }; doesn't really make sense in > > this test, but usually these are in calls > > f([]() { ... }, foo, bar).call(...) > > > > b) make .as("") have paramters that go beyond the limit > > > > c) add another chained call behind .as(""). > Hello, sorry for the late follow up on this! > > Indeed an interesting thing to test, and so I did, the patterns you describe > seems to give strange indentation as far back as release_36 and probably has > always done so. The case I'm testing here worked in release_40 but stopped > working somewhere before release_50 > > maybe fixing those other cases can be done in another patch > > cheers, > Anders I meant: please add these tests :) Repository: rC Clang https://reviews.llvm.org/D45719 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47534: [ASTImporter] Add new tests about templated-described swing
martong updated this revision to Diff 152660. martong marked 2 inline comments as done. martong added a comment. - Clang format the test code snippet. Repository: rC Clang https://reviews.llvm.org/D47534 Files: unittests/AST/ASTImporterTest.cpp Index: unittests/AST/ASTImporterTest.cpp === --- unittests/AST/ASTImporterTest.cpp +++ unittests/AST/ASTImporterTest.cpp @@ -1095,6 +1095,20 @@ unless(has(cxxRecordDecl(hasName("declToImport"; } +TEST(ImportDecl, ImportClassTemplatePartialSpecialization) { + MatchVerifier Verifier; + auto Code = + R"s( + struct declToImport { +template struct X; +template struct X {}; + }; + )s"; + testImport(Code, Lang_CXX, "", Lang_CXX, Verifier, + recordDecl(has(classTemplateDecl()), +has(classTemplateSpecializationDecl(; +} + TEST(ImportExpr, CXXOperatorCallExpr) { MatchVerifier Verifier; testImport("class declToImport {" @@ -1128,6 +1142,52 @@ EXPECT_EQ(ToTemplated1, ToTemplated); } +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclOfFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX); + auto From = FirstDeclMatcher().match( + FromTU, functionTemplateDecl()); + ASSERT_TRUE(From); + auto To = cast(Import(From, Lang_CXX)); + ASSERT_TRUE(To); + Decl *ToTemplated = To->getTemplatedDecl(); + Decl *ToTemplated1 = Import(From->getTemplatedDecl(), Lang_CXX); + EXPECT_TRUE(ToTemplated1); + EXPECT_EQ(ToTemplated1, ToTemplated); +} + +TEST_P(ASTImporterTestBase, + ImportOfTemplatedDeclShouldImportTheClassTemplateDecl) { + Decl *FromTU = getTuDecl("template struct S{};", Lang_CXX); + auto FromFT = + FirstDeclMatcher().match(FromTU, classTemplateDecl()); + ASSERT_TRUE(FromFT); + + auto ToTemplated = + cast(Import(FromFT->getTemplatedDecl(), Lang_CXX)); + EXPECT_TRUE(ToTemplated); + auto ToTU = ToTemplated->getTranslationUnitDecl(); + auto ToFT = + FirstDeclMatcher().match(ToTU, classTemplateDecl()); + EXPECT_TRUE(ToFT); +} + +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclShouldImportTheFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX); + auto FromFT = FirstDeclMatcher().match( + FromTU, functionTemplateDecl()); + ASSERT_TRUE(FromFT); + + auto ToTemplated = + cast(Import(FromFT->getTemplatedDecl(), Lang_CXX)); + EXPECT_TRUE(ToTemplated); + auto ToTU = ToTemplated->getTranslationUnitDecl(); + auto ToFT = FirstDeclMatcher().match( + ToTU, functionTemplateDecl()); + EXPECT_TRUE(ToFT); +} + TEST_P(ASTImporterTestBase, ImportCorrectTemplatedDecl) { auto Code = R"( Index: unittests/AST/ASTImporterTest.cpp === --- unittests/AST/ASTImporterTest.cpp +++ unittests/AST/ASTImporterTest.cpp @@ -1095,6 +1095,20 @@ unless(has(cxxRecordDecl(hasName("declToImport"; } +TEST(ImportDecl, ImportClassTemplatePartialSpecialization) { + MatchVerifier Verifier; + auto Code = + R"s( + struct declToImport { +template struct X; +template struct X {}; + }; + )s"; + testImport(Code, Lang_CXX, "", Lang_CXX, Verifier, + recordDecl(has(classTemplateDecl()), +has(classTemplateSpecializationDecl(; +} + TEST(ImportExpr, CXXOperatorCallExpr) { MatchVerifier Verifier; testImport("class declToImport {" @@ -1128,6 +1142,52 @@ EXPECT_EQ(ToTemplated1, ToTemplated); } +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclOfFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX); + auto From = FirstDeclMatcher().match( + FromTU, functionTemplateDecl()); + ASSERT_TRUE(From); + auto To = cast(Import(From, Lang_CXX)); + ASSERT_TRUE(To); + Decl *ToTemplated = To->getTemplatedDecl(); + Decl *ToTemplated1 = Import(From->getTemplatedDecl(), Lang_CXX); + EXPECT_TRUE(ToTemplated1); + EXPECT_EQ(ToTemplated1, ToTemplated); +} + +TEST_P(ASTImporterTestBase, + ImportOfTemplatedDeclShouldImportTheClassTemplateDecl) { + Decl *FromTU = getTuDecl("template struct S{};", Lang_CXX); + auto FromFT = + FirstDeclMatcher().match(FromTU, classTemplateDecl()); + ASSERT_TRUE(FromFT); + + auto ToTemplated = + cast(Import(FromFT->getTemplatedDecl(), Lang_CXX)); + EXPECT_TRUE(ToTemplated); + auto ToTU = ToTemplated->getTranslationUnitDecl(); + auto ToFT = + FirstDeclMatcher().match(ToTU, classTemplateDecl()); + EXPECT_TRUE(ToFT); +} + +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclShouldImportTheFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX); + auto FromFT = FirstDeclMatcher().match( + FromTU, functionTemplateDecl()); + ASSERT_TRUE(FromFT); + + auto ToTempla
r335455 - [ASTImporter] Add new tests about templated-described swing
Author: martong Date: Mon Jun 25 04:38:43 2018 New Revision: 335455 URL: http://llvm.org/viewvc/llvm-project?rev=335455&view=rev Log: [ASTImporter] Add new tests about templated-described swing Summary: Add a new test about importing a partial specialization (of a class). Also, this patch adds new tests about the templated-described swing, some of these fail ATM, but subsequent patches will fix them. Reviewers: a.sidorin, r.stahl, xazax.hun Subscribers: rnkovacs, dkrupp, cfe-commits Differential Revision: https://reviews.llvm.org/D47534 Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/ASTImporterTest.cpp?rev=335455&r1=335454&r2=335455&view=diff == --- cfe/trunk/unittests/AST/ASTImporterTest.cpp (original) +++ cfe/trunk/unittests/AST/ASTImporterTest.cpp Mon Jun 25 04:38:43 2018 @@ -1095,6 +1095,20 @@ TEST(ImportDecl, ImportTemplatedDeclForT unless(has(cxxRecordDecl(hasName("declToImport"; } +TEST(ImportDecl, ImportClassTemplatePartialSpecialization) { + MatchVerifier Verifier; + auto Code = + R"s( + struct declToImport { +template struct X; +template struct X {}; + }; + )s"; + testImport(Code, Lang_CXX, "", Lang_CXX, Verifier, + recordDecl(has(classTemplateDecl()), +has(classTemplateSpecializationDecl(; +} + TEST(ImportExpr, CXXOperatorCallExpr) { MatchVerifier Verifier; testImport("class declToImport {" @@ -1128,6 +1142,52 @@ TEST_P(ASTImporterTestBase, ImportOfTemp EXPECT_EQ(ToTemplated1, ToTemplated); } +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclOfFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX); + auto From = FirstDeclMatcher().match( + FromTU, functionTemplateDecl()); + ASSERT_TRUE(From); + auto To = cast(Import(From, Lang_CXX)); + ASSERT_TRUE(To); + Decl *ToTemplated = To->getTemplatedDecl(); + Decl *ToTemplated1 = Import(From->getTemplatedDecl(), Lang_CXX); + EXPECT_TRUE(ToTemplated1); + EXPECT_EQ(ToTemplated1, ToTemplated); +} + +TEST_P(ASTImporterTestBase, + ImportOfTemplatedDeclShouldImportTheClassTemplateDecl) { + Decl *FromTU = getTuDecl("template struct S{};", Lang_CXX); + auto FromFT = + FirstDeclMatcher().match(FromTU, classTemplateDecl()); + ASSERT_TRUE(FromFT); + + auto ToTemplated = + cast(Import(FromFT->getTemplatedDecl(), Lang_CXX)); + EXPECT_TRUE(ToTemplated); + auto ToTU = ToTemplated->getTranslationUnitDecl(); + auto ToFT = + FirstDeclMatcher().match(ToTU, classTemplateDecl()); + EXPECT_TRUE(ToFT); +} + +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclShouldImportTheFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX); + auto FromFT = FirstDeclMatcher().match( + FromTU, functionTemplateDecl()); + ASSERT_TRUE(FromFT); + + auto ToTemplated = + cast(Import(FromFT->getTemplatedDecl(), Lang_CXX)); + EXPECT_TRUE(ToTemplated); + auto ToTU = ToTemplated->getTranslationUnitDecl(); + auto ToFT = FirstDeclMatcher().match( + ToTU, functionTemplateDecl()); + EXPECT_TRUE(ToFT); +} + TEST_P(ASTImporterTestBase, ImportCorrectTemplatedDecl) { auto Code = R"( ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48426: [clang-cl] Don't emit dllexport inline functions etc. from pch files (PR37801)
hans updated this revision to Diff 152659. hans added a comment. Added special-casing for explicit template instantiations, and missing test case suggested by Nico. Please take another look. https://reviews.llvm.org/D48426 Files: include/clang/AST/ExternalASTSource.h include/clang/Basic/LangOptions.def include/clang/Driver/CC1Options.td include/clang/Sema/MultiplexExternalSemaSource.h include/clang/Serialization/ASTBitCodes.h include/clang/Serialization/ASTReader.h include/clang/Serialization/Module.h lib/AST/ASTContext.cpp lib/Driver/Driver.cpp lib/Driver/ToolChains/Clang.cpp lib/Frontend/CompilerInvocation.cpp lib/Frontend/FrontendActions.cpp lib/Sema/MultiplexExternalSemaSource.cpp lib/Serialization/ASTReader.cpp lib/Serialization/ASTWriter.cpp test/CodeGen/pch-dllexport.cpp test/Driver/cl-pch.cpp Index: test/Driver/cl-pch.cpp === --- test/Driver/cl-pch.cpp +++ test/Driver/cl-pch.cpp @@ -7,13 +7,15 @@ // 1. Build .pch file. // CHECK-YC: cc1 // CHECK-YC: -emit-pch +// CHECK-YC: -building-pch-with-obj // CHECK-YC: -o // CHECK-YC: pchfile.pch // CHECK-YC: -x // CHECK-YC: "c++-header" // 2. Use .pch file. // CHECK-YC: cc1 // CHECK-YC: -emit-obj +// CHECK-YC: -building-pch-with-obj // CHECK-YC: -include-pch // CHECK-YC: pchfile.pch @@ -24,11 +26,13 @@ // 1. Build .pch file. // CHECK-YCO: cc1 // CHECK-YCO: -emit-pch +// CHECK-YCO: -building-pch-with-obj // CHECK-YCO: -o // CHECK-YCO: pchfile.pch // 2. Use .pch file. // CHECK-YCO: cc1 // CHECK-YCO: -emit-obj +// CHECK-YCO: -building-pch-with-obj // CHECK-YCO: -include-pch // CHECK-YCO: pchfile.pch // CHECK-YCO: -o @@ -46,6 +50,7 @@ // RUN: | FileCheck -check-prefix=CHECK-YU %s // Use .pch file, but don't build it. // CHECK-YU-NOT: -emit-pch +// CHECK-YU-NOT: -building-pch-with-obj // CHECK-YU: cc1 // CHECK-YU: -emit-obj // CHECK-YU: -include-pch @@ -63,6 +68,7 @@ // 1. Build .pch file. // CHECK-YC-YU: cc1 // CHECK-YC-YU: -emit-pch +// CHECK-YC-YU: -building-pch-with-obj // CHECK-YC-YU: -o // CHECK-YC-YU: pchfile.pch // 2. Use .pch file. Index: test/CodeGen/pch-dllexport.cpp === --- /dev/null +++ test/CodeGen/pch-dllexport.cpp @@ -0,0 +1,84 @@ +// Build PCH without object file, then use it. +// RUN: %clang_cc1 -triple i686-pc-win32 -fms-extensions -emit-pch -o %t %s +// RUN: %clang_cc1 -triple i686-pc-win32 -fms-extensions -emit-obj -emit-llvm -include-pch %t -o - %s | FileCheck -check-prefix=PCH %s + +// Build PCH with object file, then use it. +// RUN: %clang_cc1 -triple i686-pc-win32 -fms-extensions -emit-pch -building-pch-with-obj -o %t %s +// RUN: %clang_cc1 -triple i686-pc-win32 -fms-extensions -emit-obj -emit-llvm -include-pch %t -building-pch-with-obj -o - %s | FileCheck -check-prefix=OBJ %s +// RUN: %clang_cc1 -triple i686-pc-win32 -fms-extensions -emit-obj -emit-llvm -include-pch %t -o - %s | FileCheck -check-prefix=PCHWITHOBJ %s + +// Check for vars separately to avoid having to reorder the check statements. +// RUN: %clang_cc1 -triple i686-pc-win32 -fms-extensions -emit-obj -emit-llvm -include-pch %t -o - %s | FileCheck -check-prefix=PCHWITHOBJVARS %s + +#ifndef IN_HEADER +#define IN_HEADER + +inline void __declspec(dllexport) foo() {} +// OBJ: define weak_odr dso_local dllexport void @"?foo@@YAXXZ" +// PCH: define weak_odr dso_local dllexport void @"?foo@@YAXXZ" +// PCHWITHOBJ-NOT: define {{.*}}foo + + +// This function is referenced, so gets emitted as usual. +inline void __declspec(dllexport) baz() {} +// OBJ: define weak_odr dso_local dllexport void @"?baz@@YAXXZ" +// PCH: define weak_odr dso_local dllexport void @"?baz@@YAXXZ" +// PCHWITHOBJ: define weak_odr dso_local dllexport void @"?baz@@YAXXZ" + + +struct __declspec(dllexport) S { + void bar() {} +// OBJ: define weak_odr dso_local dllexport x86_thiscallcc void @"?bar@S@@QAEXXZ" +// PCH: define weak_odr dso_local dllexport x86_thiscallcc void @"?bar@S@@QAEXXZ" +// PCHWITHOBJ-NOT: define {{.*}}bar +}; + +// This isn't dllexported, attribute((used)) or referenced, so not emitted. +inline void quux() {} +// OBJ-NOT: define {{.*}}quux +// PCH-NOT: define {{.*}}quux +// PCHWITHOBJ-NOT: define {{.*}}quux + +// Referenced non-dllexport function. +inline void referencedNonExported() {} +// OBJ: define {{.*}}referencedNonExported +// PCH: define {{.*}}referencedNonExported +// PCHWITHOBJ: define {{.*}}referencedNonExported + +template void __declspec(dllexport) implicitInstantiation(T) {} + +template inline void __declspec(dllexport) explicitSpecialization(T) {} + +template void __declspec(dllexport) explicitInstantiationDef(T) {} + +template void __declspec(dllexport) explicitInstantiationDefAfterDecl(T) {} +extern template void explicitInstantiationDefAfterDecl(int); + +template T __declspec(dllexport) variableTemplate; +extern template int variableTemplate; + +#else + +void use() { + ba
[PATCH] D47534: [ASTImporter] Add new tests about templated-described swing
martong added a comment. I addressed the comments, thanks for the review! Repository: rC Clang https://reviews.llvm.org/D47534 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47534: [ASTImporter] Add new tests about templated-described swing
This revision was automatically updated to reflect the committed changes. Closed by commit rL335455: [ASTImporter] Add new tests about templated-described swing (authored by martong, committed by ). Herald added a subscriber: llvm-commits. Repository: rL LLVM https://reviews.llvm.org/D47534 Files: cfe/trunk/unittests/AST/ASTImporterTest.cpp Index: cfe/trunk/unittests/AST/ASTImporterTest.cpp === --- cfe/trunk/unittests/AST/ASTImporterTest.cpp +++ cfe/trunk/unittests/AST/ASTImporterTest.cpp @@ -1095,6 +1095,20 @@ unless(has(cxxRecordDecl(hasName("declToImport"; } +TEST(ImportDecl, ImportClassTemplatePartialSpecialization) { + MatchVerifier Verifier; + auto Code = + R"s( + struct declToImport { +template struct X; +template struct X {}; + }; + )s"; + testImport(Code, Lang_CXX, "", Lang_CXX, Verifier, + recordDecl(has(classTemplateDecl()), +has(classTemplateSpecializationDecl(; +} + TEST(ImportExpr, CXXOperatorCallExpr) { MatchVerifier Verifier; testImport("class declToImport {" @@ -1128,6 +1142,52 @@ EXPECT_EQ(ToTemplated1, ToTemplated); } +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclOfFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX); + auto From = FirstDeclMatcher().match( + FromTU, functionTemplateDecl()); + ASSERT_TRUE(From); + auto To = cast(Import(From, Lang_CXX)); + ASSERT_TRUE(To); + Decl *ToTemplated = To->getTemplatedDecl(); + Decl *ToTemplated1 = Import(From->getTemplatedDecl(), Lang_CXX); + EXPECT_TRUE(ToTemplated1); + EXPECT_EQ(ToTemplated1, ToTemplated); +} + +TEST_P(ASTImporterTestBase, + ImportOfTemplatedDeclShouldImportTheClassTemplateDecl) { + Decl *FromTU = getTuDecl("template struct S{};", Lang_CXX); + auto FromFT = + FirstDeclMatcher().match(FromTU, classTemplateDecl()); + ASSERT_TRUE(FromFT); + + auto ToTemplated = + cast(Import(FromFT->getTemplatedDecl(), Lang_CXX)); + EXPECT_TRUE(ToTemplated); + auto ToTU = ToTemplated->getTranslationUnitDecl(); + auto ToFT = + FirstDeclMatcher().match(ToTU, classTemplateDecl()); + EXPECT_TRUE(ToFT); +} + +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclShouldImportTheFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX); + auto FromFT = FirstDeclMatcher().match( + FromTU, functionTemplateDecl()); + ASSERT_TRUE(FromFT); + + auto ToTemplated = + cast(Import(FromFT->getTemplatedDecl(), Lang_CXX)); + EXPECT_TRUE(ToTemplated); + auto ToTU = ToTemplated->getTranslationUnitDecl(); + auto ToFT = FirstDeclMatcher().match( + ToTU, functionTemplateDecl()); + EXPECT_TRUE(ToFT); +} + TEST_P(ASTImporterTestBase, ImportCorrectTemplatedDecl) { auto Code = R"( Index: cfe/trunk/unittests/AST/ASTImporterTest.cpp === --- cfe/trunk/unittests/AST/ASTImporterTest.cpp +++ cfe/trunk/unittests/AST/ASTImporterTest.cpp @@ -1095,6 +1095,20 @@ unless(has(cxxRecordDecl(hasName("declToImport"; } +TEST(ImportDecl, ImportClassTemplatePartialSpecialization) { + MatchVerifier Verifier; + auto Code = + R"s( + struct declToImport { +template struct X; +template struct X {}; + }; + )s"; + testImport(Code, Lang_CXX, "", Lang_CXX, Verifier, + recordDecl(has(classTemplateDecl()), +has(classTemplateSpecializationDecl(; +} + TEST(ImportExpr, CXXOperatorCallExpr) { MatchVerifier Verifier; testImport("class declToImport {" @@ -1128,6 +1142,52 @@ EXPECT_EQ(ToTemplated1, ToTemplated); } +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclOfFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX); + auto From = FirstDeclMatcher().match( + FromTU, functionTemplateDecl()); + ASSERT_TRUE(From); + auto To = cast(Import(From, Lang_CXX)); + ASSERT_TRUE(To); + Decl *ToTemplated = To->getTemplatedDecl(); + Decl *ToTemplated1 = Import(From->getTemplatedDecl(), Lang_CXX); + EXPECT_TRUE(ToTemplated1); + EXPECT_EQ(ToTemplated1, ToTemplated); +} + +TEST_P(ASTImporterTestBase, + ImportOfTemplatedDeclShouldImportTheClassTemplateDecl) { + Decl *FromTU = getTuDecl("template struct S{};", Lang_CXX); + auto FromFT = + FirstDeclMatcher().match(FromTU, classTemplateDecl()); + ASSERT_TRUE(FromFT); + + auto ToTemplated = + cast(Import(FromFT->getTemplatedDecl(), Lang_CXX)); + EXPECT_TRUE(ToTemplated); + auto ToTU = ToTemplated->getTranslationUnitDecl(); + auto ToFT = + FirstDeclMatcher().match(ToTU, classTemplateDecl()); + EXPECT_TRUE(ToFT); +} + +TEST_P(ASTImporterTestBase, + DISABLED_ImportOfTemplatedDeclShouldImportTheFunctionTemplateDecl) { + Decl *FromTU = getTuDecl("t
[PATCH] D48367: [modules] Fix 37878; Autoload subdirectory modulemaps with specific LangOpts
yamaguchi added inline comments. Comment at: clang/lib/Lex/HeaderSearch.cpp:285 // directory. -loadSubdirectoryModuleMaps(SearchDirs[Idx]); +if (ModMap.getLangOpts().ObjC1 || ModMap.getLangOpts().ObjC2) + loadSubdirectoryModuleMaps(SearchDirs[Idx]); bruno wrote: > yamaguchi wrote: > > bruno wrote: > > > aprantl wrote: > > > > Are these flags also enabled in Objective-C++ mode? > > > Looks like all this logic was introduced in r177621 to allow the names of > > > modules to differ from the name of their subdirectory in the include path. > > > > > > Instead of having this to be based on the language, it's probably better > > > if we have it based on @import name lookup, which is the scenario where > > > we actually currently look more aggressively, did you try that path? > > > > > > This is also lacking a testcase, can you create one? > > > Are these flags also enabled in Objective-C++ mode? > > I think so from FrontendOptions.h:190 > > `bool isObjectiveC() const { return Lang == ObjC || Lang == ObjCXX; }` > > > > > it's probably better if we have it based on @import name lookup > > I don't think I understood what you're saying, could you explain a bit more? > > > > > This is also lacking a testcase, can you create one? > > Sure! > > I don't think I understood what you're saying, could you explain a bit more? > > This extra call to `loadSubdirectoryModuleMaps` was introduced in r177621 to > allow `@import SomeName` to work even if `SomeName` doesn't match a > subdirectory name. See the original commit for more details. > > This means that it was never supposed to be called when the module is built > via `#include` or `#import`, which is what you are getting. That said, I > believe it's better if the condition for calling `loadSubdirectoryModuleMaps` > checks somehow if the lookup is coming from of an `@import` instead of > checking the language (we too don't want it to be called for ObjC when > `#include` or `#import` are used). > we too don't want it to be called for ObjC when #include or #import are used https://gist.github.com/yamaguchi1024/27caba1897eb813b297a8c4785adc11d This is one thing I could think of, it excludes `#include` but `#import` and `@import` are still treated in the same way. Do you have any idea how to do this? Is Clang differenciating the module behavior based on `#import` or `@import` in ObjC? Comment at: clang/test/Modules/autoload-subdirectory.cpp:1 +// RUN: %clang -fmodules -fmodule-name=Foo -I %S/Inputs/autoload-subdirectory/ %s + bruno wrote: > Instead of `%clang`, please use `%clang_cc1` and `-verify` here. Sure https://reviews.llvm.org/D48367 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r335458 - [clangd] Always remove dots before converting paths to URIs in symbol collector.
Author: ioeric Date: Mon Jun 25 04:50:11 2018 New Revision: 335458 URL: http://llvm.org/viewvc/llvm-project?rev=335458&view=rev Log: [clangd] Always remove dots before converting paths to URIs in symbol collector. Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=335458&r1=335457&r2=335458&view=diff == --- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original) +++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Mon Jun 25 04:50:11 2018 @@ -75,9 +75,10 @@ llvm::Optional toURI(const } } else if (!Opts.FallbackDir.empty()) { llvm::sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath); -llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true); } + llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true); + std::string ErrMsg; for (const auto &Scheme : Opts.URISchemes) { auto U = URI::create(AbsolutePath, Scheme); ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48367: [modules] Fix 37878; Autoload subdirectory modulemaps with specific LangOpts
yamaguchi updated this revision to Diff 152664. yamaguchi added a comment. use %clang_cc1 instead of %clang https://reviews.llvm.org/D48367 Files: clang/include/clang/Lex/ModuleMap.h clang/lib/Lex/HeaderSearch.cpp clang/test/Modules/Inputs/autoload-subdirectory/a.h clang/test/Modules/Inputs/autoload-subdirectory/b.h clang/test/Modules/Inputs/autoload-subdirectory/include/module.modulemap clang/test/Modules/Inputs/autoload-subdirectory/module.modulemap clang/test/Modules/autoload-subdirectory.cpp Index: clang/test/Modules/autoload-subdirectory.cpp === --- /dev/null +++ clang/test/Modules/autoload-subdirectory.cpp @@ -0,0 +1,9 @@ +// RUN: %clang_cc1 -fmodules -fmodule-name=Foo -I %S/Inputs/autoload-subdirectory/ %s -verify +// expected-no-diagnostics + +#include "a.h" + +int main() { + foo neko; + return 0; +} Index: clang/test/Modules/Inputs/autoload-subdirectory/module.modulemap === --- /dev/null +++ clang/test/Modules/Inputs/autoload-subdirectory/module.modulemap @@ -0,0 +1,2 @@ +module a { header "a.h" } +module b { header "b.h" } Index: clang/test/Modules/Inputs/autoload-subdirectory/include/module.modulemap === --- /dev/null +++ clang/test/Modules/Inputs/autoload-subdirectory/include/module.modulemap @@ -0,0 +1,2 @@ +module a { header "a.h" } +module b { header "b.h" } Index: clang/test/Modules/Inputs/autoload-subdirectory/b.h === --- /dev/null +++ clang/test/Modules/Inputs/autoload-subdirectory/b.h @@ -0,0 +1 @@ +class bar {}; Index: clang/test/Modules/Inputs/autoload-subdirectory/a.h === --- /dev/null +++ clang/test/Modules/Inputs/autoload-subdirectory/a.h @@ -0,0 +1,8 @@ +#include "b.h" + +class foo { + int x,y; + public: +foo() {}; +~foo() {}; +}; Index: clang/lib/Lex/HeaderSearch.cpp === --- clang/lib/Lex/HeaderSearch.cpp +++ clang/lib/Lex/HeaderSearch.cpp @@ -282,7 +282,8 @@ // Load all module maps in the immediate subdirectories of this search // directory. -loadSubdirectoryModuleMaps(SearchDirs[Idx]); +if (ModMap.getLangOpts().ObjC1 || ModMap.getLangOpts().ObjC2) + loadSubdirectoryModuleMaps(SearchDirs[Idx]); // Look again for the module. Module = ModMap.findModule(ModuleName); Index: clang/include/clang/Lex/ModuleMap.h === --- clang/include/clang/Lex/ModuleMap.h +++ clang/include/clang/Lex/ModuleMap.h @@ -110,6 +110,11 @@ llvm::StringMap> PendingLinkAsModule; public: + /// Get LangOpts of ModuleMap + const LangOptions& getLangOpts() { +return LangOpts; + } + /// Use PendingLinkAsModule information to mark top level link names that /// are going to be replaced by export_as aliases. void resolveLinkAsDependencies(Module *Mod); Index: clang/test/Modules/autoload-subdirectory.cpp === --- /dev/null +++ clang/test/Modules/autoload-subdirectory.cpp @@ -0,0 +1,9 @@ +// RUN: %clang_cc1 -fmodules -fmodule-name=Foo -I %S/Inputs/autoload-subdirectory/ %s -verify +// expected-no-diagnostics + +#include "a.h" + +int main() { + foo neko; + return 0; +} Index: clang/test/Modules/Inputs/autoload-subdirectory/module.modulemap === --- /dev/null +++ clang/test/Modules/Inputs/autoload-subdirectory/module.modulemap @@ -0,0 +1,2 @@ +module a { header "a.h" } +module b { header "b.h" } Index: clang/test/Modules/Inputs/autoload-subdirectory/include/module.modulemap === --- /dev/null +++ clang/test/Modules/Inputs/autoload-subdirectory/include/module.modulemap @@ -0,0 +1,2 @@ +module a { header "a.h" } +module b { header "b.h" } Index: clang/test/Modules/Inputs/autoload-subdirectory/b.h === --- /dev/null +++ clang/test/Modules/Inputs/autoload-subdirectory/b.h @@ -0,0 +1 @@ +class bar {}; Index: clang/test/Modules/Inputs/autoload-subdirectory/a.h === --- /dev/null +++ clang/test/Modules/Inputs/autoload-subdirectory/a.h @@ -0,0 +1,8 @@ +#include "b.h" + +class foo { + int x,y; + public: +foo() {}; +~foo() {}; +}; Index: clang/lib/Lex/HeaderSearch.cpp === --- clang/lib/Lex/HeaderSearch.cpp +++ clang/lib/Lex/HeaderSearch.cpp @@ -282,7 +282,8 @@ // Load all module maps in the immediate subdirectories of this search // directory. -loadSubdirectoryModuleMaps(SearchDirs[Idx]); +if (ModMap
[PATCH] D48456: [Fixed Point Arithmetic] Casting between fixed point types and other arithmetic types
ebevhan added a comment. Would it be possible to add some form of target hook (perhaps to CodeGenABIInfo, which is already accessed with `getTargetHooks`) for fixed-point operations (maybe even some conversions)? As I've mentioned earlier, we emit both IR and intrinsics for many of these operations to make instruction selection possible. I suspect that any target that wants to utilize fixed-point effectively will need this as well. --- I'm contemplating whether the unsigned padding bit clear before operations is needed at all. If you have the outlook that producing a value with a bit in that position is technically overflow and therefore undefined behavior, it shouldn't matter that the bit is set or not before operations; we already have UB. If you want to be sure that things 'work anyway', then you're better off clearing after operations instead to keep things consistent between operations instead of just before them. I suspect that some of our tests depend on unsigned behaving this way, so we would have to look at that in case we decide to drop the clear altogether... --- I also have a bit more feedback on previous patches that I missed at the time, but it feels wrong to add that here. How do you want me to take it? Comment at: include/clang/AST/ASTContext.h:1954 + llvm::APInt getFixedPointMin(QualType Ty) const; + llvm::APInt getFixedPointOne(QualType Ty) const; rjmccall wrote: > Are these opaque bit-patterns? I think there should be a type which > abstracts over constant fixed-point values, something `APSInt`-like that also > carries the signedness and scale. For now that type can live in Clang; if > LLVM wants to add intrinsic support for fixed-point, it'll be easy enough to > move it there. All of the parameters that determine these values (min, max, one) need to be sourced from the target, though. It's not like APSInt is aware of the dimensions of integers on the targets. I think these should return APSInt and not APInt, though. Creating another abstraction on top of APInt is probably still quite useful, especially for certain operations (multiplication, division, saturating conversion, saturating operations). Probably not too useful for this patch since it doesn't deal with constant evaluation. Comment at: include/clang/Lex/LiteralSupport.h:76 + bool isFixedPointLiteral() const { +return saw_fixed_point_suffix && (saw_period || saw_exponent); + } I realized there was something off with this as well after the patch landed, but I wasn't sure what it was. Could this cause problems with user-defined literals as well? Comment at: lib/AST/ASTContext.cpp:10260 + + if (Ty->isSignedFixedPointType()) +Val = llvm::APInt::getSignedMaxValue(NumBits); Can't this be `Ty->isSignedFixedPointType() || SameFBits`? I suspect this function can be simplified to look like the 'Min' one. Comment at: lib/AST/ASTContext.cpp:10283 + llvm::APInt One(NumBits, 1, Ty->isSignedFixedPointType()); + return One.shl(Scale); +} This will give a nonsensical result for unsigned fract with !SameFBits. Comment at: lib/AST/ExprConstant.cpp:9501 + return false; +return Success(Result.getInt() >> Scale, E); + } The shift here will not produce the correct rounding behavior for fixed-point to integer conversion. E-C says `Conversions from a fixed-point to an integer type round toward zero.` However, simply shifting will always round towards -inf. If the fixed-point number is negative, you need to add `lowBits(Scale)` before performing the shift. This operation here is also not the same as the FixedPointToBool emission in CodeGen. Comment at: lib/CodeGen/CGExprScalar.cpp:768 +if (CGF.getContext().getTargetInfo().unsignedFixedPointTypesHavePadding() && +Ty->isUnsignedFixedPointType()) { + unsigned NumBits = CGF.getContext().getTypeSize(Ty); rjmccall wrote: > Can you explain the padding thing? Why is padding uniformly present or > absent on all unsigned fixed point types on a target, and never on signed > types? Is this "low bits set" thing endian-specific? I'll give an example with a fract type. Let's say fract is 16 bits wide. That means the signed fract will have a scale of 15 (15 fractional bits) and one sign bit, for a value range of [-1.0, 1.0). The LSB is worth 2^-15 and the MSB is worth -2^0, similar to signed integers. The unsigned fract cannot be negative, but must also have a value range of 1.0. This means that either: * The scale remains the same (15), and the MSB is a padding bit. This bit would normally be the 2^0 bit, but since the range of the number cannot exceed 1, this bit will always be 0. In this case, the LSB is worth 2^-15 (same as the signed) and the MSB is not worth anything. * The scale is that of signed frac
[PATCH] D48426: [clang-cl] Don't emit dllexport inline functions etc. from pch files (PR37801)
thakis added a comment. Still looks good, ship it! One more suggestion about additional test coverage (but maybe it's already there and I'm just missing it). Comment at: test/CodeGen/pch-dllexport.cpp:55 +template void __declspec(dllexport) explicitInstantiationDefAfterDecl(T) {} +extern template void explicitInstantiationDefAfterDecl(int); + This has two interesting cases: 1. An explicit instantiation declaration. 2. An explicit instantiation definition. You have a test for 2, but not for 1, as far as I can tell (?). For 1, the inline function from the pch-obj should be used (which probably already works; if not a FIXME is enough). https://reviews.llvm.org/D48426 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D44143: [clang-tidy] Create properly seeded random generator check
aaron.ballman added inline comments. Comment at: clang-tidy/cert/CERTTidyModule.cpp:44 "cert-dcl54-cpp"); -CheckFactories.registerCheck( -"cert-dcl58-cpp"); + CheckFactories.registerCheck("cert-dcl58-cpp"); CheckFactories.registerCheck( boga95 wrote: > aaron.ballman wrote: > > This change looks unrelated to the patch. > Clang format did it when I apply it to the whole file. You should clang-format the patch, not the entire file. See https://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting for details. Comment at: clang-tidy/cert/ProperlySeededRandomGeneratorCheck.cpp:74 + callExpr(has(implicitCastExpr(has( + declRefExpr(hasDeclaration(namedDecl(hasName("srand" + .bind("srand"), boga95 wrote: > aaron.ballman wrote: > > I think that in C mode, this is fine, but in C++ mode it should register > > `::std::srand`. > It is not match for ##::std::srand##, just for ##::srand##. I found some > examples, but I think they don't work neither. > > > As it stands, I'm not certain whether this will match code like `std::srand(0);`. Please add a test case to the C++ tests for it as it should be handled. Comment at: docs/clang-tidy/checks/cert-msc51-cpp.rst:7 +This check flags all pseudo-random number engines, engine adaptor +instantiations and srand when initialized or seeded with default argument, +constant expression or any user-configurable type. Pseudo-random number Eugene.Zelenko wrote: > aaron.ballman wrote: > > Backticks around `srand` > Two of them and please add (). Will be good idea to make first statement same > as in Release Notes. This comment still has not been handled. Also, please remove the space between `srand` and the parens. https://reviews.llvm.org/D44143 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48412: [RISCV] Add support for interrupt attribute
aaron.ballman added inline comments. Herald added a subscriber: the_o. Comment at: lib/Sema/SemaDeclAttr.cpp:5280 + // Check the attribute arguments. + if (AL.getNumArgs() > 1) { +S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) apazos wrote: > aaron.ballman wrote: > > Please call `checkAttributeNumArgs()` instead; the error you're using is > > incorrect (it's used for variadic parameters where you receive more > > arguments than you expect). > The argument is optional and at most one argument , I will use > checkAttributeAtMostNumArgs instead Ah, yeah, I didn't pick up the optional part when writing my comment; this LG. Comment at: lib/Sema/SemaDeclAttr.cpp:5301 + + if (!isFunctionOrMethod(D)) { +S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) apazos wrote: > aaron.ballman wrote: > > I don't think you need to perform this check -- I believe it's handled > > automatically (because you don't have custom parsing enabled). > I think need it. Will double check in the test. See `handleCommonAttributeFeatures()` -- it calls `diagnoseAppertainsTo()` which handles this for you. As it is, your check here does not match the subject list on the attribute. The declarative bit says it only appertains to a function and this check is for a function or Obj-C method. Which brings up my next question: should this appertain to an ObjC method? Comment at: test/Sema/riscv-interrupt-attr.c:18 + +__attribute__((interrupt("user"), interrupt("supervisor"))) void foo6() { } // expected-warning {{repeated RISC-V 'interrupt' attribute}} \ +// expected-note {{repeated RISC-V 'interrupt' attribute is here}} apazos wrote: > aaron.ballman wrote: > > You should also add tests for: > > ``` > > __attribute__((interrupt("user"))) void f(void); > > __attribute__((interrupt("machine"))) void f(void); > > > > void f(void) { } > > > > [[gnu::interrupt("user") gnu::interrupt("machine")]] void g() {} > > > > [[gnu::interrupt("user")]] [[gnu::interrupt("machine")]] void h() {} > > ``` > For this test case tt seems LLVM honors the last setting, "machine". > But gcc is honoring the first. > I think the last setting should prevail. Will check with GCC folks. Do all of these cases get diagnosed as being a repeated interrupt attribute? Should add them as test cases. https://reviews.llvm.org/D48412 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48543: [clang-format] Keep @message together in text protos
krasimir created this revision. Herald added a subscriber: cfe-commits. In C++ code snippets of the form `@field` are common. This makes clang-format keep them together in text protos, whereas before it would break them. Repository: rC Clang https://reviews.llvm.org/D48543 Files: lib/Format/ContinuationIndenter.cpp lib/Format/TokenAnnotator.cpp unittests/Format/FormatTestTextProto.cpp Index: unittests/Format/FormatTestTextProto.cpp === --- unittests/Format/FormatTestTextProto.cpp +++ unittests/Format/FormatTestTextProto.cpp @@ -717,5 +717,23 @@ "# endfile comment"); } +TEST_F(FormatTestTextProto, KeepsAmpersandsNextToKeys) { + verifyFormat("@tmpl { field: 1 }"); + verifyFormat("@placeholder: 1"); + verifyFormat("@name <>"); + verifyFormat("submessage: @base { key: value }"); + verifyFormat("submessage: @base {\n" + " key: value\n" + " item: {}\n" + "}"); + verifyFormat("submessage: {\n" + " msg: @base {\n" + "yolo: {}\n" + "key: value\n" + " }\n" + " key: value\n" + "}"); +} + } // end namespace tooling } // end namespace clang Index: lib/Format/TokenAnnotator.cpp === --- lib/Format/TokenAnnotator.cpp +++ lib/Format/TokenAnnotator.cpp @@ -2949,15 +2949,32 @@ // // Be careful to exclude the case [proto.ext] { ... } since the `]` is // the TT_SelectorName there, but we don't want to break inside the brackets. + // + // Another edge case is @submessage { key: value }, which is a common + // substitution placeholder. In this case we want to keep `@` and `submessage` + // together. + // // We ensure elsewhere that extensions are always on their own line. if ((Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) && Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) { +// Keep `@submessage` together in: +// @submessage { key: value } +if (Right.Previous && Right.Previous->is(tok::at)) + return false; // Look for the scope opener after selector in cases like: // selector { ... // selector: { ... -FormatToken *LBrace = -Right.Next->is(tok::colon) ? Right.Next->Next : Right.Next; +// selector: @base { ... +FormatToken *LBrace = Right.Next; +if (LBrace && LBrace->is(tok::colon)) { + LBrace = LBrace->Next; + if (LBrace && LBrace->is(tok::at)) { +LBrace = LBrace->Next; +if (LBrace) + LBrace = LBrace->Next; + } +} if (LBrace && // The scope opener is one of {, [, <: // selector { ... } Index: lib/Format/ContinuationIndenter.cpp === --- lib/Format/ContinuationIndenter.cpp +++ lib/Format/ContinuationIndenter.cpp @@ -379,7 +379,8 @@ if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) && State.Line->startsWith(TT_ObjCMethodSpecifier)) return true; - if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound && + if (Current.is(TT_SelectorName) && !Previous.is(tok::at) && + State.Stack.back().ObjCSelectorNameFound && State.Stack.back().BreakBeforeParameter) return true; Index: unittests/Format/FormatTestTextProto.cpp === --- unittests/Format/FormatTestTextProto.cpp +++ unittests/Format/FormatTestTextProto.cpp @@ -717,5 +717,23 @@ "# endfile comment"); } +TEST_F(FormatTestTextProto, KeepsAmpersandsNextToKeys) { + verifyFormat("@tmpl { field: 1 }"); + verifyFormat("@placeholder: 1"); + verifyFormat("@name <>"); + verifyFormat("submessage: @base { key: value }"); + verifyFormat("submessage: @base {\n" + " key: value\n" + " item: {}\n" + "}"); + verifyFormat("submessage: {\n" + " msg: @base {\n" + "yolo: {}\n" + "key: value\n" + " }\n" + " key: value\n" + "}"); +} + } // end namespace tooling } // end namespace clang Index: lib/Format/TokenAnnotator.cpp === --- lib/Format/TokenAnnotator.cpp +++ lib/Format/TokenAnnotator.cpp @@ -2949,15 +2949,32 @@ // // Be careful to exclude the case [proto.ext] { ... } since the `]` is // the TT_SelectorName there, but we don't want to break inside the brackets. + // + // Another edge case is @submessage { key: value }, which is a common + // substitution placeholder. In this case we want to keep `@` and `submessage` + // together. + // // We ensure elsewhere that extensions are always on their own line. if ((Style.Language == FormatStyle::L
r335459 - [clang-format] Keep @message together in text protos
Author: krasimir Date: Mon Jun 25 05:43:12 2018 New Revision: 335459 URL: http://llvm.org/viewvc/llvm-project?rev=335459&view=rev Log: [clang-format] Keep @message together in text protos Summary: In C++ code snippets of the form `@field` are common. This makes clang-format keep them together in text protos, whereas before it would break them. Subscribers: cfe-commits Differential Revision: https://reviews.llvm.org/D48543 Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp cfe/trunk/lib/Format/TokenAnnotator.cpp cfe/trunk/unittests/Format/FormatTestTextProto.cpp Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=335459&r1=335458&r2=335459&view=diff == --- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original) +++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Mon Jun 25 05:43:12 2018 @@ -379,7 +379,8 @@ bool ContinuationIndenter::mustBreak(con if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) && State.Line->startsWith(TT_ObjCMethodSpecifier)) return true; - if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound && + if (Current.is(TT_SelectorName) && !Previous.is(tok::at) && + State.Stack.back().ObjCSelectorNameFound && State.Stack.back().BreakBeforeParameter) return true; Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=335459&r1=335458&r2=335459&view=diff == --- cfe/trunk/lib/Format/TokenAnnotator.cpp (original) +++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Jun 25 05:43:12 2018 @@ -2949,15 +2949,32 @@ bool TokenAnnotator::mustBreakBefore(con // // Be careful to exclude the case [proto.ext] { ... } since the `]` is // the TT_SelectorName there, but we don't want to break inside the brackets. + // + // Another edge case is @submessage { key: value }, which is a common + // substitution placeholder. In this case we want to keep `@` and `submessage` + // together. + // // We ensure elsewhere that extensions are always on their own line. if ((Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) && Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) { +// Keep `@submessage` together in: +// @submessage { key: value } +if (Right.Previous && Right.Previous->is(tok::at)) + return false; // Look for the scope opener after selector in cases like: // selector { ... // selector: { ... -FormatToken *LBrace = -Right.Next->is(tok::colon) ? Right.Next->Next : Right.Next; +// selector: @base { ... +FormatToken *LBrace = Right.Next; +if (LBrace && LBrace->is(tok::colon)) { + LBrace = LBrace->Next; + if (LBrace && LBrace->is(tok::at)) { +LBrace = LBrace->Next; +if (LBrace) + LBrace = LBrace->Next; + } +} if (LBrace && // The scope opener is one of {, [, <: // selector { ... } Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=335459&r1=335458&r2=335459&view=diff == --- cfe/trunk/unittests/Format/FormatTestTextProto.cpp (original) +++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp Mon Jun 25 05:43:12 2018 @@ -717,5 +717,23 @@ TEST_F(FormatTestTextProto, FormatsComme "# endfile comment"); } +TEST_F(FormatTestTextProto, KeepsAmpersandsNextToKeys) { + verifyFormat("@tmpl { field: 1 }"); + verifyFormat("@placeholder: 1"); + verifyFormat("@name <>"); + verifyFormat("submessage: @base { key: value }"); + verifyFormat("submessage: @base {\n" + " key: value\n" + " item: {}\n" + "}"); + verifyFormat("submessage: {\n" + " msg: @base {\n" + "yolo: {}\n" + "key: value\n" + " }\n" + " key: value\n" + "}"); +} + } // end namespace tooling } // end namespace clang ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48543: [clang-format] Keep @message together in text protos
This revision was not accepted when it landed; it landed in state "Needs Review". This revision was automatically updated to reflect the committed changes. Closed by commit rC335459: [clang-format] Keep @message together in text protos (authored by krasimir, committed by ). Changed prior to commit: https://reviews.llvm.org/D48543?vs=152670&id=152671#toc Repository: rC Clang https://reviews.llvm.org/D48543 Files: lib/Format/ContinuationIndenter.cpp lib/Format/TokenAnnotator.cpp unittests/Format/FormatTestTextProto.cpp Index: lib/Format/TokenAnnotator.cpp === --- lib/Format/TokenAnnotator.cpp +++ lib/Format/TokenAnnotator.cpp @@ -2949,15 +2949,32 @@ // // Be careful to exclude the case [proto.ext] { ... } since the `]` is // the TT_SelectorName there, but we don't want to break inside the brackets. + // + // Another edge case is @submessage { key: value }, which is a common + // substitution placeholder. In this case we want to keep `@` and `submessage` + // together. + // // We ensure elsewhere that extensions are always on their own line. if ((Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) && Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) { +// Keep `@submessage` together in: +// @submessage { key: value } +if (Right.Previous && Right.Previous->is(tok::at)) + return false; // Look for the scope opener after selector in cases like: // selector { ... // selector: { ... -FormatToken *LBrace = -Right.Next->is(tok::colon) ? Right.Next->Next : Right.Next; +// selector: @base { ... +FormatToken *LBrace = Right.Next; +if (LBrace && LBrace->is(tok::colon)) { + LBrace = LBrace->Next; + if (LBrace && LBrace->is(tok::at)) { +LBrace = LBrace->Next; +if (LBrace) + LBrace = LBrace->Next; + } +} if (LBrace && // The scope opener is one of {, [, <: // selector { ... } Index: lib/Format/ContinuationIndenter.cpp === --- lib/Format/ContinuationIndenter.cpp +++ lib/Format/ContinuationIndenter.cpp @@ -379,7 +379,8 @@ if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) && State.Line->startsWith(TT_ObjCMethodSpecifier)) return true; - if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound && + if (Current.is(TT_SelectorName) && !Previous.is(tok::at) && + State.Stack.back().ObjCSelectorNameFound && State.Stack.back().BreakBeforeParameter) return true; Index: unittests/Format/FormatTestTextProto.cpp === --- unittests/Format/FormatTestTextProto.cpp +++ unittests/Format/FormatTestTextProto.cpp @@ -717,5 +717,23 @@ "# endfile comment"); } +TEST_F(FormatTestTextProto, KeepsAmpersandsNextToKeys) { + verifyFormat("@tmpl { field: 1 }"); + verifyFormat("@placeholder: 1"); + verifyFormat("@name <>"); + verifyFormat("submessage: @base { key: value }"); + verifyFormat("submessage: @base {\n" + " key: value\n" + " item: {}\n" + "}"); + verifyFormat("submessage: {\n" + " msg: @base {\n" + "yolo: {}\n" + "key: value\n" + " }\n" + " key: value\n" + "}"); +} + } // end namespace tooling } // end namespace clang Index: lib/Format/TokenAnnotator.cpp === --- lib/Format/TokenAnnotator.cpp +++ lib/Format/TokenAnnotator.cpp @@ -2949,15 +2949,32 @@ // // Be careful to exclude the case [proto.ext] { ... } since the `]` is // the TT_SelectorName there, but we don't want to break inside the brackets. + // + // Another edge case is @submessage { key: value }, which is a common + // substitution placeholder. In this case we want to keep `@` and `submessage` + // together. + // // We ensure elsewhere that extensions are always on their own line. if ((Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) && Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) { +// Keep `@submessage` together in: +// @submessage { key: value } +if (Right.Previous && Right.Previous->is(tok::at)) + return false; // Look for the scope opener after selector in cases like: // selector { ... // selector: { ... -FormatToken *LBrace = -Right.Next->is(tok::colon) ? Right.Next->Next : Right.Next; +// selector: @base { ... +FormatToken *LBrace = Right.Next; +if (LBrace && LBrace->is(tok::colon)) { + LBrace = LBrace->Next; + if (LBrace && LBrace->is(tok::at)) { +LBrace = LBrace->Next; +if (LBrace) +
[PATCH] D48426: [clang-cl] Don't emit dllexport inline functions etc. from pch files (PR37801)
hans added inline comments. Comment at: test/CodeGen/pch-dllexport.cpp:55 +template void __declspec(dllexport) explicitInstantiationDefAfterDecl(T) {} +extern template void explicitInstantiationDefAfterDecl(int); + thakis wrote: > This has two interesting cases: > > 1. An explicit instantiation declaration. > 2. An explicit instantiation definition. > > You have a test for 2, but not for 1, as far as I can tell (?). For 1, the > inline function from the pch-obj should be used (which probably already > works; if not a FIXME is enough). It's really testing the "explicit instantiation def after explicit instantiation decl" case. With just an explicit instantiation decl (1), there's not much to test, since that's like a promise that someone else is going to instantiate the template. Nothing needs to be emitted for that. Maybe I'm not understanding your question? https://reviews.llvm.org/D48426 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D45719: [clang-Format] Fix indentation of member call after block
ank added inline comments. Comment at: unittests/Format/FormatTest.cpp:4359 + "return 3;\n" + " }).as("");\n" + "}"); klimek wrote: > ank wrote: > > klimek wrote: > > > What would be interesting is tests that: > > > a) have another value after the closing }; doesn't really make sense in > > > this test, but usually these are in calls > > > f([]() { ... }, foo, bar).call(...) > > > > > > b) make .as("") have paramters that go beyond the limit > > > > > > c) add another chained call behind .as(""). > > Hello, sorry for the late follow up on this! > > > > Indeed an interesting thing to test, and so I did, the patterns you > > describe seems to give strange indentation as far back as release_36 and > > probably has always done so. The case I'm testing here worked in release_40 > > but stopped working somewhere before release_50 > > > > maybe fixing those other cases can be done in another patch > > > > cheers, > > Anders > I meant: please add these tests :) I need to clarify, those tests will not be correctly indented by this commit, I could add those tests but then they would verify a faulty behaviour, this is how they will be indented even with this patch applied: ``` // Dont break if only closing statements before member call verifyFormat("test() {\n" " ([]() -> {\n" "int b = 32;\n" "return 3;\n" " }).foo();\n" "}"); verifyFormat("test() {\n" " (\n" " []() -> {\n" "int b = 32;\n" "return 3;\n" " },\n" " foo, bar)\n" " .foo();\n" "}"); verifyFormat("test() {\n" " ([]() -> {\n" "int b = 32;\n" "return 3;\n" " })\n" " .foo()\n" " .bar();\n" "}"); verifyFormat("test() {\n" " ([]() -> {\n" "int b = 32;\n" "return 3;\n" " })\n" " .foo(\"aaa\"\n" " \"bb\");\n" "}"); verifyFormat("test() {\n" " foo([]() -> {\n" "int b = 32;\n" "return 3;\n" " }).foo();\n" "}"); verifyFormat("test() {\n" " foo(\n" " []() -> {\n" "int b = 32;\n" "return 3;\n" " },\n" " foo, bar)\n" " .as();\n" "}"); verifyFormat("test() {\n" " foo([]() -> {\n" "int b = 32;\n" "return 3;\n" " })\n" " .foo()\n" " .bar();\n" "}"); verifyFormat("test() {\n" " foo([]() -> {\n" "int b = 32;\n" "return 3;\n" " })\n" " .as(\"\"\n" " \"bb\");\n" "}"); ``` Repository: rC Clang https://reviews.llvm.org/D45719 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48426: [clang-cl] Don't emit dllexport inline functions etc. from pch files (PR37801)
thakis added inline comments. Comment at: test/CodeGen/pch-dllexport.cpp:55 +template void __declspec(dllexport) explicitInstantiationDefAfterDecl(T) {} +extern template void explicitInstantiationDefAfterDecl(int); + hans wrote: > thakis wrote: > > This has two interesting cases: > > > > 1. An explicit instantiation declaration. > > 2. An explicit instantiation definition. > > > > You have a test for 2, but not for 1, as far as I can tell (?). For 1, the > > inline function from the pch-obj should be used (which probably already > > works; if not a FIXME is enough). > It's really testing the "explicit instantiation def after explicit > instantiation decl" case. > > With just an explicit instantiation decl (1), there's not much to test, since > that's like a promise that someone else is going to instantiate the template. > Nothing needs to be emitted for that. > > Maybe I'm not understanding your question? > Nothing needs to be emitted for that. Right, I meant including a test that we really don't emit anything for that. But feel free to omit it if you don't think it adds much. I suggested it because we end up with TSK_ExplicitInstantiationDeclaration in that case, and you're checking the TSK in this change, and you have coverage for the other kinds. https://reviews.llvm.org/D48426 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47367: [ASTImporter] Add ms compatibility to tests
martong updated this revision to Diff 152674. martong added a comment. - Update commit comment and fix broken format in a comment. Repository: rC Clang https://reviews.llvm.org/D47367 Files: unittests/AST/ASTImporterTest.cpp unittests/AST/Language.cpp unittests/AST/Language.h Index: unittests/AST/Language.h === --- unittests/AST/Language.h +++ unittests/AST/Language.h @@ -22,7 +22,6 @@ namespace ast_matchers { typedef std::vector ArgVector; -typedef std::vector RunOptions; enum Language { Lang_C, @@ -34,12 +33,7 @@ Lang_OBJCXX }; -inline bool isCXX(Language Lang) { - return Lang == Lang_CXX || Lang == Lang_CXX11 || Lang == Lang_CXX14; -} - ArgVector getBasicRunOptionsForLanguage(Language Lang); -RunOptions getRunOptionsForLanguage(Language Lang); } // end namespace ast_matchers } // end namespace clang Index: unittests/AST/Language.cpp === --- unittests/AST/Language.cpp +++ unittests/AST/Language.cpp @@ -42,19 +42,5 @@ return BasicArgs; } -RunOptions getRunOptionsForLanguage(Language Lang) { - ArgVector BasicArgs = getBasicRunOptionsForLanguage(Lang); - - // For C++, test with "-fdelayed-template-parsing" enabled to handle MSVC - // default behaviour. - if (isCXX(Lang)) { -ArgVector ArgsForDelayedTemplateParse = BasicArgs; -ArgsForDelayedTemplateParse.emplace_back("-fdelayed-template-parsing"); -return {BasicArgs, ArgsForDelayedTemplateParse}; - } - - return {BasicArgs}; -} - } // end namespace ast_matchers } // end namespace clang Index: unittests/AST/ASTImporterTest.cpp === --- unittests/AST/ASTImporterTest.cpp +++ unittests/AST/ASTImporterTest.cpp @@ -50,114 +50,233 @@ llvm::MemoryBuffer::getMemBuffer(Code)); } -template -NodeType importNode(ASTUnit *From, ASTUnit *To, ASTImporter &Importer, -NodeType Node) { - ASTContext &ToCtx = To->getASTContext(); +const StringRef DeclToImportID = "declToImport"; +const StringRef DeclToVerifyID = "declToVerify"; - // Add 'From' file to virtual file system so importer can 'find' it - // while importing SourceLocations. It is safe to add same file multiple - // times - it just isn't replaced. - StringRef FromFileName = From->getMainFileName(); - createVirtualFileIfNeeded(To, FromFileName, -From->getBufferForFile(FromFileName)); +// Common base for the different families of ASTImporter tests that are +// parameterized on the compiler options which may result a different AST. E.g. +// -fms-compatibility or -fdelayed-template-parsing. +struct ParameterizedTestsFixture : ::testing::TestWithParam { - auto Imported = Importer.Import(Node); + // Returns the argument vector used for a specific language option, this set + // can be tweaked by the test parameters. + ArgVector getArgVectorForLanguage(Language Lang) const { +ArgVector Args = getBasicRunOptionsForLanguage(Lang); +ArgVector ExtraArgs = GetParam(); +for (const auto &Arg : ExtraArgs) { + Args.push_back(Arg); +} +return Args; + } - // This should dump source locations and assert if some source locations - // were not imported. - SmallString<1024> ImportChecker; - llvm::raw_svector_ostream ToNothing(ImportChecker); - ToCtx.getTranslationUnitDecl()->print(ToNothing); +}; - // This traverses the AST to catch certain bugs like poorly or not - // implemented subtrees. - Imported->dump(ToNothing); +// Base class for those tests which use the family of `testImport` functions. +class TestImportBase : public ParameterizedTestsFixture { - return Imported; -} + template + NodeType importNode(ASTUnit *From, ASTUnit *To, ASTImporter &Importer, + NodeType Node) { +ASTContext &ToCtx = To->getASTContext(); -const StringRef DeclToImportID = "declToImport"; -const StringRef DeclToVerifyID = "declToVerify"; +// Add 'From' file to virtual file system so importer can 'find' it +// while importing SourceLocations. It is safe to add same file multiple +// times - it just isn't replaced. +StringRef FromFileName = From->getMainFileName(); +createVirtualFileIfNeeded(To, FromFileName, + From->getBufferForFile(FromFileName)); -template -testing::AssertionResult -testImport(const std::string &FromCode, const ArgVector &FromArgs, - const std::string &ToCode, const ArgVector &ToArgs, - MatchVerifier &Verifier, - const BindableMatcher &SearchMatcher, - const BindableMatcher &VerificationMatcher) { - const char *const InputFileName = "input.cc"; - const char *const OutputFileName = "output.cc"; +auto Imported = Importer.Import(Node); - std::unique_ptr - FromAST = tooling::buildASTFromCodeWithArgs( -FromCode, FromArg
r335464 - [ASTImporter] Add ms compatibility to tests which use the TestBase
Author: martong Date: Mon Jun 25 06:04:37 2018 New Revision: 335464 URL: http://llvm.org/viewvc/llvm-project?rev=335464&view=rev Log: [ASTImporter] Add ms compatibility to tests which use the TestBase Summary: In order to avoid build failures on MS, we use -fms-compatibility too in the tests which use the TestBase. Moved the family of `testImport` functions under a test fixture class, so we can use parameterized tests. Refactored `testImport` and `testImportSequence`, because `for` loops over the different compiler options is no longer needed, that is handeld by the test framework via parameters from now on. Reviewers: a.sidorin, r.stahl, xazax.hun Subscribers: rnkovacs, dkrupp, cfe-commits Differential Revision: https://reviews.llvm.org/D47367 Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp cfe/trunk/unittests/AST/Language.cpp cfe/trunk/unittests/AST/Language.h Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/ASTImporterTest.cpp?rev=335464&r1=335463&r2=335464&view=diff == --- cfe/trunk/unittests/AST/ASTImporterTest.cpp (original) +++ cfe/trunk/unittests/AST/ASTImporterTest.cpp Mon Jun 25 06:04:37 2018 @@ -50,114 +50,233 @@ static void createVirtualFileIfNeeded(AS llvm::MemoryBuffer::getMemBuffer(Code)); } -template -NodeType importNode(ASTUnit *From, ASTUnit *To, ASTImporter &Importer, -NodeType Node) { - ASTContext &ToCtx = To->getASTContext(); - - // Add 'From' file to virtual file system so importer can 'find' it - // while importing SourceLocations. It is safe to add same file multiple - // times - it just isn't replaced. - StringRef FromFileName = From->getMainFileName(); - createVirtualFileIfNeeded(To, FromFileName, -From->getBufferForFile(FromFileName)); - - auto Imported = Importer.Import(Node); - - // This should dump source locations and assert if some source locations - // were not imported. - SmallString<1024> ImportChecker; - llvm::raw_svector_ostream ToNothing(ImportChecker); - ToCtx.getTranslationUnitDecl()->print(ToNothing); - - // This traverses the AST to catch certain bugs like poorly or not - // implemented subtrees. - Imported->dump(ToNothing); - - return Imported; -} - const StringRef DeclToImportID = "declToImport"; const StringRef DeclToVerifyID = "declToVerify"; -template -testing::AssertionResult -testImport(const std::string &FromCode, const ArgVector &FromArgs, - const std::string &ToCode, const ArgVector &ToArgs, - MatchVerifier &Verifier, - const BindableMatcher &SearchMatcher, - const BindableMatcher &VerificationMatcher) { - const char *const InputFileName = "input.cc"; - const char *const OutputFileName = "output.cc"; +// Common base for the different families of ASTImporter tests that are +// parameterized on the compiler options which may result a different AST. E.g. +// -fms-compatibility or -fdelayed-template-parsing. +struct ParameterizedTestsFixture : ::testing::TestWithParam { - std::unique_ptr - FromAST = tooling::buildASTFromCodeWithArgs( -FromCode, FromArgs, InputFileName), - ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, OutputFileName); - - ASTContext &FromCtx = FromAST->getASTContext(), - &ToCtx = ToAST->getASTContext(); - - FromAST->enableSourceFileDiagnostics(); - ToAST->enableSourceFileDiagnostics(); - - ASTImporter Importer(ToCtx, ToAST->getFileManager(), - FromCtx, FromAST->getFileManager(), false); - - auto FoundNodes = match(SearchMatcher, FromCtx); - if (FoundNodes.size() != 1) -return testing::AssertionFailure() - << "Multiple potential nodes were found!"; - - auto ToImport = selectFirst(DeclToImportID, FoundNodes); - if (!ToImport) -return testing::AssertionFailure() << "Node type mismatch!"; - - // Sanity check: the node being imported should match in the same way as - // the result node. - BindableMatcher WrapperMatcher(VerificationMatcher); - EXPECT_TRUE(Verifier.match(ToImport, WrapperMatcher)); - - auto Imported = importNode(FromAST.get(), ToAST.get(), Importer, ToImport); - if (!Imported) -return testing::AssertionFailure() << "Import failed, nullptr returned!"; - - return Verifier.match(Imported, WrapperMatcher); -} - -template -testing::AssertionResult -testImport(const std::string &FromCode, const ArgVector &FromArgs, - const std::string &ToCode, const ArgVector &ToArgs, - MatchVerifier &Verifier, - const BindableMatcher &VerificationMatcher) { - return testImport( - FromCode, FromArgs, ToCode, ToArgs, Verifier, - translationUnitDecl( - has(namedDecl(hasName(DeclToImportID)).bind(DeclToImportID))), - VerificationMatcher); -} - -/// Test how AST node named "declToImport" loc
[PATCH] D47367: [ASTImporter] Add ms compatibility to tests
This revision was automatically updated to reflect the committed changes. Closed by commit rC335464: [ASTImporter] Add ms compatibility to tests which use the TestBase (authored by martong, committed by ). Changed prior to commit: https://reviews.llvm.org/D47367?vs=152674&id=152675#toc Repository: rC Clang https://reviews.llvm.org/D47367 Files: unittests/AST/ASTImporterTest.cpp unittests/AST/Language.cpp unittests/AST/Language.h Index: unittests/AST/Language.h === --- unittests/AST/Language.h +++ unittests/AST/Language.h @@ -22,7 +22,6 @@ namespace ast_matchers { typedef std::vector ArgVector; -typedef std::vector RunOptions; enum Language { Lang_C, @@ -34,12 +33,7 @@ Lang_OBJCXX }; -inline bool isCXX(Language Lang) { - return Lang == Lang_CXX || Lang == Lang_CXX11 || Lang == Lang_CXX14; -} - ArgVector getBasicRunOptionsForLanguage(Language Lang); -RunOptions getRunOptionsForLanguage(Language Lang); } // end namespace ast_matchers } // end namespace clang Index: unittests/AST/Language.cpp === --- unittests/AST/Language.cpp +++ unittests/AST/Language.cpp @@ -42,19 +42,5 @@ return BasicArgs; } -RunOptions getRunOptionsForLanguage(Language Lang) { - ArgVector BasicArgs = getBasicRunOptionsForLanguage(Lang); - - // For C++, test with "-fdelayed-template-parsing" enabled to handle MSVC - // default behaviour. - if (isCXX(Lang)) { -ArgVector ArgsForDelayedTemplateParse = BasicArgs; -ArgsForDelayedTemplateParse.emplace_back("-fdelayed-template-parsing"); -return {BasicArgs, ArgsForDelayedTemplateParse}; - } - - return {BasicArgs}; -} - } // end namespace ast_matchers } // end namespace clang Index: unittests/AST/ASTImporterTest.cpp === --- unittests/AST/ASTImporterTest.cpp +++ unittests/AST/ASTImporterTest.cpp @@ -50,114 +50,233 @@ llvm::MemoryBuffer::getMemBuffer(Code)); } -template -NodeType importNode(ASTUnit *From, ASTUnit *To, ASTImporter &Importer, -NodeType Node) { - ASTContext &ToCtx = To->getASTContext(); - - // Add 'From' file to virtual file system so importer can 'find' it - // while importing SourceLocations. It is safe to add same file multiple - // times - it just isn't replaced. - StringRef FromFileName = From->getMainFileName(); - createVirtualFileIfNeeded(To, FromFileName, -From->getBufferForFile(FromFileName)); - - auto Imported = Importer.Import(Node); - - // This should dump source locations and assert if some source locations - // were not imported. - SmallString<1024> ImportChecker; - llvm::raw_svector_ostream ToNothing(ImportChecker); - ToCtx.getTranslationUnitDecl()->print(ToNothing); - - // This traverses the AST to catch certain bugs like poorly or not - // implemented subtrees. - Imported->dump(ToNothing); - - return Imported; -} - const StringRef DeclToImportID = "declToImport"; const StringRef DeclToVerifyID = "declToVerify"; -template -testing::AssertionResult -testImport(const std::string &FromCode, const ArgVector &FromArgs, - const std::string &ToCode, const ArgVector &ToArgs, - MatchVerifier &Verifier, - const BindableMatcher &SearchMatcher, - const BindableMatcher &VerificationMatcher) { - const char *const InputFileName = "input.cc"; - const char *const OutputFileName = "output.cc"; +// Common base for the different families of ASTImporter tests that are +// parameterized on the compiler options which may result a different AST. E.g. +// -fms-compatibility or -fdelayed-template-parsing. +struct ParameterizedTestsFixture : ::testing::TestWithParam { - std::unique_ptr - FromAST = tooling::buildASTFromCodeWithArgs( -FromCode, FromArgs, InputFileName), - ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, OutputFileName); - - ASTContext &FromCtx = FromAST->getASTContext(), - &ToCtx = ToAST->getASTContext(); - - FromAST->enableSourceFileDiagnostics(); - ToAST->enableSourceFileDiagnostics(); - - ASTImporter Importer(ToCtx, ToAST->getFileManager(), - FromCtx, FromAST->getFileManager(), false); - - auto FoundNodes = match(SearchMatcher, FromCtx); - if (FoundNodes.size() != 1) -return testing::AssertionFailure() - << "Multiple potential nodes were found!"; - - auto ToImport = selectFirst(DeclToImportID, FoundNodes); - if (!ToImport) -return testing::AssertionFailure() << "Node type mismatch!"; - - // Sanity check: the node being imported should match in the same way as - // the result node. - BindableMatcher WrapperMatcher(VerificationMatcher); - EXPECT_TRUE(Verifier.match(ToImport, WrapperMatcher)); - - auto Imported = importNode(FromAST.get(), ToAST.get(), Importer, ToImport); - if (!Imported) -
r335466 - [clang-cl] Don't emit dllexport inline functions etc. from pch files (PR37801)
Author: hans Date: Mon Jun 25 06:23:49 2018 New Revision: 335466 URL: http://llvm.org/viewvc/llvm-project?rev=335466&view=rev Log: [clang-cl] Don't emit dllexport inline functions etc. from pch files (PR37801) With MSVC, PCH files are created along with an object file that needs to be linked into the final library or executable. That object file contains the code generated when building the headers. In particular, it will include definitions of inline dllexport functions, and because they are emitted in this object file, other files using the PCH do not need to emit them. See the bug for an example. This patch makes clang-cl match MSVC's behaviour in this regard, causing significant compile-time savings when building dlls using precompiled headers. For example, in a 64-bit optimized shared library build of Chromium with PCH, it reduces the binary size and compile time of stroke_opacity_custom.obj from 9315564 bytes to 3659629 bytes and 14.6 to 6.63 s. The wall-clock time of building blink_core.dll goes from 38m41s to 22m33s. ("user" time goes from 1979m to 1142m). Differential Revision: https://reviews.llvm.org/D48426 Added: cfe/trunk/test/CodeGen/pch-dllexport.cpp Modified: cfe/trunk/include/clang/AST/ExternalASTSource.h cfe/trunk/include/clang/Basic/LangOptions.def cfe/trunk/include/clang/Driver/CC1Options.td cfe/trunk/include/clang/Sema/MultiplexExternalSemaSource.h cfe/trunk/include/clang/Serialization/ASTBitCodes.h cfe/trunk/include/clang/Serialization/ASTReader.h cfe/trunk/include/clang/Serialization/Module.h cfe/trunk/lib/AST/ASTContext.cpp cfe/trunk/lib/Driver/Driver.cpp cfe/trunk/lib/Driver/ToolChains/Clang.cpp cfe/trunk/lib/Frontend/CompilerInvocation.cpp cfe/trunk/lib/Frontend/FrontendActions.cpp cfe/trunk/lib/Sema/MultiplexExternalSemaSource.cpp cfe/trunk/lib/Serialization/ASTReader.cpp cfe/trunk/lib/Serialization/ASTWriter.cpp cfe/trunk/test/Driver/cl-pch.cpp Modified: cfe/trunk/include/clang/AST/ExternalASTSource.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ExternalASTSource.h?rev=335466&r1=335465&r2=335466&view=diff == --- cfe/trunk/include/clang/AST/ExternalASTSource.h (original) +++ cfe/trunk/include/clang/AST/ExternalASTSource.h Mon Jun 25 06:23:49 2018 @@ -163,6 +163,10 @@ public: /// Retrieve the module that corresponds to the given module ID. virtual Module *getModule(unsigned ID) { return nullptr; } + /// Determine whether D comes from a PCH which was built with a corresponding + /// object file. + virtual bool DeclIsFromPCHWithObjectFile(const Decl *D) { return false; } + /// Abstracts clang modules and precompiled header files and holds /// everything needed to generate debug info for an imported module /// or PCH. Modified: cfe/trunk/include/clang/Basic/LangOptions.def URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/LangOptions.def?rev=335466&r1=335465&r2=335466&view=diff == --- cfe/trunk/include/clang/Basic/LangOptions.def (original) +++ cfe/trunk/include/clang/Basic/LangOptions.def Mon Jun 25 06:23:49 2018 @@ -154,6 +154,7 @@ COMPATIBLE_LANGOPT(ModulesTS , 1, 0, "C BENIGN_ENUM_LANGOPT(CompilingModule, CompilingModuleKind, 2, CMK_None, "compiling a module interface") BENIGN_LANGOPT(CompilingPCH, 1, 0, "building a pch") +BENIGN_LANGOPT(BuildingPCHWithObjectFile, 1, 0, "building a pch which has a corresponding object file") COMPATIBLE_LANGOPT(ModulesDeclUse, 1, 0, "require declaration of module uses") BENIGN_LANGOPT(ModulesSearchAll , 1, 1, "searching even non-imported modules to find unresolved references") COMPATIBLE_LANGOPT(ModulesStrictDeclUse, 1, 0, "requiring declaration of module uses and all headers to be in modules") Modified: cfe/trunk/include/clang/Driver/CC1Options.td URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=335466&r1=335465&r2=335466&view=diff == --- cfe/trunk/include/clang/Driver/CC1Options.td (original) +++ cfe/trunk/include/clang/Driver/CC1Options.td Mon Jun 25 06:23:49 2018 @@ -609,7 +609,9 @@ def find_pch_source_EQ : Joined<["-"], " "to this flag.">; def fno_pch_timestamp : Flag<["-"], "fno-pch-timestamp">, HelpText<"Disable inclusion of timestamp in precompiled headers">; - +def building_pch_with_obj : Flag<["-"], "building-pch-with-obj">, + HelpText<"This compilation is part of building a PCH with corresponding object file.">; + def aligned_alloc_unavailable : Flag<["-"], "faligned-alloc-unavailable">, HelpText<"Aligned allocation/deallocation functions are unavailable">; Modified: cfe/trunk/include/clang/Sema/MultiplexExternalSemaSource.h URL: http://llvm.org/viewvc/llvm-project/cf
[PATCH] D48426: [clang-cl] Don't emit dllexport inline functions etc. from pch files (PR37801)
This revision was automatically updated to reflect the committed changes. Closed by commit rC335466: [clang-cl] Don't emit dllexport inline functions etc. from pch files (PR37801) (authored by hans, committed by ). Repository: rC Clang https://reviews.llvm.org/D48426 Files: include/clang/AST/ExternalASTSource.h include/clang/Basic/LangOptions.def include/clang/Driver/CC1Options.td include/clang/Sema/MultiplexExternalSemaSource.h include/clang/Serialization/ASTBitCodes.h include/clang/Serialization/ASTReader.h include/clang/Serialization/Module.h lib/AST/ASTContext.cpp lib/Driver/Driver.cpp lib/Driver/ToolChains/Clang.cpp lib/Frontend/CompilerInvocation.cpp lib/Frontend/FrontendActions.cpp lib/Sema/MultiplexExternalSemaSource.cpp lib/Serialization/ASTReader.cpp lib/Serialization/ASTWriter.cpp test/CodeGen/pch-dllexport.cpp test/Driver/cl-pch.cpp Index: lib/AST/ASTContext.cpp === --- lib/AST/ASTContext.cpp +++ lib/AST/ASTContext.cpp @@ -9553,6 +9553,29 @@ else return false; + if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) { +assert(getExternalSource() && "It's from an AST file; must have a source."); +// On Windows, PCH files are built together with an object file. If this +// declaration comes from such a PCH and DeclMustBeEmitted would return +// true, it would have returned true and the decl would have been emitted +// into that object file, so it doesn't need to be emitted here. +// Note that decls are still emitted if they're referenced, as usual; +// DeclMustBeEmitted is used to decide whether a decl must be emitted even +// if it's not referenced. +// +// Explicit template instantiation definitions are tricky. If there was an +// explicit template instantiation decl in the PCH before, it will look like +// the definition comes from there, even if that was just the declaration. +// (Explicit instantiation defs of variable templates always get emitted.) +bool IsExpInstDef = +isa(D) && +cast(D)->getTemplateSpecializationKind() == +TSK_ExplicitInstantiationDefinition; + +if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef) + return false; + } + // If this is a member of a class template, we do not need to emit it. if (D->getDeclContext()->isDependentContext()) return false; @@ -9573,7 +9596,7 @@ // Constructors and destructors are required. if (FD->hasAttr() || FD->hasAttr()) return true; - + // The key function for a class is required. This rule only comes // into play when inline functions can be key functions, though. if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { @@ -9594,7 +9617,7 @@ // Implicit template instantiations can also be deferred in C++. return !isDiscardableGVALinkage(Linkage); } - + const auto *VD = cast(D); assert(VD->isFileVarDecl() && "Expected file scoped var"); Index: lib/Sema/MultiplexExternalSemaSource.cpp === --- lib/Sema/MultiplexExternalSemaSource.cpp +++ lib/Sema/MultiplexExternalSemaSource.cpp @@ -171,6 +171,13 @@ return nullptr; } +bool MultiplexExternalSemaSource::DeclIsFromPCHWithObjectFile(const Decl *D) { + for (auto *S : Sources) +if (S->DeclIsFromPCHWithObjectFile(D)) + return true; + return false; +} + bool MultiplexExternalSemaSource::layoutRecordType(const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment, Index: lib/Frontend/CompilerInvocation.cpp === --- lib/Frontend/CompilerInvocation.cpp +++ lib/Frontend/CompilerInvocation.cpp @@ -2776,6 +2776,7 @@ } Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers); + Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj); } static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { Index: lib/Frontend/FrontendActions.cpp === --- lib/Frontend/FrontendActions.cpp +++ lib/Frontend/FrontendActions.cpp @@ -112,14 +112,14 @@ if (!CI.getFrontendOpts().RelocatablePCH) Sysroot.clear(); + const auto &FrontendOpts = CI.getFrontendOpts(); auto Buffer = std::make_shared(); std::vector> Consumers; Consumers.push_back(llvm::make_unique( CI.getPreprocessor(), OutputFile, Sysroot, -Buffer, CI.getFrontendOpts().ModuleFileExtensions, - /*AllowASTWithErrors*/CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, -/*IncludeTimestamps*/ - +CI.getFrontendOpts().IncludeTimestamps)); +Buffer, FrontendOpts.
[PATCH] D46013: [ARM] Conform to AAPCS when passing overaligned composites as arguments
chill updated this revision to Diff 152679. chill added a comment. Update: use "unadjusted alignment" instead of "natural alignment", rename things accordingly. https://reviews.llvm.org/D46013 Files: include/clang/AST/ASTContext.h include/clang/AST/RecordLayout.h lib/AST/ASTContext.cpp lib/AST/RecordLayout.cpp lib/AST/RecordLayoutBuilder.cpp lib/CodeGen/TargetInfo.cpp test/CodeGen/aapcs-align.cc test/CodeGen/aapcs64-align.cc test/CodeGen/arm-arguments.c Index: test/CodeGen/arm-arguments.c === --- test/CodeGen/arm-arguments.c +++ test/CodeGen/arm-arguments.c @@ -211,10 +211,13 @@ // APCS-GNU: call void @llvm.memcpy.p0i8.p0i8.i32(i8* align {{[0-9]+}} %[[b]], i8* align {{[0-9]+}} %[[c]] // APCS-GNU: %[[d:.*]] = bitcast %struct.s35* %[[a]] to <4 x float>* // APCS-GNU: load <4 x float>, <4 x float>* %[[d]], align 16 -// AAPCS-LABEL: define arm_aapcscc <4 x float> @f35(i32 %i, %struct.s35* byval align 8, %struct.s35* byval align 8) -// AAPCS: %[[a:.*]] = alloca %struct.s35, align 16 -// AAPCS: %[[b:.*]] = bitcast %struct.s35* %[[a]] to i8* -// AAPCS: %[[c:.*]] = bitcast %struct.s35* %0 to i8* -// AAPCS: call void @llvm.memcpy.p0i8.p0i8.i32(i8* align 16 %[[b]], i8* align 8 %[[c]] -// AAPCS: %[[d:.*]] = bitcast %struct.s35* %[[a]] to <4 x float>* -// AAPCS: load <4 x float>, <4 x float>* %[[d]], align 16 + +// AAPCS-LABEL: define arm_aapcscc <4 x float> @f35(i32 %i, %struct.s35* byval align 4 %s1, %struct.s35* byval align 4 %s2) +// AAPCS: %[[a_addr:.*]] = alloca <4 x float>, align 16 +// AAPCS: %[[b_addr:.*]] = alloca <4 x float>, align 16 +// AAPCS: %[[p1:.*]] = bitcast %struct.s35* %s1 to <4 x float>* +// AAPCS: %[[a:.*]] = load <4 x float>, <4 x float>* %[[p1]], align 4 +// AAPCS: %[[p2:.*]] = bitcast %struct.s35* %s2 to <4 x float>* +// AAPCS: %[[b:.*]] = load <4 x float>, <4 x float>* %[[p2]], align 4 +// AAPCS: store <4 x float> %[[a]], <4 x float>* %[[a_addr]], align 16 +// AAPCS: store <4 x float> %[[b]], <4 x float>* %[[b_addr]], align 16 Index: test/CodeGen/aapcs64-align.cc === --- /dev/null +++ test/CodeGen/aapcs64-align.cc @@ -0,0 +1,103 @@ +// REQUIRES: arm-registered-target +// RUN: %clang_cc1 -triple aarch64-none-none-eabi \ +// RUN: -O2 \ +// RUN: -emit-llvm -o - %s | FileCheck %s + +extern "C" { + +// Base case, nothing interesting. +struct S { + long x, y; +}; + +void f0(long, S); +void f0m(long, long, long, long, long, S); +void g0() { + S s = {6, 7}; + f0(1, s); + f0m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g0 +// CHECK: call void @f0(i64 1, [2 x i64] [i64 6, i64 7] +// CHECK: call void @f0m{{.*}}[2 x i64] [i64 6, i64 7] +// CHECK: declare void @f0(i64, [2 x i64]) +// CHECK: declare void @f0m(i64, i64, i64, i64, i64, [2 x i64]) + +// Aligned struct, passed according to its natural alignment. +struct __attribute__((aligned(16))) S16 { + long x, y; +} s16; + +void f1(long, S16); +void f1m(long, long, long, long, long, S16); +void g1() { + S16 s = {6, 7}; + f1(1, s); + f1m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g1 +// CHECK: call void @f1{{.*}}[2 x i64] [i64 6, i64 7] +// CHECK: call void @f1m{{.*}}[2 x i64] [i64 6, i64 7] +// CHECK: declare void @f1(i64, [2 x i64]) +// CHECK: declare void @f1m(i64, i64, i64, i64, i64, [2 x i64]) + +// Increased natural alignment. +struct SF16 { + long x __attribute__((aligned(16))); + long y; +}; + +void f3(long, SF16); +void f3m(long, long, long, long, long, SF16); +void g3() { + SF16 s = {6, 7}; + f3(1, s); + f3m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g3 +// CHECK: call void @f3(i64 1, i128 129127208515966861318) +// CHECK: call void @f3m(i64 1, i64 2, i64 3, i64 4, i64 5, i128 129127208515966861318) +// CHECK: declare void @f3(i64, i128) +// CHECK: declare void @f3m(i64, i64, i64, i64, i64, i128) + + +// Packed structure. +struct __attribute__((packed)) P { + int x; + long u; +}; + +void f4(int, P); +void f4m(int, int, int, int, int, P); +void g4() { + P s = {6, 7}; + f4(1, s); + f4m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g4() +// CHECK: call void @f4(i32 1, [2 x i64] [i64 30064771078, i64 0]) +// CHECK: void @f4m(i32 1, i32 2, i32 3, i32 4, i32 5, [2 x i64] [i64 30064771078, i64 0]) +// CHECK: declare void @f4(i32, [2 x i64]) +// CHECK: declare void @f4m(i32, i32, i32, i32, i32, [2 x i64]) + + +// Packed structure, overaligned, same as above. +struct __attribute__((packed, aligned(16))) P16 { + int x; + long y; +}; + +void f5(int, P16); +void f5m(int, int, int, int, int, P16); + void g5() { +P16 s = {6, 7}; +f5(1, s); +f5m(1, 2, 3, 4, 5, s); +} +// CHECK: define void @g5() +// CHECK: call void @f5(i32 1, [2 x i64] [i64 30064771078, i64 0]) +// CHECK: void @f5m(i32 1, i32 2, i32 3, i32 4, i32 5, [2 x i64] [i64 30064771078, i64 0]) +// CHECK: declare void @f5(i32, [2 x i64]) +// CHECK: declare void @f5m(i32, i32, i32, i32, i32, [2 x i64]) + +}
[PATCH] D45454: Make __gcov_flush visible outside a shared library
marco-c added a comment. In https://reviews.llvm.org/D45454#1070884, @belleyb wrote: > @chh I had a chance to try out your proposed changes. It's not causing us any > trouble. In fact, `__gcov_flush()` is not even used at all (at least in LLVM > 5.0.1).. I can recompile llvm, compiler_rt and clang and re-run all the tests > with `__gcov_flush` commented out! No problem. > > I would suggest adding a bit more documentation to `__gcov_flush()`, thus > describing what those "special cases" are... __gcov_flush is only used if you actually call it (it's needed for example if you want to profile only part of your program). In GCC, __gcov_flush is not hidden, so perhaps we should do the same to keep the same behavior? I've also submitted https://reviews.llvm.org/D48538, which is making __gcov_flush flush counters for all shared libraries (like GCC does, with the same caveat: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83879). https://reviews.llvm.org/D45454 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48549: Use Triple::isMIPS() instead of enumerating all Triples. NFC
arichardson created this revision. arichardson added a reviewer: atanasyan. Herald added subscribers: cfe-commits, sdardis, emaste. Repository: rC Clang https://reviews.llvm.org/D48549 Files: lib/Basic/Targets/Mips.cpp lib/Basic/Targets/Mips.h lib/Driver/ToolChains/Arch/Mips.cpp lib/Driver/ToolChains/Arch/Mips.h lib/Driver/ToolChains/CommonArgs.cpp lib/Driver/ToolChains/FreeBSD.cpp lib/Driver/ToolChains/Gnu.cpp lib/Driver/ToolChains/Linux.cpp lib/Driver/ToolChains/NetBSD.cpp lib/Driver/ToolChains/OpenBSD.cpp Index: lib/Driver/ToolChains/OpenBSD.cpp === --- lib/Driver/ToolChains/OpenBSD.cpp +++ lib/Driver/ToolChains/OpenBSD.cpp @@ -68,10 +68,10 @@ CmdArgs.push_back("-mabi"); CmdArgs.push_back(mips::getGnuCompatibleMipsABIName(ABIName).data()); -if (getToolChain().getArch() == llvm::Triple::mips64) - CmdArgs.push_back("-EB"); -else +if (getToolChain().getTriple().isLittleEndian()) CmdArgs.push_back("-EL"); +else + CmdArgs.push_back("-EB"); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; Index: lib/Driver/ToolChains/NetBSD.cpp === --- lib/Driver/ToolChains/NetBSD.cpp +++ lib/Driver/ToolChains/NetBSD.cpp @@ -64,11 +64,10 @@ CmdArgs.push_back("-mabi"); CmdArgs.push_back(mips::getGnuCompatibleMipsABIName(ABIName).data()); -if (getToolChain().getArch() == llvm::Triple::mips || -getToolChain().getArch() == llvm::Triple::mips64) - CmdArgs.push_back("-EB"); -else +if (getToolChain().getTriple().isLittleEndian()) CmdArgs.push_back("-EL"); +else + CmdArgs.push_back("-EB"); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; Index: lib/Driver/ToolChains/Linux.cpp === --- lib/Driver/ToolChains/Linux.cpp +++ lib/Driver/ToolChains/Linux.cpp @@ -156,7 +156,7 @@ } static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) { - if (tools::isMipsArch(Triple.getArch())) { + if (Triple.isMIPS()) { if (Triple.isAndroid()) { StringRef CPUName; StringRef ABIName; @@ -242,7 +242,7 @@ ExtraOpts.push_back("-X"); const bool IsAndroid = Triple.isAndroid(); - const bool IsMips = tools::isMipsArch(Arch); + const bool IsMips = Triple.isMIPS(); const bool IsHexagon = Arch == llvm::Triple::hexagon; const bool IsRISCV = Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64; @@ -438,7 +438,7 @@ return AndroidSysRootPath; } - if (!GCCInstallation.isValid() || !tools::isMipsArch(getTriple().getArch())) + if (!GCCInstallation.isValid() || !getTriple().isMIPS()) return std::string(); // Standalone MIPS toolchains use different names for sysroot folder @@ -530,17 +530,15 @@ case llvm::Triple::mipsel: case llvm::Triple::mips64: case llvm::Triple::mips64el: { -bool LE = (Triple.getArch() == llvm::Triple::mipsel) || - (Triple.getArch() == llvm::Triple::mips64el); bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple); LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple); if (tools::mips::isUCLibc(Args)) Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0"; else if (!Triple.hasEnvironment() && Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies) - Loader = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1"; + Loader = Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1"; else Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1"; @@ -894,10 +892,8 @@ SanitizerMask Linux::getSupportedSanitizers() const { const bool IsX86 = getTriple().getArch() == llvm::Triple::x86; const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64; - const bool IsMIPS = getTriple().getArch() == llvm::Triple::mips || - getTriple().getArch() == llvm::Triple::mipsel; - const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 || -getTriple().getArch() == llvm::Triple::mips64el; + const bool IsMIPS = getTriple().isMIPS32(); + const bool IsMIPS64 = getTriple().isMIPS64(); const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 || getTriple().getArch() == llvm::Triple::ppc64le; const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 || Index: lib/Driver/ToolChains/Gnu.cpp === --- lib/Driver/ToolChains/Gnu.cpp +++ lib/Driver/ToolChains/Gnu.cpp @@ -707,11 +707,10 @@ if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls)) CmdArgs.push_back("-call_nonpic"); -if (getToolChain().getArch() == llvm::Triple::mips || -getToolChain().getArch() == llvm::Triple::mips64) -
[PATCH] D46845: [libcxx][c++17] P0083R5: Splicing Maps and Sets
erik.pilkington added a comment. Ping! If it'd make this easier to review, I'd be happy to split this up a bit. https://reviews.llvm.org/D46845 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48549: Use Triple::isMIPS() instead of enumerating all Triples. NFC
atanasyan accepted this revision. atanasyan added a comment. This revision is now accepted and ready to land. LGTM. the only minor nit Comment at: lib/Driver/ToolChains/FreeBSD.cpp:321 // back to '/usr/lib' if it doesn't exist. - if ((Triple.getArch() == llvm::Triple::x86 || - Triple.getArch() == llvm::Triple::mips || - Triple.getArch() == llvm::Triple::mipsel || - Triple.getArch() == llvm::Triple::ppc) && + if ((Triple.getArch() == llvm::Triple::x86 || Triple.isMIPS32() || Triple.getArch() == llvm::Triple::ppc) && D.getVFS().exists(getDriver().SysRoot + "/usr/lib32/crt1.o")) Too long line. Repository: rC Clang https://reviews.llvm.org/D48549 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47532: [ASTImporter] Import the whole redecl chain of functions
martong updated this revision to Diff 152691. martong marked 3 inline comments as done. martong added a comment. - Address review comments Repository: rC Clang https://reviews.llvm.org/D47532 Files: include/clang/AST/ASTImporter.h lib/AST/ASTImporter.cpp lib/AST/DeclBase.cpp test/ASTMerge/class/test.cpp unittests/AST/ASTImporterTest.cpp Index: unittests/AST/ASTImporterTest.cpp === --- unittests/AST/ASTImporterTest.cpp +++ unittests/AST/ASTImporterTest.cpp @@ -20,7 +20,7 @@ #include "DeclMatcher.h" #include "Language.h" -#include "gtest/gtest.h" +#include "gmock/gmock.h" #include "llvm/ADT/StringMap.h" namespace clang { @@ -428,6 +428,48 @@ struct ImportType : TestImportBase {}; struct ImportDecl : TestImportBase {}; +struct CanonicalRedeclChain : ASTImporterTestBase {}; + +TEST_P(CanonicalRedeclChain, ShouldBeConsequentWithMatchers) { + Decl *FromTU = getTuDecl("void f();", Lang_CXX); + auto Pattern = functionDecl(hasName("f")); + auto *D0 = FirstDeclMatcher().match(FromTU, Pattern); + + auto Redecls = getCanonicalForwardRedeclChain(D0); + ASSERT_EQ(Redecls.size(), 1u); + EXPECT_EQ(D0, Redecls[0]); +} + +TEST_P(CanonicalRedeclChain, ShouldBeConsequentWithMatchers2) { + Decl *FromTU = getTuDecl("void f(); void f(); void f();", Lang_CXX); + auto Pattern = functionDecl(hasName("f")); + auto *D0 = FirstDeclMatcher().match(FromTU, Pattern); + auto *D2 = LastDeclMatcher().match(FromTU, Pattern); + FunctionDecl *D1 = D2->getPreviousDecl(); + + auto Redecls = getCanonicalForwardRedeclChain(D0); + ASSERT_EQ(Redecls.size(), 3u); + EXPECT_EQ(D0, Redecls[0]); + EXPECT_EQ(D1, Redecls[1]); + EXPECT_EQ(D2, Redecls[2]); +} + +TEST_P(CanonicalRedeclChain, ShouldBeSameForAllDeclInTheChain) { + Decl *FromTU = getTuDecl("void f(); void f(); void f();", Lang_CXX); + auto Pattern = functionDecl(hasName("f")); + auto *D0 = FirstDeclMatcher().match(FromTU, Pattern); + auto *D2 = LastDeclMatcher().match(FromTU, Pattern); + FunctionDecl *D1 = D2->getPreviousDecl(); + + auto RedeclsD0 = getCanonicalForwardRedeclChain(D0); + auto RedeclsD1 = getCanonicalForwardRedeclChain(D1); + auto RedeclsD2 = getCanonicalForwardRedeclChain(D2); + + EXPECT_THAT(RedeclsD0, ::testing::ContainerEq(RedeclsD1)); + EXPECT_THAT(RedeclsD1, ::testing::ContainerEq(RedeclsD2)); +} + + TEST_P(ImportExpr, ImportStringLiteral) { MatchVerifier Verifier; testImport("void declToImport() { \"foo\"; }", @@ -1673,34 +1715,6 @@ struct ImportFunctions : ASTImporterTestBase {}; TEST_P(ImportFunctions, - PrototypeShouldBeImportedAsAPrototypeWhenThereIsNoDefinition) { - Decl *FromTU = getTuDecl("void f();", Lang_CXX); - auto Pattern = functionDecl(hasName("f")); - FunctionDecl *FromD = - FirstDeclMatcher().match(FromTU, Pattern); - - Decl *ImportedD = Import(FromD, Lang_CXX); - Decl *ToTU = ImportedD->getTranslationUnitDecl(); - - EXPECT_EQ(DeclCounter().match(ToTU, Pattern), 1u); - EXPECT_TRUE(!cast(ImportedD)->doesThisDeclarationHaveABody()); -} - -TEST_P(ImportFunctions, - PrototypeShouldBeImportedAsDefintionWhenThereIsADefinition) { - Decl *FromTU = getTuDecl("void f(); void f() {}", Lang_CXX); - auto Pattern = functionDecl(hasName("f")); - FunctionDecl *FromD = // Prototype - FirstDeclMatcher().match(FromTU, Pattern); - - Decl *ImportedD = Import(FromD, Lang_CXX); - Decl *ToTU = ImportedD->getTranslationUnitDecl(); - - EXPECT_EQ(DeclCounter().match(ToTU, Pattern), 1u); - EXPECT_TRUE(cast(ImportedD)->doesThisDeclarationHaveABody()); -} - -TEST_P(ImportFunctions, DefinitionShouldBeImportedAsDefintionWhenThereIsAPrototype) { Decl *FromTU = getTuDecl("void f(); void f() {}", Lang_CXX); auto Pattern = functionDecl(hasName("f")); @@ -1710,7 +1724,7 @@ Decl *ImportedD = Import(FromD, Lang_CXX); Decl *ToTU = ImportedD->getTranslationUnitDecl(); - EXPECT_EQ(DeclCounter().match(ToTU, Pattern), 1u); + EXPECT_EQ(DeclCounter().match(ToTU, Pattern), 2u); EXPECT_TRUE(cast(ImportedD)->doesThisDeclarationHaveABody()); } @@ -1727,80 +1741,116 @@ EXPECT_TRUE(cast(ImportedD)->doesThisDeclarationHaveABody()); } -TEST_P(ImportFunctions, DISABLED_ImportPrototypeOfRecursiveFunction) { +TEST_P(ImportFunctions, ImportPrototypeOfRecursiveFunction) { Decl *FromTU = getTuDecl("void f(); void f() { f(); }", Lang_CXX); auto Pattern = functionDecl(hasName("f")); - FunctionDecl *PrototypeFD = - FirstDeclMatcher().match(FromTU, Pattern); + auto *From = + FirstDeclMatcher().match(FromTU, Pattern); // Proto - Decl *ImportedD = Import(PrototypeFD, Lang_CXX); + Decl *ImportedD = Import(From, Lang_CXX); Decl *ToTU = ImportedD->getTranslationUnitDecl(); - EXPECT_EQ(DeclCounter().match(ToTU, Pattern), 1u); - EXPECT_TRUE(cast(ImportedD)->doesThisDeclarationHaveABody()); + EXPECT_EQ(DeclCounter().match(ToTU, Pattern), 2u); + auto *To0 = FirstDeclMatcher().match(ToTU, Pattern); +
[PATCH] D47532: [ASTImporter] Import the whole redecl chain of functions
martong added inline comments. Comment at: unittests/AST/ASTImporterTest.cpp:2021 + +TEST_P(ImportFriendFunctions, + DISABLED_ImportFriendFunctionRedeclChainDefWithClass_ImportTheProto) { a_sidorin wrote: > Could you add comments why these tests are disabled? Added the comment, plus copied the explanation here as well. This test is disabled, because ATM we create a redundant FunctionDecl. We start the import with the definition of `f` then we continue with the import of the type of `f` which involves `X`. During the import of `X` we start again the import of the definition of `f` and then finally we create the node. But then in the first frame of `VisitFunctionDecl` we create a node again since we do not check if such a node exists yet or not. This is being fixed in a separate patch: https://reviews.llvm.org/D47632 . Backtrace to support the above explanation: ``` #0 clang::ASTNodeImporter::VisitFunctionDecl (this=0x7fffae30, D=0xb02b68) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:2372 #1 0x7694adbc in clang::declvisitor::Base::Visit (this=0x7fffae30, D=0xb02b68) at tools/clang/include/clang/AST/DeclNodes.inc:389 #2 0x7690fa64 in clang::ASTImporter::Import (this=0x7fffca18, FromD=0xb02b68) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:6821 #3 0x76920570 in clang::ASTNodeImporter::VisitFriendDecl (this=0x7fffb1e0, D=0xb02c20) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:2844 #4 0x7694a95c in clang::declvisitor::Base::Visit (this=0x7fffb1e0, D=0xb02c20) at tools/clang/include/clang/AST/DeclNodes.inc:71 #5 0x7690fa64 in clang::ASTImporter::Import (this=0x7fffca18, FromD=0xb02c20) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:6821 #6 0x76916a27 in clang::ASTNodeImporter::ImportDeclContext (this=0x7fffb9b0, FromDC=0xb02970, ForceImport=true) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:1161 #7 0x769164a0 in clang::ASTNodeImporter::ImportDefinition (this=0x7fffb9b0, From=0xb02938, To=0xbcea58, Kind=clang::ASTNodeImporter::IDK_Default) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:1287 #8 0x7691bdf0 in clang::ASTNodeImporter::VisitRecordDecl (this=0x7fffb9b0, D=0xb02938) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:2215 #9 0x76964678 in clang::declvisitor::Base::VisitCXXRecordDecl (this=0x7fffb9b0, D=0xb02938) at tools/clang/include/clang/AST/DeclNodes.inc:251 #10 0x7694abe0 in clang::declvisitor::Base::Visit (this=0x7fffb9b0, D=0xb02938) at tools/clang/include/clang/AST/DeclNodes.inc:251 #11 0x7690fa64 in clang::ASTImporter::Import (this=0x7fffca18, FromD=0xb02938) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:6821 #12 0x769128e7 in clang::ASTNodeImporter::VisitRecordType (this=0x7fffbac0, T=0xb02720) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:857 #13 0x7694a254 in clang::TypeVisitor::Visit (this=0x7fffbac0, T=0xb02720) at ../../git/llvm/tools/clang/include/clang/AST/TypeNodes.def:92 #14 0x7690ff05 in clang::ASTImporter::Import (this=0x7fffca18, FromT=...) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:6765 #15 0x7691107c in clang::ASTNodeImporter::VisitPointerType (this=0x7fffbc50, T=0xb02740) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:570 #16 0x76949fb4 in clang::TypeVisitor::Visit (this=0x7fffbc50, T=0xb02740) at ../../git/llvm/tools/clang/include/clang/AST/TypeNodes.def:64 #17 0x7690ff05 in clang::ASTImporter::Import (this=0x7fffca18, FromT=...) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:6765 #18 0x76911d21 in clang::ASTNodeImporter::VisitFunctionProtoType (this=0x7fffbf90, T=0xb027e0) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:712 #19 0x7694a120 in clang::TypeVisitor::Visit (this=0x7fffbf90, T=0xb027e0) at ../../git/llvm/tools/clang/include/clang/AST/TypeNodes.def:80 #20 0x7690ff05 in clang::ASTImporter::Import (this=0x7fffca18, FromT=...) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:6765 #21 0x7691d55a in clang::ASTNodeImporter::VisitFunctionDecl (this=0x7fffc990, D=0xb02840) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:2482 #22 0x7694adbc in clang::declvisitor::Base::Visit (this=0x7fffc990, D=0xb02840) at tools/clang/include/clang/AST/DeclNodes.inc:389 #23 0x7690fa64 in clang::ASTImporter::Import (this=0x7fffca18, FromD=0xb02840) at ../../git/llvm/tools/clang/lib/AST/ASTImporter.cpp:6821 #24 0x004d4673 in clang::ast_matchers::ASTImporterTestBase::Import (this=0xa9e620, From=0xb02840, ToLang=clang::ast_matchers::Lang_CXX) at ../../git/llvm/tools/clang/unittests/AST/ASTImporterTest.cpp:300 ``` Repository: rC Clang https://reviews.llvm.org/D47532 _
r335480 - [ASTImporter] Import the whole redecl chain of functions
Author: martong Date: Mon Jun 25 07:41:58 2018 New Revision: 335480 URL: http://llvm.org/viewvc/llvm-project?rev=335480&view=rev Log: [ASTImporter] Import the whole redecl chain of functions Summary: With this patch when any `FunctionDecl` of a redeclaration chain is imported then we bring in the whole declaration chain. This involves functions and function template specializations. Also friend functions are affected. The chain is imported as it is in the "from" tu, the order of the redeclarations are kept. I also changed the lookup logic in order to find friends, but first making them visible in their declaration context. We may have long redeclaration chains if all TU contains the same prototype, but our measurements shows no degradation in time of CTU analysis (Tmux, Xerces, Bitcoin, Protobuf). Also, as further work we could squash redundant prototypes, but first ensure that functionality is working properly; then should we optimize. This may seem like a huge patch, sorry about that. But, most of the changes are new tests, changes in the production code is not that much. I also tried to create a smaller patch which does not affect specializations, but that patch failed to pass some of the `clang-import-test`s because there we import function specializations. Also very importantly, we can't just change the import of `FunctionDecl`s without changing the import of function template specializations because they are handled as `FunctionDecl`s. Reviewers: a.sidorin, r.stahl, xazax.hun, balazske Subscribers: rnkovacs, dkrupp, cfe-commits Differential Revision: https://reviews.llvm.org/D47532 Modified: cfe/trunk/include/clang/AST/ASTImporter.h cfe/trunk/lib/AST/ASTImporter.cpp cfe/trunk/lib/AST/DeclBase.cpp cfe/trunk/test/ASTMerge/class/test.cpp cfe/trunk/unittests/AST/ASTImporterTest.cpp Modified: cfe/trunk/include/clang/AST/ASTImporter.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTImporter.h?rev=335480&r1=335479&r2=335480&view=diff == --- cfe/trunk/include/clang/AST/ASTImporter.h (original) +++ cfe/trunk/include/clang/AST/ASTImporter.h Mon Jun 25 07:41:58 2018 @@ -43,6 +43,15 @@ class TagDecl; class TypeSourceInfo; class Attr; + // \brief Returns with a list of declarations started from the canonical decl + // then followed by subsequent decls in the translation unit. + // This gives a canonical list for each entry in the redecl chain. + // `Decl::redecls()` gives a list of decls which always start from the + // previous decl and the next item is actually the previous item in the order + // of source locations. Thus, `Decl::redecls()` gives different lists for + // the different entries in a given redecl chain. + llvm::SmallVector getCanonicalForwardRedeclChain(Decl* D); + /// Imports selected nodes from one AST context into another context, /// merging AST nodes where appropriate. class ASTImporter { Modified: cfe/trunk/lib/AST/ASTImporter.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=335480&r1=335479&r2=335480&view=diff == --- cfe/trunk/lib/AST/ASTImporter.cpp (original) +++ cfe/trunk/lib/AST/ASTImporter.cpp Mon Jun 25 07:41:58 2018 @@ -71,6 +71,25 @@ namespace clang { + template + SmallVector + getCanonicalForwardRedeclChain(Redeclarable* D) { +SmallVector Redecls; +for (auto *R : D->getFirstDecl()->redecls()) { + if (R != D->getFirstDecl()) +Redecls.push_back(R); +} +Redecls.push_back(D->getFirstDecl()); +std::reverse(Redecls.begin(), Redecls.end()); +return Redecls; + } + + SmallVector getCanonicalForwardRedeclChain(Decl* D) { +// Currently only FunctionDecl is supported +auto FD = cast(D); +return getCanonicalForwardRedeclChain(FD); + } + class ASTNodeImporter : public TypeVisitor, public DeclVisitor, public StmtVisitor { @@ -195,6 +214,12 @@ namespace clang { const InContainerTy &Container, TemplateArgumentListInfo &Result); +using TemplateArgsTy = SmallVector; +using OptionalTemplateArgsTy = Optional; +std::tuple +ImportFunctionTemplateWithTemplateArgsFromSpecialization( +FunctionDecl *FromFD); + bool ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD); bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, @@ -408,6 +433,8 @@ namespace clang { // Importing overrides. void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod); + +FunctionDecl *FindFunctionTemplateSpecialization(FunctionDecl *FromFD); }; template @@ -437,6 +464,25 @@ bool ASTNodeImporter::ImportTemplateArgu From.arguments(),
[PATCH] D47532: [ASTImporter] Import the whole redecl chain of functions
This revision was automatically updated to reflect the committed changes. Closed by commit rC335480: [ASTImporter] Import the whole redecl chain of functions (authored by martong, committed by ). Changed prior to commit: https://reviews.llvm.org/D47532?vs=152691&id=152693#toc Repository: rC Clang https://reviews.llvm.org/D47532 Files: include/clang/AST/ASTImporter.h lib/AST/ASTImporter.cpp lib/AST/DeclBase.cpp test/ASTMerge/class/test.cpp unittests/AST/ASTImporterTest.cpp Index: test/ASTMerge/class/test.cpp === --- test/ASTMerge/class/test.cpp +++ test/ASTMerge/class/test.cpp @@ -13,12 +13,12 @@ // CHECK: class1.cpp:19:3: note: enumerator 'b' with value 1 here // CHECK: class2.cpp:12:3: note: enumerator 'a' with value 0 here -// CHECK: class1.cpp:36:8: warning: type 'F2' has incompatible definitions in different translation units -// CHECK: class1.cpp:39:3: note: friend declared here -// CHECK: class2.cpp:30:8: note: no corresponding friend here - // CHECK: class1.cpp:43:8: warning: type 'F3' has incompatible definitions in different translation units // CHECK: class1.cpp:46:3: note: friend declared here // CHECK: class2.cpp:36:8: note: no corresponding friend here +// CHECK: class1.cpp:36:8: warning: type 'F2' has incompatible definitions in different translation units +// CHECK: class1.cpp:39:3: note: friend declared here +// CHECK: class2.cpp:30:8: note: no corresponding friend here + // CHECK: 4 warnings generated. Index: lib/AST/DeclBase.cpp === --- lib/AST/DeclBase.cpp +++ lib/AST/DeclBase.cpp @@ -1343,6 +1343,8 @@ } bool DeclContext::containsDecl(Decl *D) const { + if (hasExternalLexicalStorage()) +LoadLexicalDeclsFromExternalStorage(); return (D->getLexicalDeclContext() == this && (D->NextInContextAndBits.getPointer() || D == LastDecl)); } Index: lib/AST/ASTImporter.cpp === --- lib/AST/ASTImporter.cpp +++ lib/AST/ASTImporter.cpp @@ -71,6 +71,25 @@ namespace clang { + template + SmallVector + getCanonicalForwardRedeclChain(Redeclarable* D) { +SmallVector Redecls; +for (auto *R : D->getFirstDecl()->redecls()) { + if (R != D->getFirstDecl()) +Redecls.push_back(R); +} +Redecls.push_back(D->getFirstDecl()); +std::reverse(Redecls.begin(), Redecls.end()); +return Redecls; + } + + SmallVector getCanonicalForwardRedeclChain(Decl* D) { +// Currently only FunctionDecl is supported +auto FD = cast(D); +return getCanonicalForwardRedeclChain(FD); + } + class ASTNodeImporter : public TypeVisitor, public DeclVisitor, public StmtVisitor { @@ -195,6 +214,12 @@ const InContainerTy &Container, TemplateArgumentListInfo &Result); +using TemplateArgsTy = SmallVector; +using OptionalTemplateArgsTy = Optional; +std::tuple +ImportFunctionTemplateWithTemplateArgsFromSpecialization( +FunctionDecl *FromFD); + bool ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD); bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, @@ -408,6 +433,8 @@ // Importing overrides. void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod); + +FunctionDecl *FindFunctionTemplateSpecialization(FunctionDecl *FromFD); }; template @@ -437,6 +464,25 @@ From.arguments(), Result); } +std::tuple +ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization( +FunctionDecl *FromFD) { + assert(FromFD->getTemplatedKind() == + FunctionDecl::TK_FunctionTemplateSpecialization); + auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); + auto *Template = cast_or_null( + Importer.Import(FTSInfo->getTemplate())); + + // Import template arguments. + auto TemplArgs = FTSInfo->TemplateArguments->asArray(); + TemplateArgsTy ToTemplArgs; + if (ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(), + ToTemplArgs)) // Error during import. +return std::make_tuple(Template, OptionalTemplateArgsTy()); + + return std::make_tuple(Template, ToTemplArgs); +} + } // namespace clang // @@ -2252,31 +2298,26 @@ } case FunctionDecl::TK_FunctionTemplateSpecialization: { -auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); -auto *Template = cast_or_null( -Importer.Import(FTSInfo->getTemplate())); -if (!Template) - return true; -TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind(); - -// Import template arguments. -auto TemplArgs = FTSInfo->TemplateArguments->asArray(); -Sma
[PATCH] D48549: Use Triple::isMIPS() instead of enumerating all Triples. NFC
arichardson updated this revision to Diff 152696. arichardson added a comment. Ran clang-format on the diff Repository: rC Clang https://reviews.llvm.org/D48549 Files: lib/Basic/Targets/Mips.cpp lib/Basic/Targets/Mips.h lib/Driver/ToolChains/Arch/Mips.cpp lib/Driver/ToolChains/Arch/Mips.h lib/Driver/ToolChains/CommonArgs.cpp lib/Driver/ToolChains/FreeBSD.cpp lib/Driver/ToolChains/Gnu.cpp lib/Driver/ToolChains/Linux.cpp lib/Driver/ToolChains/NetBSD.cpp lib/Driver/ToolChains/OpenBSD.cpp Index: lib/Driver/ToolChains/OpenBSD.cpp === --- lib/Driver/ToolChains/OpenBSD.cpp +++ lib/Driver/ToolChains/OpenBSD.cpp @@ -68,10 +68,10 @@ CmdArgs.push_back("-mabi"); CmdArgs.push_back(mips::getGnuCompatibleMipsABIName(ABIName).data()); -if (getToolChain().getArch() == llvm::Triple::mips64) - CmdArgs.push_back("-EB"); -else +if (getToolChain().getTriple().isLittleEndian()) CmdArgs.push_back("-EL"); +else + CmdArgs.push_back("-EB"); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; Index: lib/Driver/ToolChains/NetBSD.cpp === --- lib/Driver/ToolChains/NetBSD.cpp +++ lib/Driver/ToolChains/NetBSD.cpp @@ -64,11 +64,10 @@ CmdArgs.push_back("-mabi"); CmdArgs.push_back(mips::getGnuCompatibleMipsABIName(ABIName).data()); -if (getToolChain().getArch() == llvm::Triple::mips || -getToolChain().getArch() == llvm::Triple::mips64) - CmdArgs.push_back("-EB"); -else +if (getToolChain().getTriple().isLittleEndian()) CmdArgs.push_back("-EL"); +else + CmdArgs.push_back("-EB"); AddAssemblerKPIC(getToolChain(), Args, CmdArgs); break; Index: lib/Driver/ToolChains/Linux.cpp === --- lib/Driver/ToolChains/Linux.cpp +++ lib/Driver/ToolChains/Linux.cpp @@ -156,7 +156,7 @@ } static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) { - if (tools::isMipsArch(Triple.getArch())) { + if (Triple.isMIPS()) { if (Triple.isAndroid()) { StringRef CPUName; StringRef ABIName; @@ -242,7 +242,7 @@ ExtraOpts.push_back("-X"); const bool IsAndroid = Triple.isAndroid(); - const bool IsMips = tools::isMipsArch(Arch); + const bool IsMips = Triple.isMIPS(); const bool IsHexagon = Arch == llvm::Triple::hexagon; const bool IsRISCV = Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64; @@ -438,7 +438,7 @@ return AndroidSysRootPath; } - if (!GCCInstallation.isValid() || !tools::isMipsArch(getTriple().getArch())) + if (!GCCInstallation.isValid() || !getTriple().isMIPS()) return std::string(); // Standalone MIPS toolchains use different names for sysroot folder @@ -530,17 +530,16 @@ case llvm::Triple::mipsel: case llvm::Triple::mips64: case llvm::Triple::mips64el: { -bool LE = (Triple.getArch() == llvm::Triple::mipsel) || - (Triple.getArch() == llvm::Triple::mips64el); bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple); LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple); if (tools::mips::isUCLibc(Args)) Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0"; else if (!Triple.hasEnvironment() && Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies) - Loader = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1"; + Loader = + Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1"; else Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1"; @@ -894,10 +893,8 @@ SanitizerMask Linux::getSupportedSanitizers() const { const bool IsX86 = getTriple().getArch() == llvm::Triple::x86; const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64; - const bool IsMIPS = getTriple().getArch() == llvm::Triple::mips || - getTriple().getArch() == llvm::Triple::mipsel; - const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 || -getTriple().getArch() == llvm::Triple::mips64el; + const bool IsMIPS = getTriple().isMIPS32(); + const bool IsMIPS64 = getTriple().isMIPS64(); const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 || getTriple().getArch() == llvm::Triple::ppc64le; const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 || Index: lib/Driver/ToolChains/Gnu.cpp === --- lib/Driver/ToolChains/Gnu.cpp +++ lib/Driver/ToolChains/Gnu.cpp @@ -707,11 +707,10 @@ if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls)) CmdArgs.push_back("-call_nonpic"); -if (getToolChain().getArch() == llvm::Triple::mips || -getToolChain().getArch() == llvm::Triple::mips64) - CmdArgs.pu
[PATCH] D48455: Remove hip.amdgcn.bc hc.amdgcn.bc from HIP Toolchains
gregrodgers added a comment. Why not provide a specific list of --hip-device-lib= for VDI builds? I am not sure about defining functions inside headers instead of using a hip bc lib. Repository: rC Clang https://reviews.llvm.org/D48455 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47532: [ASTImporter] Import the whole redecl chain of functions
labath added subscribers: aprantl, labath. labath added a comment. This has broken the LLDB bot http://lab.llvm.org:8011/builders/lldb-x86_64-ubuntu-14.04-cmake/builds/25132. Could you take a look? Repository: rC Clang https://reviews.llvm.org/D47532 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r335483 - [OPENMP] Do not consider address constant vars as possibly
Author: abataev Date: Mon Jun 25 08:32:05 2018 New Revision: 335483 URL: http://llvm.org/viewvc/llvm-project?rev=335483&view=rev Log: [OPENMP] Do not consider address constant vars as possibly threadprivate. Do not delay emission of the address constant variables in OpenMP mode as they cannot be defined as threadprivate. Added: cfe/trunk/test/OpenMP/constexpr_codegen.cpp Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=335483&r1=335482&r2=335483&view=diff == --- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original) +++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Mon Jun 25 08:32:05 2018 @@ -1914,7 +1914,8 @@ bool CodeGenModule::MayBeEmittedEagerly( // If OpenMP is enabled and threadprivates must be generated like TLS, delay // codegen for global variables, because they may be marked as threadprivate. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && - getContext().getTargetInfo().isTLSSupported() && isa(Global)) + getContext().getTargetInfo().isTLSSupported() && isa(Global) && + !isTypeConstant(Global->getType(), false)) return false; return true; Added: cfe/trunk/test/OpenMP/constexpr_codegen.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/constexpr_codegen.cpp?rev=335483&view=auto == --- cfe/trunk/test/OpenMP/constexpr_codegen.cpp (added) +++ cfe/trunk/test/OpenMP/constexpr_codegen.cpp Mon Jun 25 08:32:05 2018 @@ -0,0 +1,29 @@ +// RUN: %clang_cc1 -verify -fopenmp -std=c++11 -triple x86_64-unknown-unknown -x c++ -emit-llvm %s -fexceptions -fcxx-exceptions -o - | FileCheck %s +// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -emit-pch -o %t %s +// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -debug-info-kind=limited -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s + +// RUN: %clang_cc1 -verify -fopenmp-simd -std=c++11 -triple x86_64-unknown-unknown -x c++ -emit-llvm %s -fexceptions -fcxx-exceptions -o - | FileCheck --check-prefix SIMD-ONLY1 %s +// RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -emit-pch -o %t %s +// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple x86_64-unknown-unknown -fexceptions -fcxx-exceptions -debug-info-kind=limited -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY1 %s +// SIMD-ONLY1-NOT: {{__kmpc|__tgt}} + +// expected-no-diagnostics +// +#ifndef HEADER +#define HEADER + +// CHECK: @{{.*}}Foo{{.*}}bar{{.*}} = constant i32 1, + +// Section A - Define a class with a static constexpr data member. +struct Foo { + static constexpr int bar = 1; +}; + +// Section B - ODR-use the data member. +void F(const int &); +void Test() { F(Foo::bar); } + +// Section C - Define the data member. +constexpr int Foo::bar; +#endif + ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48532: [analyzer] Add support for std::basic_string::data() in DanglingInternalBufferChecker
xazax.hun accepted this revision. xazax.hun added a comment. This revision is now accepted and ready to land. LG! Repository: rC Clang https://reviews.llvm.org/D48532 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48532: [analyzer] Add support for std::basic_string::data() in DanglingInternalBufferChecker
xazax.hun added inline comments. Comment at: test/Analysis/dangling-internal-buffer.cpp:10 const CharT *c_str(); + const CharT *data(); }; Note that these methods are const according to the standard. Even if it does not make any difference for this check we should follow the signatures. Also, from c++17 there is a non-const overload of data. Repository: rC Clang https://reviews.llvm.org/D48532 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D45719: [clang-Format] Fix indentation of member call after block
klimek added inline comments. Comment at: unittests/Format/FormatTest.cpp:4359 + "return 3;\n" + " }).as("");\n" + "}"); ank wrote: > klimek wrote: > > ank wrote: > > > klimek wrote: > > > > What would be interesting is tests that: > > > > a) have another value after the closing }; doesn't really make sense in > > > > this test, but usually these are in calls > > > > f([]() { ... }, foo, bar).call(...) > > > > > > > > b) make .as("") have paramters that go beyond the limit > > > > > > > > c) add another chained call behind .as(""). > > > Hello, sorry for the late follow up on this! > > > > > > Indeed an interesting thing to test, and so I did, the patterns you > > > describe seems to give strange indentation as far back as release_36 and > > > probably has always done so. The case I'm testing here worked in > > > release_40 but stopped working somewhere before release_50 > > > > > > maybe fixing those other cases can be done in another patch > > > > > > cheers, > > > Anders > > I meant: please add these tests :) > I need to clarify, those tests will not be correctly indented by this commit, > I could add those tests but then they would verify a faulty behaviour, this > is how they will be indented even with this patch applied: > > > ``` > // Dont break if only closing statements before member call > verifyFormat("test() {\n" > " ([]() -> {\n" > "int b = 32;\n" > "return 3;\n" > " }).foo();\n" > "}"); > verifyFormat("test() {\n" > " (\n" > " []() -> {\n" > "int b = 32;\n" > "return 3;\n" > " },\n" > " foo, bar)\n" > " .foo();\n" > "}"); > verifyFormat("test() {\n" > " ([]() -> {\n" > "int b = 32;\n" > "return 3;\n" > " })\n" > " .foo()\n" > " .bar();\n" > "}"); > verifyFormat("test() {\n" > " ([]() -> {\n" > "int b = 32;\n" > "return 3;\n" > " })\n" > " > .foo(\"aaa\"\n" > " \"bb\");\n" > "}"); > > verifyFormat("test() {\n" > " foo([]() -> {\n" > "int b = 32;\n" > "return 3;\n" > " }).foo();\n" > "}"); > verifyFormat("test() {\n" > " foo(\n" > " []() -> {\n" > "int b = 32;\n" > "return 3;\n" > " },\n" > " foo, bar)\n" > " .as();\n" > "}"); > verifyFormat("test() {\n" > " foo([]() -> {\n" > "int b = 32;\n" > "return 3;\n" > " })\n" > " .foo()\n" > " .bar();\n" > "}"); > verifyFormat("test() {\n" > " foo([]() -> {\n" > "int b = 32;\n" > "return 3;\n" > " })\n" > " > .as(\"\"\n" > " \"bb\");\n" > "}"); > ``` I'm not sure we agree that the behavior is "faulty" - I do believe it was an intentional change :) This is an indent of 4 from the start of the expression that call belongs to. For example, in example (2), having the .foo() at the end of line after a potentially complex parameter strongly de-emphasizes the parameter. In example (3), how would you want to layout a chain of calls? Repository: rC Clang https://reviews.llvm.org/D45719 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47632: [ASTImporter] Refactor Decl creation
martong updated this revision to Diff 152703. martong added a comment. - Rebase from master. Repository: rC Clang https://reviews.llvm.org/D47632 Files: include/clang/AST/ASTImporter.h include/clang/AST/DeclBase.h lib/AST/ASTImporter.cpp lib/AST/ExternalASTMerger.cpp Index: lib/AST/ExternalASTMerger.cpp === --- lib/AST/ExternalASTMerger.cpp +++ lib/AST/ExternalASTMerger.cpp @@ -154,7 +154,7 @@ ToContainer->setMustBuildLookupTable(); assert(Parent.CanComplete(ToContainer)); } -return ASTImporter::Imported(From, To); +return To; } ASTImporter &GetReverse() { return Reverse; } }; @@ -229,7 +229,7 @@ SourceTag->getASTContext().getExternalSource()->CompleteType(SourceTag); if (!SourceTag->getDefinition()) return false; -Forward.Imported(SourceTag, Tag); +Forward.MapImported(SourceTag, Tag); Forward.ImportDefinition(SourceTag); Tag->setCompleteDefinition(SourceTag->isCompleteDefinition()); return true; @@ -248,7 +248,7 @@ SourceInterface); if (!SourceInterface->getDefinition()) return false; -Forward.Imported(SourceInterface, Interface); +Forward.MapImported(SourceInterface, Interface); Forward.ImportDefinition(SourceInterface); return true; }); @@ -304,7 +304,7 @@ void ExternalASTMerger::RecordOriginImpl(const DeclContext *ToDC, DCOrigin Origin, ASTImporter &Importer) { Origins[ToDC] = Origin; - Importer.ASTImporter::Imported(cast(Origin.DC), const_cast(cast(ToDC))); + Importer.ASTImporter::MapImported(cast(Origin.DC), const_cast(cast(ToDC))); } ExternalASTMerger::ExternalASTMerger(const ImporterTarget &Target, Index: lib/AST/ASTImporter.cpp === --- lib/AST/ASTImporter.cpp +++ lib/AST/ASTImporter.cpp @@ -95,6 +95,58 @@ public StmtVisitor { ASTImporter &Importer; +// Wrapper for an overload set. +template struct CallOverloadedCreateFun { + template + auto operator()(Args &&... args) + -> decltype(ToDeclT::Create(std::forward(args)...)) { +return ToDeclT::Create(std::forward(args)...); + } +}; + +// Always use this function to create a Decl during import. There are +// certain tasks which must be done after the Decl was created, e.g. we +// must immediately register that as an imported Decl. +// Returns a pair consisting of a pointer to the new or the already imported +// Decl and a bool value set to true if the `FromD` had been imported +// before. +template +std::pair CreateDecl(FromDeclT *FromD, Args &&... args) { + // There may be several overloads of ToDeclT::Create. We must make sure + // to call the one which would be chosen by the arguments, thus we use a + // wrapper for the overload set. + CallOverloadedCreateFun OC; + return CreateDecl(OC, FromD, std::forward(args)...); +} +// Use this overload directly only if a special create function must be +// used, e.g. CXXRecordDecl::CreateLambda . +template +auto CreateDecl(CreateFunT CreateFun, FromDeclT *FromD, Args &&... args) +-> std::pair(args)...)), bool> { + using ToDeclT = typename std::remove_pointer(args)...))>::type; + ToDeclT *AlreadyImported = + cast_or_null(Importer.GetAlreadyImportedOrNull(FromD)); + if (AlreadyImported) { +return std::make_pair(AlreadyImported, /*AlreadyImported=*/true); + } + ToDeclT *ToD = CreateFun(std::forward(args)...); + InitializeImportedDecl(FromD, ToD); + return std::make_pair(ToD, /*AlreadyImported=*/false); +} + +void InitializeImportedDecl(Decl *FromD, Decl *ToD) { + Importer.MapImported(FromD, ToD); + ToD->IdentifierNamespace = FromD->IdentifierNamespace; + if (FromD->hasAttrs()) +for (const Attr *FromAttr : FromD->getAttrs()) + ToD->addAttr(Importer.Import(FromAttr)); + if (FromD->isUsed()) +ToD->setIsUsed(); + if (FromD->isImplicit()) +ToD->setImplicit(); +} + public: explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {} @@ -1572,18 +1624,23 @@ // Import the location of this declaration. SourceLocation Loc = Importer.Import(D->getLocation()); - EmptyDecl *ToD = EmptyDecl::Create(Importer.getToContext(), DC, Loc); + bool AlreadyImported; + EmptyDecl *ToD; + std::tie(ToD, AlreadyImported) = + CreateDecl(D, Importer.getToContext(), DC, Loc); + if (AlreadyImported) +return ToD; + ToD->setLexicalDeclContext(LexicalDC); - Importer.Imported(D, ToD); LexicalDC->addDeclInternal(ToD); return ToD; } Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { TranslationUnitDecl *ToD = Importer.getToContext().getTra
[PATCH] D48027: [analyzer] Improve `CallDescription` to handle c++ method.
MTC updated this revision to Diff 152702. MTC added a comment. Sorry for the long long delay, I was on the Dragon Boat Festival a few days ago. This update has two parts: - Use the `matchesName` to match the AST node with the specified name, `matchesName` use regex to match the specified name. - Use `std::vector` to record the list of qualified name, user can provide information as much as possible to improve matching accuracy. But can also provide only the function name. There are two remain issues: - There is possible match the wrong AST node, e.g. for the NamedDecl `foo()`, if the function body has the `a::b::x`, when we match `a::b::X()`, we will match `foo()` . Because I'm not familiar with ASTMatcher, my bad, I can't think of a perfect way to match only the specified nodes. - The `std::vector` to record the information provide by the users may be not the best data structure. - I'm not the regex expert, the regex used in this patch definitely has the chance to improve. And I am not good at English writing, if any comments are not very clear, please correct me. Thanks for the help! Repository: rC Clang https://reviews.llvm.org/D48027 Files: include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp lib/StaticAnalyzer/Checkers/ValistChecker.cpp lib/StaticAnalyzer/Core/CallEvent.cpp Index: lib/StaticAnalyzer/Core/CallEvent.cpp === --- lib/StaticAnalyzer/Core/CallEvent.cpp +++ lib/StaticAnalyzer/Core/CallEvent.cpp @@ -28,6 +28,7 @@ #include "clang/Analysis/AnalysisDeclContext.h" #include "clang/Analysis/CFG.h" #include "clang/Analysis/ProgramPoint.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/CrossTU/CrossTranslationUnit.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" @@ -65,6 +66,7 @@ using namespace clang; using namespace ento; +using namespace clang::ast_matchers; QualType CallEvent::getResultType() const { ASTContext &Ctx = getState()->getStateManager().getContext(); @@ -256,11 +258,28 @@ return false; if (!CD.IsLookupDone) { CD.IsLookupDone = true; -CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName); +CD.II = &getState()->getStateManager().getContext().Idents.get( +CD.getFunctionName()); } const IdentifierInfo *II = getCalleeIdentifier(); if (!II || II != CD.II) return false; + + if (CD.QualifiedName.size() > 1) { +const NamedDecl *ND = dyn_cast_or_null(getDecl()); +if (!ND) + return false; + +std::string Regex = "^::(.*)?"; +Regex += llvm::join(CD.QualifiedName, "(.*)?::(.*)?") + "(.*)?$"; + +auto Matches = match(namedDecl(matchesName(Regex)).bind("Regex"), *ND, + LCtx->getAnalysisDeclContext()->getASTContext()); + +if (Matches.empty()) + return false; + } + return (CD.RequiredArgs == CallDescription::NoArgRequirement || CD.RequiredArgs == getNumArgs()); } Index: lib/StaticAnalyzer/Checkers/ValistChecker.cpp === --- lib/StaticAnalyzer/Checkers/ValistChecker.cpp +++ lib/StaticAnalyzer/Checkers/ValistChecker.cpp @@ -103,24 +103,24 @@ const SmallVector ValistChecker::VAListAccepters = { -{{"vfprintf", 3}, 2}, -{{"vfscanf", 3}, 2}, -{{"vprintf", 2}, 1}, -{{"vscanf", 2}, 1}, -{{"vsnprintf", 4}, 3}, -{{"vsprintf", 3}, 2}, -{{"vsscanf", 3}, 2}, -{{"vfwprintf", 3}, 2}, -{{"vfwscanf", 3}, 2}, -{{"vwprintf", 2}, 1}, -{{"vwscanf", 2}, 1}, -{{"vswprintf", 4}, 3}, +{{{"vfprintf"}, 3}, 2}, +{{{"vfscanf"}, 3}, 2}, +{{{"vprintf"}, 2}, 1}, +{{{"vscanf"}, 2}, 1}, +{{{"vsnprintf"}, 4}, 3}, +{{{"vsprintf"}, 3}, 2}, +{{{"vsscanf"}, 3}, 2}, +{{{"vfwprintf"}, 3}, 2}, +{{{"vfwscanf"}, 3}, 2}, +{{{"vwprintf"}, 2}, 1}, +{{{"vwscanf"}, 2}, 1}, +{{{"vswprintf"}, 4}, 3}, // vswprintf is the wide version of vsnprintf, // vsprintf has no wide version -{{"vswscanf", 3}, 2}}; -const CallDescription ValistChecker::VaStart("__builtin_va_start", 2), -ValistChecker::VaCopy("__builtin_va_copy", 2), -ValistChecker::VaEnd("__builtin_va_end", 1); +{{{"vswscanf"}, 3}, 2}}; +const CallDescription ValistChecker::VaStart({"__builtin_va_start"}, 2), +ValistChecker::VaCopy({"__builtin_va_copy"}, 2), +ValistChecker::VaEnd({"__builtin_va_end"}, 1); } // end anonymous namespace void ValistChecker::checkPreCall(const CallEvent &Call, Index: lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
[PATCH] D47532: [ASTImporter] Import the whole redecl chain of functions
martong added a comment. @labath Sure, looking into it. Repository: rC Clang https://reviews.llvm.org/D47532 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
LLVM buildmaster will be restarted tonight
Hello everyone, LLVM buildmaster will be updated and restarted after 6PM Pacific time today. Thanks Galina ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r335491 - Revert "[ASTImporter] Import the whole redecl chain of functions"
Author: martong Date: Mon Jun 25 09:25:30 2018 New Revision: 335491 URL: http://llvm.org/viewvc/llvm-project?rev=335491&view=rev Log: Revert "[ASTImporter] Import the whole redecl chain of functions" This reverts commit r335480. Modified: cfe/trunk/include/clang/AST/ASTImporter.h cfe/trunk/lib/AST/ASTImporter.cpp cfe/trunk/lib/AST/DeclBase.cpp cfe/trunk/test/ASTMerge/class/test.cpp cfe/trunk/unittests/AST/ASTImporterTest.cpp Modified: cfe/trunk/include/clang/AST/ASTImporter.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTImporter.h?rev=335491&r1=335490&r2=335491&view=diff == --- cfe/trunk/include/clang/AST/ASTImporter.h (original) +++ cfe/trunk/include/clang/AST/ASTImporter.h Mon Jun 25 09:25:30 2018 @@ -43,15 +43,6 @@ class TagDecl; class TypeSourceInfo; class Attr; - // \brief Returns with a list of declarations started from the canonical decl - // then followed by subsequent decls in the translation unit. - // This gives a canonical list for each entry in the redecl chain. - // `Decl::redecls()` gives a list of decls which always start from the - // previous decl and the next item is actually the previous item in the order - // of source locations. Thus, `Decl::redecls()` gives different lists for - // the different entries in a given redecl chain. - llvm::SmallVector getCanonicalForwardRedeclChain(Decl* D); - /// Imports selected nodes from one AST context into another context, /// merging AST nodes where appropriate. class ASTImporter { Modified: cfe/trunk/lib/AST/ASTImporter.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=335491&r1=335490&r2=335491&view=diff == --- cfe/trunk/lib/AST/ASTImporter.cpp (original) +++ cfe/trunk/lib/AST/ASTImporter.cpp Mon Jun 25 09:25:30 2018 @@ -71,25 +71,6 @@ namespace clang { - template - SmallVector - getCanonicalForwardRedeclChain(Redeclarable* D) { -SmallVector Redecls; -for (auto *R : D->getFirstDecl()->redecls()) { - if (R != D->getFirstDecl()) -Redecls.push_back(R); -} -Redecls.push_back(D->getFirstDecl()); -std::reverse(Redecls.begin(), Redecls.end()); -return Redecls; - } - - SmallVector getCanonicalForwardRedeclChain(Decl* D) { -// Currently only FunctionDecl is supported -auto FD = cast(D); -return getCanonicalForwardRedeclChain(FD); - } - class ASTNodeImporter : public TypeVisitor, public DeclVisitor, public StmtVisitor { @@ -214,12 +195,6 @@ namespace clang { const InContainerTy &Container, TemplateArgumentListInfo &Result); -using TemplateArgsTy = SmallVector; -using OptionalTemplateArgsTy = Optional; -std::tuple -ImportFunctionTemplateWithTemplateArgsFromSpecialization( -FunctionDecl *FromFD); - bool ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD); bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, @@ -433,8 +408,6 @@ namespace clang { // Importing overrides. void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod); - -FunctionDecl *FindFunctionTemplateSpecialization(FunctionDecl *FromFD); }; template @@ -464,25 +437,6 @@ bool ASTNodeImporter::ImportTemplateArgu From.arguments(), Result); } -std::tuple -ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization( -FunctionDecl *FromFD) { - assert(FromFD->getTemplatedKind() == - FunctionDecl::TK_FunctionTemplateSpecialization); - auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); - auto *Template = cast_or_null( - Importer.Import(FTSInfo->getTemplate())); - - // Import template arguments. - auto TemplArgs = FTSInfo->TemplateArguments->asArray(); - TemplateArgsTy ToTemplArgs; - if (ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(), - ToTemplArgs)) // Error during import. -return std::make_tuple(Template, OptionalTemplateArgsTy()); - - return std::make_tuple(Template, ToTemplArgs); -} - } // namespace clang // @@ -2298,17 +2252,23 @@ bool ASTNodeImporter::ImportTemplateInfo } case FunctionDecl::TK_FunctionTemplateSpecialization: { -FunctionTemplateDecl* Template; -OptionalTemplateArgsTy ToTemplArgs; -std::tie(Template, ToTemplArgs) = -ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD); -if (!Template || !ToTemplArgs) +auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); +auto *Template = cast_or_null( +Importer.Import(FTSInfo->getTemplate())); +if (!Template) +
[PATCH] D47532: [ASTImporter] Import the whole redecl chain of functions
martong added a comment. This is not trivial to fix. Reverting until we can reproduce and fix it. Reverted with commit: r335491 Repository: rC Clang https://reviews.llvm.org/D47532 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r335492 - [clang-format] Add a default format style that can be used by users of `getStyle`
Author: ioeric Date: Mon Jun 25 09:29:19 2018 New Revision: 335492 URL: http://llvm.org/viewvc/llvm-project?rev=335492&view=rev Log: [clang-format] Add a default format style that can be used by users of `getStyle` Summary: Tools that reformat code often call `getStyle` to decide the format style to use on a certain source file. In practice, "file" style is widely used. As a result, many tools hardcode "file" when calling `getStyle`, which makes it hard to control the default style in tools across a codebase when needed. This change introduces a `DefaultFormatStyle` constant (default to "file" in upstream), which can be modified downstream if wanted, so that all users/tools built from the same source tree can have a consistent default format style. This also adds an DefaultFallbackStyle that is recommended to be used by tools and can be modified downstream. Reviewers: sammccall, djasper Reviewed By: sammccall Subscribers: cfe-commits Differential Revision: https://reviews.llvm.org/D48492 Modified: cfe/trunk/include/clang/Format/Format.h cfe/trunk/lib/Format/Format.cpp cfe/trunk/tools/clang-format/ClangFormat.cpp Modified: cfe/trunk/include/clang/Format/Format.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=335492&r1=335491&r2=335492&view=diff == --- cfe/trunk/include/clang/Format/Format.h (original) +++ cfe/trunk/include/clang/Format/Format.h Mon Jun 25 09:29:19 2018 @@ -1963,6 +1963,15 @@ LangOptions getFormattingLangOpts(const /// of ``getStyle()``. extern const char *StyleOptionHelpDescription; +/// The suggested format style to use by default. This allows tools using +/// `getStyle` to have a consistent default style. +/// Different builds can modify the value to the preferred styles. +extern const char *DefaultFormatStyle; + +/// The suggested predefined style to use as the fallback style in `getStyle`. +/// Different builds can modify the value to the preferred styles. +extern const char *DefaultFallbackStyle; + /// Construct a FormatStyle based on ``StyleName``. /// /// ``StyleName`` can take several forms: Modified: cfe/trunk/lib/Format/Format.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=335492&r1=335491&r2=335492&view=diff == --- cfe/trunk/lib/Format/Format.cpp (original) +++ cfe/trunk/lib/Format/Format.cpp Mon Jun 25 09:29:19 2018 @@ -2144,6 +2144,10 @@ FormatStyle::LanguageKind guessLanguage( return GuessedLanguage; } +const char *DefaultFormatStyle = "file"; + +const char *DefaultFallbackStyle = "LLVM"; + llvm::Expected getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName, StringRef Code, vfs::FileSystem *FS) { Modified: cfe/trunk/tools/clang-format/ClangFormat.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-format/ClangFormat.cpp?rev=335492&r1=335491&r2=335492&view=diff == --- cfe/trunk/tools/clang-format/ClangFormat.cpp (original) +++ cfe/trunk/tools/clang-format/ClangFormat.cpp Mon Jun 25 09:29:19 2018 @@ -60,17 +60,18 @@ LineRanges("lines", cl::desc(" -Style("style", - cl::desc(clang::format::StyleOptionHelpDescription), - cl::init("file"), cl::cat(ClangFormatCategory)); +Style("style", cl::desc(clang::format::StyleOptionHelpDescription), + cl::init(clang::format::DefaultFormatStyle), + cl::cat(ClangFormatCategory)); static cl::opt -FallbackStyle("fallback-style", - cl::desc("The name of the predefined style used as a\n" - "fallback in case clang-format is invoked with\n" - "-style=file, but can not find the .clang-format\n" - "file to use.\n" - "Use -fallback-style=none to skip formatting."), - cl::init("LLVM"), cl::cat(ClangFormatCategory)); +FallbackStyle("fallback-style", + cl::desc("The name of the predefined style used as a\n" + "fallback in case clang-format is invoked with\n" + "-style=file, but can not find the .clang-format\n" + "file to use.\n" + "Use -fallback-style=none to skip formatting."), + cl::init(clang::format::DefaultFallbackStyle), + cl::cat(ClangFormatCategory)); static cl::opt AssumeFileName("assume-filename", ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48492: [clang-format] Add a default format style that can be used by users of `getStyle`
This revision was automatically updated to reflect the committed changes. Closed by commit rL335492: [clang-format] Add a default format style that can be used by users of… (authored by ioeric, committed by ). Herald added a subscriber: llvm-commits. Repository: rL LLVM https://reviews.llvm.org/D48492 Files: cfe/trunk/include/clang/Format/Format.h cfe/trunk/lib/Format/Format.cpp cfe/trunk/tools/clang-format/ClangFormat.cpp Index: cfe/trunk/tools/clang-format/ClangFormat.cpp === --- cfe/trunk/tools/clang-format/ClangFormat.cpp +++ cfe/trunk/tools/clang-format/ClangFormat.cpp @@ -60,17 +60,18 @@ "Can only be used with one input file."), cl::cat(ClangFormatCategory)); static cl::opt -Style("style", - cl::desc(clang::format::StyleOptionHelpDescription), - cl::init("file"), cl::cat(ClangFormatCategory)); +Style("style", cl::desc(clang::format::StyleOptionHelpDescription), + cl::init(clang::format::DefaultFormatStyle), + cl::cat(ClangFormatCategory)); static cl::opt -FallbackStyle("fallback-style", - cl::desc("The name of the predefined style used as a\n" - "fallback in case clang-format is invoked with\n" - "-style=file, but can not find the .clang-format\n" - "file to use.\n" - "Use -fallback-style=none to skip formatting."), - cl::init("LLVM"), cl::cat(ClangFormatCategory)); +FallbackStyle("fallback-style", + cl::desc("The name of the predefined style used as a\n" + "fallback in case clang-format is invoked with\n" + "-style=file, but can not find the .clang-format\n" + "file to use.\n" + "Use -fallback-style=none to skip formatting."), + cl::init(clang::format::DefaultFallbackStyle), + cl::cat(ClangFormatCategory)); static cl::opt AssumeFileName("assume-filename", Index: cfe/trunk/include/clang/Format/Format.h === --- cfe/trunk/include/clang/Format/Format.h +++ cfe/trunk/include/clang/Format/Format.h @@ -1963,6 +1963,15 @@ /// of ``getStyle()``. extern const char *StyleOptionHelpDescription; +/// The suggested format style to use by default. This allows tools using +/// `getStyle` to have a consistent default style. +/// Different builds can modify the value to the preferred styles. +extern const char *DefaultFormatStyle; + +/// The suggested predefined style to use as the fallback style in `getStyle`. +/// Different builds can modify the value to the preferred styles. +extern const char *DefaultFallbackStyle; + /// Construct a FormatStyle based on ``StyleName``. /// /// ``StyleName`` can take several forms: Index: cfe/trunk/lib/Format/Format.cpp === --- cfe/trunk/lib/Format/Format.cpp +++ cfe/trunk/lib/Format/Format.cpp @@ -2144,6 +2144,10 @@ return GuessedLanguage; } +const char *DefaultFormatStyle = "file"; + +const char *DefaultFallbackStyle = "LLVM"; + llvm::Expected getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName, StringRef Code, vfs::FileSystem *FS) { Index: cfe/trunk/tools/clang-format/ClangFormat.cpp === --- cfe/trunk/tools/clang-format/ClangFormat.cpp +++ cfe/trunk/tools/clang-format/ClangFormat.cpp @@ -60,17 +60,18 @@ "Can only be used with one input file."), cl::cat(ClangFormatCategory)); static cl::opt -Style("style", - cl::desc(clang::format::StyleOptionHelpDescription), - cl::init("file"), cl::cat(ClangFormatCategory)); +Style("style", cl::desc(clang::format::StyleOptionHelpDescription), + cl::init(clang::format::DefaultFormatStyle), + cl::cat(ClangFormatCategory)); static cl::opt -FallbackStyle("fallback-style", - cl::desc("The name of the predefined style used as a\n" - "fallback in case clang-format is invoked with\n" - "-style=file, but can not find the .clang-format\n" - "file to use.\n" - "Use -fallback-style=none to skip formatting."), - cl::init("LLVM"), cl::cat(ClangFormatCategory)); +FallbackStyle("fallback-style", + cl::desc("The name of the predefined style used as a\n" + "fallback in case clang-format is invoked with\n" + "-style=file, but can not find the .clang-format\n" + "file to use.\n" + "Use -fallback-style=non
[PATCH] D48549: Use Triple::isMIPS() instead of enumerating all Triples. NFC
This revision was automatically updated to reflect the committed changes. Closed by commit rC335495: Use Triple::isMIPS() instead of enumerating all Triples. NFC (authored by arichardson, committed by ). Changed prior to commit: https://reviews.llvm.org/D48549?vs=152696&id=152713#toc Repository: rC Clang https://reviews.llvm.org/D48549 Files: lib/Basic/Targets/Mips.cpp lib/Basic/Targets/Mips.h lib/Driver/ToolChains/Arch/Mips.cpp lib/Driver/ToolChains/Arch/Mips.h lib/Driver/ToolChains/CommonArgs.cpp lib/Driver/ToolChains/FreeBSD.cpp lib/Driver/ToolChains/Gnu.cpp lib/Driver/ToolChains/Linux.cpp lib/Driver/ToolChains/NetBSD.cpp lib/Driver/ToolChains/OpenBSD.cpp Index: lib/Basic/Targets/Mips.h === --- lib/Basic/Targets/Mips.h +++ lib/Basic/Targets/Mips.h @@ -69,10 +69,7 @@ UseIndirectJumpHazard(false), HasFP64(false) { TheCXXABI.set(TargetCXXABI::GenericMIPS); -setABI((getTriple().getArch() == llvm::Triple::mips || -getTriple().getArch() == llvm::Triple::mipsel) - ? "o32" - : "n64"); +setABI(getTriple().isMIPS32() ? "o32" : "n64"); CPU = ABI == "o32" ? "mips32r2" : "mips64r2"; Index: lib/Basic/Targets/Mips.cpp === --- lib/Basic/Targets/Mips.cpp +++ lib/Basic/Targets/Mips.cpp @@ -200,9 +200,7 @@ bool MipsTargetInfo::validateTarget(DiagnosticsEngine &Diags) const { // microMIPS64R6 backend was removed. - if ((getTriple().getArch() == llvm::Triple::mips64 || - getTriple().getArch() == llvm::Triple::mips64el) && - IsMicromips && (ABI == "n32" || ABI == "n64")) { + if (getTriple().isMIPS64() && IsMicromips && (ABI == "n32" || ABI == "n64")) { Diags.Report(diag::err_target_unsupported_cpu_for_micromips) << CPU; return false; } @@ -222,20 +220,16 @@ // FIXME: It's valid to use O32 on a mips64/mips64el triple but the backend //can't handle this yet. It's better to fail here than on the //backend assertion. - if ((getTriple().getArch() == llvm::Triple::mips64 || - getTriple().getArch() == llvm::Triple::mips64el) && - ABI == "o32") { + if (getTriple().isMIPS64() && ABI == "o32") { Diags.Report(diag::err_target_unsupported_abi_for_triple) << ABI << getTriple().str(); return false; } // FIXME: It's valid to use N32/N64 on a mips/mipsel triple but the backend //can't handle this yet. It's better to fail here than on the //backend assertion. - if ((getTriple().getArch() == llvm::Triple::mips || - getTriple().getArch() == llvm::Triple::mipsel) && - (ABI == "n32" || ABI == "n64")) { + if (getTriple().isMIPS32() && (ABI == "n32" || ABI == "n64")) { Diags.Report(diag::err_target_unsupported_abi_for_triple) << ABI << getTriple().str(); return false; Index: lib/Driver/ToolChains/FreeBSD.cpp === --- lib/Driver/ToolChains/FreeBSD.cpp +++ lib/Driver/ToolChains/FreeBSD.cpp @@ -57,11 +57,10 @@ CmdArgs.push_back("-mabi"); CmdArgs.push_back(mips::getGnuCompatibleMipsABIName(ABIName).data()); -if (getToolChain().getArch() == llvm::Triple::mips || -getToolChain().getArch() == llvm::Triple::mips64) - CmdArgs.push_back("-EB"); -else +if (getToolChain().getTriple().isLittleEndian()) CmdArgs.push_back("-EL"); +else + CmdArgs.push_back("-EB"); if (Arg *A = Args.getLastArg(options::OPT_G)) { StringRef v = A->getValue(); @@ -179,10 +178,7 @@ } if (Arg *A = Args.getLastArg(options::OPT_G)) { -if (ToolChain.getArch() == llvm::Triple::mips || - ToolChain.getArch() == llvm::Triple::mipsel || - ToolChain.getArch() == llvm::Triple::mips64 || - ToolChain.getArch() == llvm::Triple::mips64el) { +if (ToolChain.getTriple().isMIPS()) { StringRef v = A->getValue(); CmdArgs.push_back(Args.MakeArgString("-G" + v)); A->claim(); @@ -322,9 +318,7 @@ // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall // back to '/usr/lib' if it doesn't exist. - if ((Triple.getArch() == llvm::Triple::x86 || - Triple.getArch() == llvm::Triple::mips || - Triple.getArch() == llvm::Triple::mipsel || + if ((Triple.getArch() == llvm::Triple::x86 || Triple.isMIPS32() || Triple.getArch() == llvm::Triple::ppc) && D.getVFS().exists(getDriver().SysRoot + "/usr/lib32/crt1.o")) getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32"); @@ -389,8 +383,7 @@ SanitizerMask FreeBSD::getSupportedSanitizers() const { const bool IsX86 = getTriple().getArch() == llvm::Triple::x86; const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64; - const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 || -getTriple().getArch() == llvm
r335495 - Use Triple::isMIPS() instead of enumerating all Triples. NFC
Author: arichardson Date: Mon Jun 25 09:49:52 2018 New Revision: 335495 URL: http://llvm.org/viewvc/llvm-project?rev=335495&view=rev Log: Use Triple::isMIPS() instead of enumerating all Triples. NFC Reviewed By: atanasyan Differential Revision: https://reviews.llvm.org/D48549 Modified: cfe/trunk/lib/Basic/Targets/Mips.cpp cfe/trunk/lib/Basic/Targets/Mips.h cfe/trunk/lib/Driver/ToolChains/Arch/Mips.cpp cfe/trunk/lib/Driver/ToolChains/Arch/Mips.h cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp cfe/trunk/lib/Driver/ToolChains/FreeBSD.cpp cfe/trunk/lib/Driver/ToolChains/Gnu.cpp cfe/trunk/lib/Driver/ToolChains/Linux.cpp cfe/trunk/lib/Driver/ToolChains/NetBSD.cpp cfe/trunk/lib/Driver/ToolChains/OpenBSD.cpp Modified: cfe/trunk/lib/Basic/Targets/Mips.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/Mips.cpp?rev=335495&r1=335494&r2=335495&view=diff == --- cfe/trunk/lib/Basic/Targets/Mips.cpp (original) +++ cfe/trunk/lib/Basic/Targets/Mips.cpp Mon Jun 25 09:49:52 2018 @@ -200,9 +200,7 @@ ArrayRef MipsTargetInfo:: bool MipsTargetInfo::validateTarget(DiagnosticsEngine &Diags) const { // microMIPS64R6 backend was removed. - if ((getTriple().getArch() == llvm::Triple::mips64 || - getTriple().getArch() == llvm::Triple::mips64el) && - IsMicromips && (ABI == "n32" || ABI == "n64")) { + if (getTriple().isMIPS64() && IsMicromips && (ABI == "n32" || ABI == "n64")) { Diags.Report(diag::err_target_unsupported_cpu_for_micromips) << CPU; return false; } @@ -222,9 +220,7 @@ bool MipsTargetInfo::validateTarget(Diag // FIXME: It's valid to use O32 on a mips64/mips64el triple but the backend //can't handle this yet. It's better to fail here than on the //backend assertion. - if ((getTriple().getArch() == llvm::Triple::mips64 || - getTriple().getArch() == llvm::Triple::mips64el) && - ABI == "o32") { + if (getTriple().isMIPS64() && ABI == "o32") { Diags.Report(diag::err_target_unsupported_abi_for_triple) << ABI << getTriple().str(); return false; @@ -233,9 +229,7 @@ bool MipsTargetInfo::validateTarget(Diag // FIXME: It's valid to use N32/N64 on a mips/mipsel triple but the backend //can't handle this yet. It's better to fail here than on the //backend assertion. - if ((getTriple().getArch() == llvm::Triple::mips || - getTriple().getArch() == llvm::Triple::mipsel) && - (ABI == "n32" || ABI == "n64")) { + if (getTriple().isMIPS32() && (ABI == "n32" || ABI == "n64")) { Diags.Report(diag::err_target_unsupported_abi_for_triple) << ABI << getTriple().str(); return false; Modified: cfe/trunk/lib/Basic/Targets/Mips.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/Mips.h?rev=335495&r1=335494&r2=335495&view=diff == --- cfe/trunk/lib/Basic/Targets/Mips.h (original) +++ cfe/trunk/lib/Basic/Targets/Mips.h Mon Jun 25 09:49:52 2018 @@ -69,10 +69,7 @@ public: UseIndirectJumpHazard(false), HasFP64(false) { TheCXXABI.set(TargetCXXABI::GenericMIPS); -setABI((getTriple().getArch() == llvm::Triple::mips || -getTriple().getArch() == llvm::Triple::mipsel) - ? "o32" - : "n64"); +setABI(getTriple().isMIPS32() ? "o32" : "n64"); CPU = ABI == "o32" ? "mips32r2" : "mips64r2"; Modified: cfe/trunk/lib/Driver/ToolChains/Arch/Mips.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Arch/Mips.cpp?rev=335495&r1=335494&r2=335495&view=diff == --- cfe/trunk/lib/Driver/ToolChains/Arch/Mips.cpp (original) +++ cfe/trunk/lib/Driver/ToolChains/Arch/Mips.cpp Mon Jun 25 09:49:52 2018 @@ -20,11 +20,6 @@ using namespace clang::driver::tools; using namespace clang; using namespace llvm::opt; -bool tools::isMipsArch(llvm::Triple::ArchType Arch) { - return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel || - Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el; -} - // Get CPU and ABI names. They are not independent // so we have to calculate them together. void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple, @@ -106,11 +101,7 @@ void mips::getMipsCPUAndABI(const ArgLis if (ABIName.empty()) { // Deduce ABI name from the target triple. -if (Triple.getArch() == llvm::Triple::mips || -Triple.getArch() == llvm::Triple::mipsel) - ABIName = "o32"; -else - ABIName = "n64"; +ABIName = Triple.isMIPS32() ? "o32" : "n64"; } if (CPUName.empty()) { Modified: cfe/trunk/lib/Driver/ToolChains/Arch/Mips.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Arch/Mips.h?rev=335495&r1=335494&r2=335495&view=diff =
[PATCH] D45454: Make __gcov_flush visible outside a shared library
chh added a comment. In https://reviews.llvm.org/D45454#1142197, @marco-c wrote: > In https://reviews.llvm.org/D45454#1070884, @belleyb wrote: > > > @chh I had a chance to try out your proposed changes. It's not causing us > > any trouble. In fact, `__gcov_flush()` is not even used at all (at least in > > LLVM 5.0.1).. I can recompile llvm, compiler_rt and clang and re-run all > > the tests with `__gcov_flush` commented out! No problem. > > > > I would suggest adding a bit more documentation to `__gcov_flush()`, thus > > describing what those "special cases" are... > > > __gcov_flush is only used if you actually call it (it's needed for example if > you want to profile only part of your program). > > In GCC, __gcov_flush is not hidden, so perhaps we should do the same to keep > the same behavior? I've also submitted https://reviews.llvm.org/D48538, which > is making __gcov_flush flush counters for all shared libraries (like GCC > does, with the same caveat: > https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83879). I have no problem keeping these functions compatible with GCC. My earlier proposal and David's comment in the mailing list seemed to be lost and not showing here. So, let me summarize the case here. This change should make `__gcov_flush` not hidden as before in GCC, but earlier change made it hidden as well as other `llvm_gov_*` functions. Could we have both `__gov_flush` and `llvm_gov_flush` functions, one unhidden and one hidden? https://reviews.llvm.org/D45454 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48522: [analyzer] Highlight c_str() call in DanglingInternalBuffer checker
rnkovacs updated this revision to Diff 152719. rnkovacs added a comment. Fixed the constness of `c_str()` in the test file. https://reviews.llvm.org/D48522 Files: lib/StaticAnalyzer/Checkers/AllocationState.h lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp lib/StaticAnalyzer/Checkers/MallocChecker.cpp test/Analysis/dangling-internal-buffer.cpp Index: test/Analysis/dangling-internal-buffer.cpp === --- test/Analysis/dangling-internal-buffer.cpp +++ test/Analysis/dangling-internal-buffer.cpp @@ -6,7 +6,7 @@ class basic_string { public: ~basic_string(); - const CharT *c_str(); + const CharT *c_str() const; }; typedef basic_string string; @@ -25,17 +25,29 @@ const char *c; { std::string s; -c = s.c_str(); +c = s.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} + } // expected-note {{Internal buffer is released because the object was destroyed}} + consume(c); // expected-warning {{Use of memory after it is freed}} + // expected-note@-1 {{Use of memory after it is freed}} +} + +void deref_after_scope_char2() { + const char *c; + { +std::string s; +c = s.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::string s; + const char *c2 = s.c_str(); consume(c); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } void deref_after_scope_wchar_t() { const wchar_t *w; { std::wstring ws; -w = ws.c_str(); +w = ws.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} consume(w); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} @@ -45,7 +57,7 @@ const char16_t *c16; { std::u16string s16; -c16 = s16.c_str(); +c16 = s16.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} consume(c16); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} @@ -55,7 +67,7 @@ const char32_t *c32; { std::u32string s32; -c32 = s32.c_str(); +c32 = s32.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} consume(c32); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} Index: lib/StaticAnalyzer/Checkers/MallocChecker.cpp === --- lib/StaticAnalyzer/Checkers/MallocChecker.cpp +++ lib/StaticAnalyzer/Checkers/MallocChecker.cpp @@ -1994,6 +1994,11 @@ R->markInteresting(Sym); R->addRange(Range); R->addVisitor(llvm::make_unique(Sym)); + +const RefState *RS = C.getState()->get(Sym); +if (RS->getAllocationFamily() == AF_InternalBuffer) + R->addVisitor(allocation_state::getDanglingBufferBRVisitor(Sym)); + C.emitReport(std::move(R)); } } Index: lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp === --- lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp +++ lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp @@ -7,30 +7,67 @@ // //===--===// // -// This file defines a check that marks a raw pointer to a C++ standard library -// container's inner buffer released when the object is destroyed. This -// information can be used by MallocChecker to detect use-after-free problems. +// This file defines a check that marks a raw pointer to a C++ container's +// inner buffer released when the object is destroyed. This information can +// be used by MallocChecker to detect use-after-free problems. // //===--===// +#include "AllocationState.h" #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" -#include "AllocationState.h" using namespace clang; using namespace ento; +// FIXME: c_str() may be called on a string object many times, so it should +// have a list of symbols associated with it. +REGISTER_MAP_WITH_PROGRAMSTATE(RawPtrMap, const MemRegion *, SymbolRef) + namespace { -class DanglingInternalBufferChecker : public Checker { +cl
r335503 - [MachineOutliner] Make last of -moutline/-mno-outline win
Author: paquette Date: Mon Jun 25 10:27:51 2018 New Revision: 335503 URL: http://llvm.org/viewvc/llvm-project?rev=335503&view=rev Log: [MachineOutliner] Make last of -moutline/-mno-outline win The expected behaviour of command-line flags to clang is to have the last of -m(whatever) and -mno-(whatever) win. The outliner didn't do that. This fixes that and updates the test. Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp cfe/trunk/test/Driver/aarch64-outliner.c Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=335503&r1=335502&r2=335503&view=diff == --- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original) +++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Mon Jun 25 10:27:51 2018 @@ -1477,10 +1477,12 @@ void Clang::AddAArch64TargetArgs(const A CmdArgs.push_back("-aarch64-enable-global-merge=true"); } - if (!Args.hasArg(options::OPT_mno_outline) && - Args.getLastArg(options::OPT_moutline)) { -CmdArgs.push_back("-mllvm"); -CmdArgs.push_back("-enable-machine-outliner"); + if (Arg *A = Args.getLastArg(options::OPT_moutline, + options::OPT_mno_outline)) { +if (A->getOption().matches(options::OPT_moutline)) { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back("-enable-machine-outliner"); +} } } Modified: cfe/trunk/test/Driver/aarch64-outliner.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/aarch64-outliner.c?rev=335503&r1=335502&r2=335503&view=diff == --- cfe/trunk/test/Driver/aarch64-outliner.c (original) +++ cfe/trunk/test/Driver/aarch64-outliner.c Mon Jun 25 10:27:51 2018 @@ -1,9 +1,5 @@ // REQUIRES: aarch64-registered-target - // RUN: %clang -target aarch64 -moutline -S %s -### 2>&1 | FileCheck %s -check-prefix=ON // ON: "-mllvm" "-enable-machine-outliner" - -// RUN: %clang -target aarch64 -moutline -mno-outline -S %s -### 2>&1 | FileCheck %s -check-prefix=OFF1 -// RUN: %clang -target aarch64 -mno-outline -moutline -S %s -### 2>&1 | FileCheck %s -check-prefix=OFF2 -// OFF1-NOT: "-mllvm" "-enable-machine-outliner" -// OFF2-NOT: "-mllvm" "-enable-machine-outliner" +// RUN: %clang -target aarch64 -moutline -mno-outline -S %s -### 2>&1 | FileCheck %s -check-prefix=OFF +// OFF-NOT: "-mllvm" "-enable-machine-outliner" ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r335504 - [MachineOutliner] Outline from linkonceodrs by default in LTO when -moutline is passed
Author: paquette Date: Mon Jun 25 10:36:05 2018 New Revision: 335504 URL: http://llvm.org/viewvc/llvm-project?rev=335504&view=rev Log: [MachineOutliner] Outline from linkonceodrs by default in LTO when -moutline is passed Pass -enable-linkonceodr-outlining by default when LTO is enabled. The outliner shouldn't compete with any sort of linker deduplication on linkonceodr functions when LTO is enabled. Therefore, this behaviour should be the default. Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp cfe/trunk/test/Driver/aarch64-outliner.c Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=335504&r1=335503&r2=335504&view=diff == --- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original) +++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Mon Jun 25 10:36:05 2018 @@ -1482,6 +1482,14 @@ void Clang::AddAArch64TargetArgs(const A if (A->getOption().matches(options::OPT_moutline)) { CmdArgs.push_back("-mllvm"); CmdArgs.push_back("-enable-machine-outliner"); + + // The outliner shouldn't compete with linkers that dedupe linkonceodr + // functions in LTO. Enable that behaviour by default when compiling with + // LTO. + if (getToolChain().getDriver().isUsingLTO()) { +CmdArgs.push_back("-mllvm"); +CmdArgs.push_back("-enable-linkonceodr-outlining"); + } } } } Modified: cfe/trunk/test/Driver/aarch64-outliner.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/aarch64-outliner.c?rev=335504&r1=335503&r2=335504&view=diff == --- cfe/trunk/test/Driver/aarch64-outliner.c (original) +++ cfe/trunk/test/Driver/aarch64-outliner.c Mon Jun 25 10:36:05 2018 @@ -3,3 +3,7 @@ // ON: "-mllvm" "-enable-machine-outliner" // RUN: %clang -target aarch64 -moutline -mno-outline -S %s -### 2>&1 | FileCheck %s -check-prefix=OFF // OFF-NOT: "-mllvm" "-enable-machine-outliner" +// RUN: %clang -target aarch64 -moutline -flto=thin -S %s -### 2>&1 | FileCheck %s -check-prefix=FLTO +// FLTO: "-mllvm" "-enable-linkonceodr-outlining" +// RUN: %clang -target aarch64 -moutline -flto=full -S %s -### 2>&1 | FileCheck %s -check-prefix=TLTO +// TLTO: "-mllvm" "-enable-linkonceodr-outlining" ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libcxx] r335507 - [CMake] Fix install-cxx target.
Author: morehouse Date: Mon Jun 25 11:01:51 2018 New Revision: 335507 URL: http://llvm.org/viewvc/llvm-project?rev=335507&view=rev Log: [CMake] Fix install-cxx target. Was broken by r334477. Modified: libcxx/trunk/include/CMakeLists.txt Modified: libcxx/trunk/include/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/CMakeLists.txt?rev=335507&r1=335506&r2=335507&view=diff == --- libcxx/trunk/include/CMakeLists.txt (original) +++ libcxx/trunk/include/CMakeLists.txt Mon Jun 25 11:01:51 2018 @@ -255,7 +255,7 @@ if (LIBCXX_INSTALL_HEADERS) if (NOT CMAKE_CONFIGURATION_TYPES) add_custom_target(install-cxx-headers - DEPENDS cxx-headers ${generated_config_deps} + DEPENDS cxx_headers ${generated_config_deps} COMMAND "${CMAKE_COMMAND}" -DCMAKE_INSTALL_COMPONENT=cxx-headers -P "${CMAKE_BINARY_DIR}/cmake_install.cmake") ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47814: Teach libc++ to use native NetBSD's max_align_t
krytarowski added a comment. ping^2 Repository: rL LLVM https://reviews.llvm.org/D47814 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D45679: [clang-tidy] Add ExprMutationAnalyzer, that analyzes whether an expression is mutated within a statement.
shuaiwang added a comment. Could someone help commit this now that the build issue with header include is fixed? Thanks a lot! (meanwhile I'm requesting commit access) In https://reviews.llvm.org/D45679#1132327, @alexfh wrote: > In https://reviews.llvm.org/D45679#1132086, @JonasToth wrote: > > > It might be the case, that the test is run with -no-stdinc (or similar), > > so the standard library is not available. > > > Tests should be self-contained and must not depend on any system headers. > Standard library implementations may differ, which would make tests brittle. > Instead, tests should mock implementations of the APIs they work with (if > necessary, multiple times - once for every distinct standard library version > the check supports). Yep. It doesn't include any headers anymore :) Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D45679 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48443: [WebAssembly] Add no-prototype attribute to prototype-less C functions
This revision was automatically updated to reflect the committed changes. Closed by commit rL335510: [WebAssembly] Add no-prototype attribute to prototype-less C functions (authored by sbc, committed by ). Herald added a subscriber: llvm-commits. Repository: rL LLVM https://reviews.llvm.org/D48443 Files: cfe/trunk/lib/CodeGen/TargetInfo.cpp cfe/trunk/test/CodeGen/no-prototype.c Index: cfe/trunk/test/CodeGen/no-prototype.c === --- cfe/trunk/test/CodeGen/no-prototype.c +++ cfe/trunk/test/CodeGen/no-prototype.c @@ -0,0 +1,20 @@ +// REQUIRES: webassembly-registered-target +// RUN: %clang_cc1 -triple wasm32 -emit-llvm %s -o - | FileCheck %s + +int foo(); + +int bar(int a) { + return foo(); +} + +int baz() { + return foo(); +} + +// CHECK: define i32 @bar(i32 %a) [[BAR_ATTR:#[0-9]+]] { +// CHECK: declare i32 @foo(...) [[FOO_ATTR:#[0-9]+]] +// CHECK: define i32 @baz() [[BAZ_ATTR:#[0-9]+]] { + +// CHECK: attributes [[FOO_ATTR]] = { {{.*}}"no-prototype"{{.*}} } +// CHECK-NOT: attributes [[BAR_ATTR]] = { {{.*}}"no-prototype"{{.*}} } +// CHECK-NOT: attributes [[BAZ_ATTR]] = { {{.*}}"no-prototype"{{.*}} } Index: cfe/trunk/lib/CodeGen/TargetInfo.cpp === --- cfe/trunk/lib/CodeGen/TargetInfo.cpp +++ cfe/trunk/lib/CodeGen/TargetInfo.cpp @@ -747,6 +747,15 @@ public: explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {} + + void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, + CodeGen::CodeGenModule &CGM) const override { +if (auto *FD = dyn_cast_or_null(D)) { + llvm::Function *Fn = cast(GV); + if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) +Fn->addFnAttr("no-prototype"); +} + } }; /// Classify argument of given type \p Ty. Index: cfe/trunk/test/CodeGen/no-prototype.c === --- cfe/trunk/test/CodeGen/no-prototype.c +++ cfe/trunk/test/CodeGen/no-prototype.c @@ -0,0 +1,20 @@ +// REQUIRES: webassembly-registered-target +// RUN: %clang_cc1 -triple wasm32 -emit-llvm %s -o - | FileCheck %s + +int foo(); + +int bar(int a) { + return foo(); +} + +int baz() { + return foo(); +} + +// CHECK: define i32 @bar(i32 %a) [[BAR_ATTR:#[0-9]+]] { +// CHECK: declare i32 @foo(...) [[FOO_ATTR:#[0-9]+]] +// CHECK: define i32 @baz() [[BAZ_ATTR:#[0-9]+]] { + +// CHECK: attributes [[FOO_ATTR]] = { {{.*}}"no-prototype"{{.*}} } +// CHECK-NOT: attributes [[BAR_ATTR]] = { {{.*}}"no-prototype"{{.*}} } +// CHECK-NOT: attributes [[BAZ_ATTR]] = { {{.*}}"no-prototype"{{.*}} } Index: cfe/trunk/lib/CodeGen/TargetInfo.cpp === --- cfe/trunk/lib/CodeGen/TargetInfo.cpp +++ cfe/trunk/lib/CodeGen/TargetInfo.cpp @@ -747,6 +747,15 @@ public: explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {} + + void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, + CodeGen::CodeGenModule &CGM) const override { +if (auto *FD = dyn_cast_or_null(D)) { + llvm::Function *Fn = cast(GV); + if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) +Fn->addFnAttr("no-prototype"); +} + } }; /// Classify argument of given type \p Ty. ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r335510 - [WebAssembly] Add no-prototype attribute to prototype-less C functions
Author: sbc Date: Mon Jun 25 11:47:32 2018 New Revision: 335510 URL: http://llvm.org/viewvc/llvm-project?rev=335510&view=rev Log: [WebAssembly] Add no-prototype attribute to prototype-less C functions The WebAssembly backend in particular benefits from being able to distinguish between varargs functions (...) and prototype-less C functions. Differential Revision: https://reviews.llvm.org/D48443 Added: cfe/trunk/test/CodeGen/no-prototype.c (with props) Modified: cfe/trunk/lib/CodeGen/TargetInfo.cpp Modified: cfe/trunk/lib/CodeGen/TargetInfo.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/TargetInfo.cpp?rev=335510&r1=335509&r2=335510&view=diff == --- cfe/trunk/lib/CodeGen/TargetInfo.cpp (original) +++ cfe/trunk/lib/CodeGen/TargetInfo.cpp Mon Jun 25 11:47:32 2018 @@ -747,6 +747,15 @@ class WebAssemblyTargetCodeGenInfo final public: explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {} + + void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, + CodeGen::CodeGenModule &CGM) const override { +if (auto *FD = dyn_cast_or_null(D)) { + llvm::Function *Fn = cast(GV); + if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) +Fn->addFnAttr("no-prototype"); +} + } }; /// Classify argument of given type \p Ty. Added: cfe/trunk/test/CodeGen/no-prototype.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/no-prototype.c?rev=335510&view=auto == --- cfe/trunk/test/CodeGen/no-prototype.c (added) +++ cfe/trunk/test/CodeGen/no-prototype.c Mon Jun 25 11:47:32 2018 @@ -0,0 +1,20 @@ +// REQUIRES: webassembly-registered-target +// RUN: %clang_cc1 -triple wasm32 -emit-llvm %s -o - | FileCheck %s + +int foo(); + +int bar(int a) { + return foo(); +} + +int baz() { + return foo(); +} + +// CHECK: define i32 @bar(i32 %a) [[BAR_ATTR:#[0-9]+]] { +// CHECK: declare i32 @foo(...) [[FOO_ATTR:#[0-9]+]] +// CHECK: define i32 @baz() [[BAZ_ATTR:#[0-9]+]] { + +// CHECK: attributes [[FOO_ATTR]] = { {{.*}}"no-prototype"{{.*}} } +// CHECK-NOT: attributes [[BAR_ATTR]] = { {{.*}}"no-prototype"{{.*}} } +// CHECK-NOT: attributes [[BAZ_ATTR]] = { {{.*}}"no-prototype"{{.*}} } Propchange: cfe/trunk/test/CodeGen/no-prototype.c -- svn:eol-style = LF ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48532: [analyzer] Add support for std::basic_string::data() in DanglingInternalBufferChecker
rnkovacs updated this revision to Diff 152737. rnkovacs marked an inline comment as done. https://reviews.llvm.org/D48532 Files: lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp test/Analysis/dangling-internal-buffer.cpp Index: test/Analysis/dangling-internal-buffer.cpp === --- test/Analysis/dangling-internal-buffer.cpp +++ test/Analysis/dangling-internal-buffer.cpp @@ -7,6 +7,8 @@ public: ~basic_string(); const CharT *c_str() const; + const CharT *data() const; + CharT *data(); }; typedef basic_string string; @@ -21,63 +23,105 @@ void consume(const char16_t *) {} void consume(const char32_t *) {} -void deref_after_scope_char() { +void deref_after_scope_char_cstr() { const char *c; { std::string s; c = s.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::string s; + const char *c2 = s.c_str(); consume(c); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_char2() { +void deref_after_scope_char_data() { const char *c; { std::string s; -c = s.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} +c = s.data(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} std::string s; - const char *c2 = s.c_str(); + const char *c2 = s.data(); + consume(c); // expected-warning {{Use of memory after it is freed}} + // expected-note@-1 {{Use of memory after it is freed}} +} + +void deref_after_scope_char_data_non_const() { + char *c; + { +std::string s; +c = s.data(); // expected-note {{Pointer to dangling buffer was obtained here}} + } // expected-note {{Internal buffer is released because the object was destroyed}} + std::string s; + char *c2 = s.data(); consume(c); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_wchar_t() { + +void deref_after_scope_wchar_t_cstr() { const wchar_t *w; { std::wstring ws; w = ws.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::wstring ws; + const wchar_t *w2 = ws.c_str(); + consume(w); // expected-warning {{Use of memory after it is freed}} + // expected-note@-1 {{Use of memory after it is freed}} +} + +void deref_after_scope_wchar_t_data() { + const wchar_t *w; + { +std::wstring ws; +w = ws.data(); // expected-note {{Pointer to dangling buffer was obtained here}} + } // expected-note {{Internal buffer is released because the object was destroyed}} + std::wstring ws; + const wchar_t *w2 = ws.data(); consume(w); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_char16_t() { +void deref_after_scope_char16_t_cstr() { const char16_t *c16; { std::u16string s16; c16 = s16.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::u16string s16; + const char16_t *c16_2 = s16.c_str(); consume(c16); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_char32_t() { +void deref_after_scope_char32_t_data() { const char32_t *c32; { std::u32string s32; -c32 = s32.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}} +c32 = s32.data(); // expected-note {{Pointer to dangling buffer was obtained here}} } // expected-note {{Internal buffer is released because the object was destroyed}} + std::u32string s32; + const char32_t *c32_2 = s32.data(); consume(c32); // expected-warning {{Use of memory after it is freed}} // expected-note@-1 {{Use of memory after it is freed}} } -void deref_after_scope_ok() { +void deref_after_scope_cstr_ok() { const char *c; std::string s; { c = s.c_str(); } consume(c); // no-warning } + +void deref_after_scope_data_ok() { + const char *c; + std::string s; + { +c = s.data(); + } + consume(c); // no-warning +} Index: lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp === --- lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp +++ lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp @@ -24,15 +24,16 @@ using namespace clang; using namespace ento; -// FIXME: c_str() may be called on a string object many times, so it should -// have a list of symbols associate
[PATCH] D48532: [analyzer] Add support for std::basic_string::data() in DanglingInternalBufferChecker
rnkovacs added inline comments. Comment at: test/Analysis/dangling-internal-buffer.cpp:10 const CharT *c_str(); + const CharT *data(); }; xazax.hun wrote: > Note that these methods are const according to the standard. Even if it does > not make any difference for this check we should follow the signatures. Also, > from c++17 there is a non-const overload of data. Oh, right, thanks. Fixed here and in D48522. https://reviews.llvm.org/D48532 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r335084 - Append new attributes to the end of an AttributeList.
On 23 June 2018 at 22:34, Michael Kruse via cfe-commits < cfe-commits@lists.llvm.org> wrote: > Hi, > > multiple comments in the code indicate that the attribute order was > surprising and probably has lead to bugs, and will lead to bugs in the > future. The order had to be explicitly reversed to avoid those. This > alone for me this seems a good reason to have the attributes in the > order in which they appear in the source. > > It would be nice it you could send a reproducer. At a glance, your > case does not seem related since the format strings are function > arguments, not attributes. > > Michael > > > 2018-06-23 17:17 GMT-05:00 David Jones : > > This commit seems to have some substantial downsides... for example, it > now > > flags calls like this as warnings: > > http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext- > tools/src/msgl-check.c?id=05ecefa943f339019b7127aa92cbb09f6fd49ed3#n478 > > > > Previously, the reverse order meant that the plural format string was > > examined, but now it is only the singular string. Since the singular > string > > doesn't include a substitution, the unused format variable warning fires > > after this revision. > > > > I don't see a strong argument for why one order is more correct than the > > other; however, given that this is in conflict with real code found in > the > > wild, I think this needs to be addressed. > > > > Since the semantics of the ordering of multiple format args seems > somewhat > > ill-defined, it seems to me like reverting may be the best near-term > choice. > > I can imagine other ways to fix the diagnostic, but the only behaviour > that > > I would believe to be expected by existing code is the old one, so a > change > > like this one probably needs to be more carefully vetted before being > > (re-)committed. > > Could you give more details about your concerns? (I'm not sure what the problem is, but as a data point, Sema::checkCall iterates over the FormatAttrs in order, so it's possible that changing the order may have triggered a new warning. That may be due to a pre-existing order-dependence bug, or it may be that we're losing an attribute here.) > Please let me know your plan. (If I don't hear back in a day or so, I'll > go > > ahead and revert for you as the safe default course of action.) > > On a weekend? Yes; our policy is generally to revert to green if a patch causes regressions that aren't going to be fixed in a few hours. This is generally good for the committer, because it lets you figure out what's wrong and deal with it on your own schedule rather than being pressured to fix it urgently because you're blocking the work of others. ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47567: Implement CFI for indirect calls via a member function pointer.
vlad.tsyrklevich accepted this revision. vlad.tsyrklevich added a comment. This revision is now accepted and ready to land. I think it would be clearer to replace uses of 'member function pointer' with 'pointer to member function'; however, a google search shows that the usage of both terms is basically the same so not this might be just be my own bias coming through. Comment at: clang/lib/CodeGen/CodeGenModule.cpp:1413 + FD->getType(), Context.getRecordType(Base).getTypePtr())); + F->addTypeMetadata(0, Id); +} It'd be nice to have a test that reaches this. Comment at: clang/lib/CodeGen/CodeGenModule.h:1256 + std::vector + getMostBaseClasses(const CXXRecordDecl *RD); Could be helpful to have a comment here to ensure there is no confusion interpreting this as 'the most-base classes' and not 'most of the base classes'. Comment at: clang/lib/Driver/SanitizerArgs.cpp:233 + options::OPT_fno_sanitize_cfi_cross_dso, false); + if (CfiCrossDso) +Supported &= ~CFIMFCall; This will cause supplying both options to fail with `clang: error: unsupported option '-fsanitize=cfi-mfcall' for target ...`. Having it error out the same way as type generalization below where it states that cfi-cross-dso is unsupported with cfi-mfcall seems like a more helpful error. Comment at: clang/test/CodeGenCXX/type-metadata.cpp:281 // ITANIUM: [[FA_ID]] = distinct !{} // MS: [[A8]] = !{i64 8, !"?AUA@@"} Any reason not to include AF64/CF64/FAF16 here? Comment at: compiler-rt/lib/ubsan/ubsan_handlers.cc:645 + const char *CheckKindStr = Data->CheckKind == CFITCK_NVMFCall + ? "non-virtual member function call" + : "indirect function call"; s/member/pointer to member/ ? Comment at: compiler-rt/lib/ubsan/ubsan_handlers_cxx.cc:126 + case CFITCK_VMFCall: +CheckKindStr = "virtual member function call"; +break; s/member/pointer to member/ ? https://reviews.llvm.org/D47567 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D35110: [Analyzer] Constraint Manager Negates Difference
baloghadamsoftware updated this revision to Diff 152752. baloghadamsoftware added a comment. Comment fixed, assertions inserted, new tests added. https://reviews.llvm.org/D35110 Files: include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h lib/StaticAnalyzer/Core/RangeConstraintManager.cpp test/Analysis/constraint_manager_negate_difference.c test/Analysis/ptr-arith.c Index: test/Analysis/ptr-arith.c === --- test/Analysis/ptr-arith.c +++ test/Analysis/ptr-arith.c @@ -265,49 +265,26 @@ clang_analyzer_eval((rhs - lhs) > 0); // expected-warning{{TRUE}} } -//--- -// False positives -//--- - void zero_implies_reversed_equal(int *lhs, int *rhs) { clang_analyzer_eval((rhs - lhs) == 0); // expected-warning{{UNKNOWN}} if ((rhs - lhs) == 0) { -#ifdef ANALYZER_CM_Z3 clang_analyzer_eval(rhs != lhs); // expected-warning{{FALSE}} clang_analyzer_eval(rhs == lhs); // expected-warning{{TRUE}} -#else -clang_analyzer_eval(rhs != lhs); // expected-warning{{UNKNOWN}} -clang_analyzer_eval(rhs == lhs); // expected-warning{{UNKNOWN}} -#endif return; } clang_analyzer_eval((rhs - lhs) == 0); // expected-warning{{FALSE}} -#ifdef ANALYZER_CM_Z3 clang_analyzer_eval(rhs == lhs); // expected-warning{{FALSE}} clang_analyzer_eval(rhs != lhs); // expected-warning{{TRUE}} -#else - clang_analyzer_eval(rhs == lhs); // expected-warning{{UNKNOWN}} - clang_analyzer_eval(rhs != lhs); // expected-warning{{UNKNOWN}} -#endif } void canonical_equal(int *lhs, int *rhs) { clang_analyzer_eval(lhs == rhs); // expected-warning{{UNKNOWN}} if (lhs == rhs) { -#ifdef ANALYZER_CM_Z3 clang_analyzer_eval(rhs == lhs); // expected-warning{{TRUE}} -#else -clang_analyzer_eval(rhs == lhs); // expected-warning{{UNKNOWN}} -#endif return; } clang_analyzer_eval(lhs == rhs); // expected-warning{{FALSE}} - -#ifdef ANALYZER_CM_Z3 clang_analyzer_eval(rhs == lhs); // expected-warning{{FALSE}} -#else - clang_analyzer_eval(rhs == lhs); // expected-warning{{UNKNOWN}} -#endif } void compare_element_region_and_base(int *p) { Index: test/Analysis/constraint_manager_negate_difference.c === --- /dev/null +++ test/Analysis/constraint_manager_negate_difference.c @@ -0,0 +1,98 @@ +// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin -analyzer-config aggressive-relational-comparison-simplification=true -verify %s + +void clang_analyzer_eval(int); + +void exit(int); + +#define UINT_MAX (~0U) +#define INT_MAX (UINT_MAX & (UINT_MAX >> 1)) +#define INT_MIN (UINT_MAX & ~(UINT_MAX >> 1)) + +extern void __assert_fail (__const char *__assertion, __const char *__file, +unsigned int __line, __const char *__function) + __attribute__ ((__noreturn__)); +#define assert(expr) \ + ((expr) ? (void)(0) : __assert_fail (#expr, __FILE__, __LINE__, __func__)) + +void assert_in_range(int x) { + assert(x <= ((int)INT_MAX / 4)); + assert(x >= -(((int)INT_MAX) / 4)); +} + +void assert_in_wide_range(int x) { + assert(x <= ((int)INT_MAX / 2)); + assert(x >= -(((int)INT_MAX) / 2)); +} + +void assert_in_range_2(int m, int n) { + assert_in_range(m); + assert_in_range(n); +} + +void equal(int m, int n) { + assert_in_range_2(m, n); + if (m != n) +return; + assert_in_wide_range(m - n); + clang_analyzer_eval(n == m); // expected-warning{{TRUE}} +} + +void non_equal(int m, int n) { + assert_in_range_2(m, n); + if (m == n) +return; + assert_in_wide_range(m - n); + clang_analyzer_eval(n != m); // expected-warning{{TRUE}} +} + +void less_or_equal(int m, int n) { + assert_in_range_2(m, n); + if (m < n) +return; + assert_in_wide_range(m - n); + clang_analyzer_eval(n <= m); // expected-warning{{TRUE}} +} + +void less(int m, int n) { + assert_in_range_2(m, n); + if (m <= n) +return; + assert_in_wide_range(m - n); + clang_analyzer_eval(n < m); // expected-warning{{TRUE}} +} + +void greater_or_equal(int m, int n) { + assert_in_range_2(m, n); + if (m > n) +return; + assert_in_wide_range(m - n); + clang_analyzer_eval(n >= m); // expected-warning{{TRUE}} +} + +void greater(int m, int n) { + assert_in_range_2(m, n); + if (m >= n) +return; + assert_in_wide_range(m - n); + clang_analyzer_eval(n > m); // expected-warning{{TRUE}} +} + +void negate_positive_range(int m, int n) { + if (m - n <= 0) +return; + clang_analyzer_eval(n - m < 0); // expected-warning{{TRUE}} + clang_analyzer_eval(n - m > INT_MIN); // expected-warning{{TRUE}} + clang_analyzer_eval(n - m == INT_MIN); // expected-warning{{FALSE}} +} + +void negate_int_min(int m, int n) { + if (m - n != INT_MIN) +return; + clang_analyzer_eval(n - m == INT_MIN); // expected-warning{{TRUE}} +} + +void negate_mixed(int m, int n) { + if (m -n > INT_MIN && m - n <= 0) +return; + clang
[PATCH] D48100: Append new attributes to the end of an AttributeList.
echristo added subscribers: dlj, echristo. echristo added a comment. I've added a couple of inline comments here - between this and the comments in the post-commit review from dlj it seems like we might want to revert this for now and figure out the best way forward. Thanks! -eric Comment at: test/Sema/attr-micromips.c:9 -__attribute__((micromips,mips16)) void foo5(); // expected-error {{'micromips' and 'mips16' attributes are not compatible}} \ +__attribute__((micromips,mips16)) void foo5(); // expected-error {{'mips16' and 'micromips' attributes are not compatible}} \ // expected-note {{conflicting attribute is here}} This seems to reverse? What's going on here? There are other occurrences too. Comment at: test/Sema/attr-target-mv.c:98 int __attribute__((target("sse4.2"))) diff_cc(void); -// expected-error@+1 {{multiversioned function declaration has a different calling convention}} +// expected-error@+1 {{attribute 'target' multiversioning cannot be combined with other attributes}} __vectorcall int __attribute__((target("arch=sandybridge"))) diff_cc(void); This appears to have broken a particular error message? Repository: rC Clang https://reviews.llvm.org/D48100 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r335084 - Append new attributes to the end of an AttributeList.
On Mon, Jun 25, 2018 at 12:21 PM Richard Smith via cfe-commits < cfe-commits@lists.llvm.org> wrote: > On 23 June 2018 at 22:34, Michael Kruse via cfe-commits < > cfe-commits@lists.llvm.org> wrote: > >> Hi, >> >> multiple comments in the code indicate that the attribute order was >> surprising and probably has lead to bugs, and will lead to bugs in the >> future. The order had to be explicitly reversed to avoid those. This >> alone for me this seems a good reason to have the attributes in the >> order in which they appear in the source. >> > It would be nice it you could send a reproducer. At a glance, your >> case does not seem related since the format strings are function >> arguments, not attributes. >> >> Michael >> >> >> 2018-06-23 17:17 GMT-05:00 David Jones : >> > This commit seems to have some substantial downsides... for example, it >> now >> > flags calls like this as warnings: >> > >> http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-tools/src/msgl-check.c?id=05ecefa943f339019b7127aa92cbb09f6fd49ed3#n478 >> > >> > Previously, the reverse order meant that the plural format string was >> > examined, but now it is only the singular string. Since the singular >> string >> > doesn't include a substitution, the unused format variable warning fires >> > after this revision. >> > >> > I don't see a strong argument for why one order is more correct than the >> > other; however, given that this is in conflict with real code found in >> the >> > wild, I think this needs to be addressed. >> > >> > Since the semantics of the ordering of multiple format args seems >> somewhat >> > ill-defined, it seems to me like reverting may be the best near-term >> choice. >> > I can imagine other ways to fix the diagnostic, but the only behaviour >> that >> > I would believe to be expected by existing code is the old one, so a >> change >> > like this one probably needs to be more carefully vetted before being >> > (re-)committed. >> >> Could you give more details about your concerns? > > > (I'm not sure what the problem is, but as a data point, Sema::checkCall > iterates over the FormatAttrs in order, so it's possible that changing the > order may have triggered a new warning. That may be due to a pre-existing > order-dependence bug, or it may be that we're losing an attribute here.) > > FWIW I just replied to the original review thread as well - there appear to be some warnings that are now missing that previously worked and some that are now in reverse order from the source. I think more work might need to happen before this patch should go back in. -eric > > Please let me know your plan. (If I don't hear back in a day or so, I'll >> go >> > ahead and revert for you as the safe default course of action.) >> >> On a weekend? > > > Yes; our policy is generally to revert to green if a patch causes > regressions that aren't going to be fixed in a few hours. This is generally > good for the committer, because it lets you figure out what's wrong and > deal with it on your own schedule rather than being pressured to fix it > urgently because you're blocking the work of others. > ___ > cfe-commits mailing list > cfe-commits@lists.llvm.org > http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48559: [clangd] refactoring for XPC transport layer [NFCI]
jkorous created this revision. jkorous added a project: clang-tools-extra. Herald added subscribers: cfe-commits, MaskRay, ioeric, ilya-biryukov, mgorny. Hi all, We finally finished a self-contained first version of our implementation of alternative transport layer for macOS based on XPC. To enable this I did couple of changes to current clangd design. Generally I aimed for small amount of disruption and tried to keep it simple. The notable changes are: - enabled registration of request handlers to different dispatchers by templatizing registerCallbackHandlers() - factored out parts of JsonDispatcher that could be reused (created DispatcherCommon.h/cpp) - created abstraction over JsonOutput (class LSPOutput) - removed of ClangdLSPServer::run() method so server can be run with different dispatcher - published IsDone and ShutdownRequestReceived through methods in ClangdLSPServer class interface to support new dispatcher We are also putting up the transport layer implementation itself for a review soon so it will be more obvious where are we going to and what motivated some of these changes. Big thanks in advance to all reviewers! Jan Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D48559 Files: CMakeLists.txt ClangdLSPServer.cpp ClangdLSPServer.h DispatcherCommon.cpp DispatcherCommon.h JSONRPCDispatcher.cpp JSONRPCDispatcher.h LSPOutput.h ProtocolHandlers.cpp ProtocolHandlers.h tool/ClangdMain.cpp Index: tool/ClangdMain.cpp === --- tool/ClangdMain.cpp +++ tool/ClangdMain.cpp @@ -19,7 +19,6 @@ #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" #include -#include #include #include #include @@ -207,12 +206,6 @@ if (Tracer) TracingSession.emplace(*Tracer); - JSONOutput Out(llvm::outs(), llvm::errs(), - InputMirrorStream ? InputMirrorStream.getPointer() : nullptr, - PrettyPrint); - - clangd::LoggingSession LoggingSession(Out); - // If --compile-commands-dir arg was invoked, check value and override default // path. llvm::Optional CompileCommandsDirPath; @@ -252,11 +245,27 @@ CCOpts.Limit = LimitResults; CCOpts.BundleOverloads = CompletionStyle != Detailed; - // Initialize and run ClangdLSPServer. - ClangdLSPServer LSPServer(Out, CCOpts, CompileCommandsDirPath, Opts); - constexpr int NoShutdownRequestErrorCode = 1; + ClangdLSPServer LSPServer(CCOpts, CompileCommandsDirPath, Opts); + llvm::set_thread_name("clangd.main"); // Change stdin to binary to not lose \r\n on windows. llvm::sys::ChangeStdinToBinary(); - return LSPServer.run(stdin, InputStyle) ? 0 : NoShutdownRequestErrorCode; + { +JSONRPCDispatcher Dispatcher([](const json::Expr &Params) { + replyError(ErrorCode::MethodNotFound, "method not found"); +}); +registerCallbackHandlers(Dispatcher, /*Callbacks=*/LSPServer); + + +JSONOutput Out(llvm::outs(), llvm::errs(), + InputMirrorStream ? InputMirrorStream.getPointer() : nullptr, + PrettyPrint); + +clangd::LoggingSession LoggingSession(Out); + +runJSONRPCServerLoop(stdin, Out, InputStyle, Dispatcher, LSPServer.getIsDone()); + } + + constexpr int NoShutdownRequestErrorCode = 1; + return LSPServer.getShutdownRequestReceived() ? 0 : NoShutdownRequestErrorCode; } Index: ProtocolHandlers.h === --- ProtocolHandlers.h +++ ProtocolHandlers.h @@ -56,8 +56,63 @@ virtual void onChangeConfiguration(DidChangeConfigurationParams &Params) = 0; }; -void registerCallbackHandlers(JSONRPCDispatcher &Dispatcher, - ProtocolCallbacks &Callbacks); +// Helper for attaching ProtocolCallbacks methods to a JSONRPCDispatcher. +// Invoke like: Registerer("foo", &ProtocolCallbacks::onFoo) +// onFoo should be: void onFoo(Ctx &C, FooParams &Params) +// FooParams should have a fromJSON function. +template +struct HandlerRegisterer { + template + void operator()(StringRef Method, void (ProtocolCallbacks::*Handler)(Param)) { +// Capture pointers by value, as the lambda will outlive this object. +auto *Callbacks = this->Callbacks; +Dispatcher.registerHandler(Method, [=](const json::Expr &RawParams) { + typename std::remove_reference::type P; + if (fromJSON(RawParams, P)) { +(Callbacks->*Handler)(P); + } else { +log("Failed to decode " + Method + " request."); + } +}); + } + + DispatcherType &Dispatcher; + ProtocolCallbacks *Callbacks; +}; + +template +void registerCallbackHandlers(DispatcherType &Dispatcher, + ProtocolCallbacks &Callbacks) { + HandlerRegisterer Register{Dispatcher, &Callbacks}; + + Register("initialize", &ProtocolCallbacks::onInitialize); + Register("shutdown", &ProtocolCallbacks::onShutdown); + Register("exit", &ProtocolCallbacks::onExit); + Register("t
[PATCH] D47567: Implement CFI for indirect calls via a member function pointer.
pcc added inline comments. Comment at: clang/lib/CodeGen/CodeGenModule.cpp:1413 + FD->getType(), Context.getRecordType(Base).getTypePtr())); + F->addTypeMetadata(0, Id); +} vlad.tsyrklevich wrote: > It'd be nice to have a test that reaches this. I'll add one. Comment at: clang/lib/CodeGen/CodeGenModule.h:1256 + std::vector + getMostBaseClasses(const CXXRecordDecl *RD); vlad.tsyrklevich wrote: > Could be helpful to have a comment here to ensure there is no confusion > interpreting this as 'the most-base classes' and not 'most of the base > classes'. Will do. Comment at: clang/lib/Driver/SanitizerArgs.cpp:233 + options::OPT_fno_sanitize_cfi_cross_dso, false); + if (CfiCrossDso) +Supported &= ~CFIMFCall; vlad.tsyrklevich wrote: > This will cause supplying both options to fail with `clang: error: > unsupported option '-fsanitize=cfi-mfcall' for target ...`. Having it error > out the same way as type generalization below where it states that > cfi-cross-dso is unsupported with cfi-mfcall seems like a more helpful error. The issue with that is that it would cause the flag combination `-fsanitize=cfi -fsanitize-cfi-cross-dso` to fail with an unsupported error. So I think it would need to work in a similar way as with the supported sanitizers. I guess I could add something after line 293 below instead. Comment at: clang/test/CodeGenCXX/type-metadata.cpp:281 // ITANIUM: [[FA_ID]] = distinct !{} // MS: [[A8]] = !{i64 8, !"?AUA@@"} vlad.tsyrklevich wrote: > Any reason not to include AF64/CF64/FAF16 here? No, I just forgot to add them. I'll do that. Comment at: compiler-rt/lib/ubsan/ubsan_handlers.cc:645 + const char *CheckKindStr = Data->CheckKind == CFITCK_NVMFCall + ? "non-virtual member function call" + : "indirect function call"; vlad.tsyrklevich wrote: > s/member/pointer to member/ ? Makes sense. Comment at: compiler-rt/lib/ubsan/ubsan_handlers_cxx.cc:126 + case CFITCK_VMFCall: +CheckKindStr = "virtual member function call"; +break; vlad.tsyrklevich wrote: > s/member/pointer to member/ ? Ditto https://reviews.llvm.org/D47567 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48560: [clangd] JSON <-> XPC conversions
jkorous created this revision. jkorous added a project: clang-tools-extra. Herald added subscribers: cfe-commits, MaskRay, ioeric, ilya-biryukov, mgorny. This is a self-contained pair of utility functions for the XPC transport layer. It's not dependent on but following the refactoring patch: https://reviews.llvm.org/D48559 Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D48560 Files: clangd/xpc/CMakeLists.txt clangd/xpc/XPCJSONConversionTests.cpp xpc/XPCJSONConversions.cpp xpc/XPCJSONConversions.h Index: clangd/xpc/XPCJSONConversionTests.cpp === --- /dev/null +++ clangd/xpc/XPCJSONConversionTests.cpp @@ -0,0 +1,452 @@ +//===-- XPCJSONConversion.cpp *- C++ -*---===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// + +#include "xpc/XPCJSONConversions.h" +#include "gtest/gtest.h" + +#include + +namespace clang { +namespace clangd { +namespace { + +TEST(JsonXpcConversionTest, Null) { + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(nullptr)), + xpc_null_create() +) + ); + EXPECT_TRUE( +json::Expr(nullptr) == xpcToJson(xpc_null_create()) + ); +} + +TEST(JsonXpcConversionTest, Bool) { + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(true)), + xpc_bool_create(true) +) + ); + EXPECT_TRUE( +json::Expr(false) == xpcToJson(xpc_bool_create(false)) + ); +} + +TEST(JsonXpcConversionTest, Number) { + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(3.14)), + xpc_double_create(3.14) +) + ); + EXPECT_TRUE( +json::Expr(3.14) == xpcToJson(xpc_double_create(3.14)) + ); + + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(42)), + xpc_double_create(42) +) + ); + EXPECT_TRUE( +json::Expr(42) == xpcToJson(xpc_double_create(42)) + ); + EXPECT_TRUE( +json::Expr(42) == xpcToJson(xpc_int64_create(42)) + ); + + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(-100)), + xpc_double_create(-100) +) + ); + EXPECT_TRUE( +json::Expr(-100) == xpcToJson(xpc_double_create(-100)) + ); + + unsigned long long bigPositiveValue = std::numeric_limits::max(); + ++bigPositiveValue; + unsigned long long bigNegativeValue = std::numeric_limits::min(); + --bigNegativeValue; + + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(bigPositiveValue)), + xpc_double_create(bigPositiveValue) +) + ); + EXPECT_TRUE( +json::Expr(bigPositiveValue) == xpcToJson(xpc_double_create(bigPositiveValue)) + ); + + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(bigNegativeValue)), + xpc_double_create(bigNegativeValue) +) + ); + EXPECT_TRUE( +json::Expr(bigNegativeValue) == xpcToJson(xpc_double_create(bigNegativeValue)) + ); +} + +TEST(JsonXpcConversionTest, String) { + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr("foo")), + xpc_string_create("foo") +) + ); + EXPECT_TRUE( +json::Expr("foo") == xpcToJson(xpc_string_create("foo")) + ); + + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr("")), + xpc_string_create("") +) + ); + EXPECT_TRUE( +json::Expr("") == xpcToJson(xpc_string_create("")) + ); + + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr("123")), + xpc_string_create("123") +) + ); + EXPECT_TRUE( +json::Expr("123") == xpcToJson(xpc_string_create("123")) + ); + + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(" ")), + xpc_string_create(" ") +) + ); + EXPECT_TRUE( +json::Expr(" ") == xpcToJson(xpc_string_create(" ")) + ); + + // Testing two different "patterns" just in case. + std::string kBStringOfAs("A", 1024); + std::string kBStringOfBs("B", 1024); + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(kBStringOfAs.c_str())), + xpc_string_create(kBStringOfAs.c_str()) +) + ); + EXPECT_TRUE( +json::Expr(kBStringOfAs.c_str()) == xpcToJson(xpc_string_create(kBStringOfAs.c_str())) + ); + + EXPECT_TRUE( +xpc_equal( + jsonToXpc(json::Expr(kBStringOfBs.c_str())), + xpc_string_create(kBStringOfBs.c_str()) +) + ); + EXPECT_TRUE( +json::Expr(kBStringOfBs.c_str()) == xpcToJson(xpc_string_create(kBStringOfBs.c_str())) + ); +} + +TEST(JsonXpcConversionTest, Array) { + json::Expr JsonArray{true, "foo", nullptr, 42}; + + xpc_object_t XpcArray = []() { +std::vector XpcArrayElements; +XpcArrayElements.emplace_back(xpc_bool_create(true)); +XpcArrayElements.emplace_back(xpc_string_create("foo")); +XpcArrayElements.emplace_back(xpc_null_create()); +XpcArrayElements.emplace_back(xpc_double_create(42)); + +return xpc_array_create(XpcArrayElements.data(), XpcArrayElements.size()); + }();
[PATCH] D48036: [CUDA] Make min/max shims host+device.
jlebar added a comment. @rsmith friendly ping on this one. https://reviews.llvm.org/D48036 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48562: [clangd] XPC transport layer
jkorous created this revision. jkorous added a project: clang-tools-extra. Herald added subscribers: cfe-commits, MaskRay, ioeric, ilya-biryukov, mgorny. Implementation of alternative transport layer for macOS based on XPC. Based on these two other patches: https://reviews.llvm.org/D48559 https://reviews.llvm.org/D48560 Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D48562 Files: CMakeLists.txt Features.inc.in ProtocolHandlers.h clangd/CMakeLists.txt clangd/xpc/initialize.test lit.cfg lit.site.cfg.in tool/CMakeLists.txt tool/ClangdMain.cpp xpc/CMakeLists.txt xpc/README.txt xpc/XPCDispatcher.cpp xpc/XPCDispatcher.h xpc/cmake/Info.plist.in xpc/cmake/XPCServiceInfo.plist.in xpc/cmake/modules/CreateClangdXPCFramework.cmake xpc/framework/CMakeLists.txt xpc/framework/ClangdXPC.cpp xpc/test-client/CMakeLists.txt xpc/test-client/ClangdXPCTestClient.cpp Index: clangd/CMakeLists.txt === --- clangd/CMakeLists.txt +++ clangd/CMakeLists.txt @@ -52,3 +52,7 @@ LLVMSupport LLVMTestingSupport ) + +if (CLANGD_BUILD_XPC_SUPPORT) + add_subdirectory(xpc) +endif () Index: lit.site.cfg.in === --- lit.site.cfg.in +++ lit.site.cfg.in @@ -11,6 +11,7 @@ config.python_executable = "@PYTHON_EXECUTABLE@" config.target_triple = "@TARGET_TRIPLE@" config.clang_staticanalyzer = @CLANG_ENABLE_STATIC_ANALYZER@ +config.clangd_xpc_support = @CLANGD_BUILD_XPC_SUPPORT@ # Support substitution of the tools and libs dirs with user parameters. This is # used when we can't determine the tool dir at configuration time. Index: lit.cfg === --- lit.cfg +++ lit.cfg @@ -117,6 +117,10 @@ if platform.system() not in ['Windows']: config.available_features.add('ansi-escape-sequences') +# XPC support for Clangd. +if config.clangd_xpc_support: +config.available_features.add('clangd-xpc-support') + if config.clang_staticanalyzer: config.available_features.add('static-analyzer') check_clang_tidy = os.path.join( Index: clangd/xpc/initialize.test === --- /dev/null +++ clangd/xpc/initialize.test @@ -0,0 +1,10 @@ +# RUN: clangd-xpc-test-client < %s | FileCheck %s +# REQUIRES: clangd-xpc-support + +{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootUri":"test:///workspace","capabilities":{},"trace":"off"}} +# CHECK: {"id":0,"jsonrpc":"2.0","result":{"capabilities":{"codeActionProvider":true,"completionProvider":{"resolveProvider":false,"triggerCharacters":[".",">",":"]},"definitionProvider":true,"documentFormattingProvider":true,"documentHighlightProvider":true,"documentOnTypeFormattingProvider":{"firstTriggerCharacter":"}","moreTriggerCharacter":[]},"documentRangeFormattingProvider":true,"executeCommandProvider":{"commands":["clangd.applyFix"]},"hoverProvider":true,"renameProvider":true,"signatureHelpProvider":{"triggerCharacters":["(",","]},"textDocumentSync":2,"workspaceSymbolProvider":true}}} + +{"jsonrpc":"2.0","id":3,"method":"shutdown"} +# CHECK: {"id":3,"jsonrpc":"2.0","result":null} + +{"jsonrpc":"2.0","method":"exit"} Index: xpc/test-client/ClangdXPCTestClient.cpp === --- /dev/null +++ xpc/test-client/ClangdXPCTestClient.cpp @@ -0,0 +1,100 @@ +#include "xpc/XPCJSONConversions.h" +#include "clang/Basic/LLVM.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/Support/LineIterator.h" +#include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/raw_ostream.h" +#include +#include +#include +#include + +typedef const char *(*clangd_xpc_get_bundle_identifier_t)(void); + +using namespace llvm; +using namespace clang; + +std::string getLibraryPath() { + Dl_info info; + if (dladdr((void *)(uintptr_t)getLibraryPath, &info) == 0) +llvm_unreachable("Call to dladdr() failed"); + llvm::SmallString<128> LibClangPath; + LibClangPath = llvm::sys::path::parent_path( + llvm::sys::path::parent_path(info.dli_fname)); + llvm::sys::path::append(LibClangPath, "lib", "ClangdXPC.framework", + "ClangdXPC"); + return LibClangPath.str(); +} + +static void dumpXPCObject(xpc_object_t Object, llvm::raw_ostream &OS) { + xpc_type_t Type = xpc_get_type(Object); + if (Type == XPC_TYPE_DICTIONARY) { +clang::clangd::json::Expr Json = clang::clangd::xpcToJson(Object); +OS << Json; + } else { +OS << ""; + } +} + +int main(int argc, char *argv[]) { + // Open the ClangdXPC dylib in the framework. + std::string LibPath = getLibraryPath(); + void *dlHandle = dlopen(LibPath.c_str(), RTLD_LOCAL | RTLD_FIRST); + if (!dlHandle) +return 1; + + // Lookup the XPC service bundle name, and launch it. + clangd_xpc_get_bundle_identifier_t clangd_xpc_get_bundle_identifie
[PATCH] D48563: [CMake] Use explicit targets for building Linux runtimes
phosek created this revision. phosek added a reviewer: mcgrathr. Herald added subscribers: cfe-commits, mgorny. Previously we were using default logic when building Linux runtimes in Fuchsia toolchain, but that leads to various issues due to how the CMake logic in compiler-rt for determining the platform support is implemented. With this change, we will use explicit target for every provided Linux sysroot. Repository: rC Clang https://reviews.llvm.org/D48563 Files: clang/cmake/caches/Fuchsia-stage2.cmake Index: clang/cmake/caches/Fuchsia-stage2.cmake === --- clang/cmake/caches/Fuchsia-stage2.cmake +++ clang/cmake/caches/Fuchsia-stage2.cmake @@ -27,67 +27,82 @@ set(CMAKE_C_FLAGS_RELWITHDEBINFO "-O3 -gline-tables-only -DNDEBUG" CACHE STRING "") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O3 -gline-tables-only -DNDEBUG" CACHE STRING "") -set(FUCHSIA_BUILTINS_BUILD_TYPE Release CACHE STRING "") -set(FUCHSIA_RUNTIMES_BUILD_TYPE Release CACHE STRING "") -set(FUCHSIA_RUNTIMES_ENABLE_ASSERTIONS ON CACHE BOOL "") +if(APPLE) + list(APPEND builtin_targets "default") + list(APPEND runtime_targets "default") +endif() -set(LLVM_BUILTIN_TARGETS "default;x86_64-fuchsia;aarch64-fuchsia" CACHE STRING "") +foreach(target i386;x86_64;armhf;aarch64) + if(LINUX_${target}_SYSROOT) +# Set the per-target builtins options. +list(APPEND builtin_targets "${target}-linux-gnu") +set(BUILTINS_${target}-linux-gnu_CMAKE_SYSTEM_NAME Linux CACHE STRING "") +set(BUILTINS_${target}-linux-gnu_CMAKE_BUILD_TYPE Release CACHE STRING "") +set(BUILTINS_${target}-linux-gnu_CMAKE_SYSROOT ${LINUX_${target}_SYSROOT} CACHE STRING "") -# Set the per-target builtins options. -foreach(target x86_64;aarch64) - set(BUILTINS_${target}-fuchsia_CMAKE_SYSTEM_NAME Fuchsia CACHE STRING "") - set(BUILTINS_${target}-fuchsia_CMAKE_BUILD_TYPE ${FUCHSIA_BUILTINS_BUILD_TYPE} CACHE STRING "") - set(BUILTINS_${target}-fuchsia_CMAKE_ASM_FLAGS ${FUCHSIA_${target}_C_FLAGS} CACHE PATH "") - set(BUILTINS_${target}-fuchsia_CMAKE_C_FLAGS ${FUCHSIA_${target}_C_FLAGS} CACHE PATH "") - set(BUILTINS_${target}-fuchsia_CMAKE_CXX_FLAGS ${FUCHSIA_${target}_CXX_FLAGS} CACHE PATH "") - set(BUILTINS_${target}-fuchsia_CMAKE_EXE_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") - set(BUILTINS_${target}-fuchsia_CMAKE_SHARED_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") - set(BUILTINS_${target}-fuchsia_CMAKE_MODULE_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") - set(BUILTINS_${target}-fuchsia_CMAKE_SYSROOT ${FUCHSIA_${target}_SYSROOT} CACHE PATH "") +# Set the per-target runtimes options. +list(APPEND runtime_targets "${target}-linux-gnu") +set(RUNTIMES_${target}-linux-gnu_CMAKE_SYSTEM_NAME Linux CACHE STRING "") +set(RUNTIMES_${target}-linux-gnu_CMAKE_BUILD_TYPE Release CACHE STRING "") +set(RUNTIMES_${target}-linux-gnu_CMAKE_SYSROOT ${LINUX_${target}_SYSROOT} CACHE STRING "") +set(RUNTIMES_${target}-linux-gnu_LLVM_ENABLE_ASSERTIONS ON CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBUNWIND_ENABLE_SHARED OFF CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBUNWIND_USE_COMPILER_RT ON CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBUNWIND_INSTALL_LIBRARY OFF CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBCXXABI_USE_COMPILER_RT ON CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBCXXABI_ENABLE_SHARED OFF CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBCXXABI_USE_LLVM_UNWINDER ON CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBCXXABI_ENABLE_STATIC_UNWINDER ON CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBCXXABI_INSTALL_LIBRARY OFF CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBCXX_USE_COMPILER_RT ON CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBCXX_ENABLE_SHARED OFF CACHE BOOL "") +set(RUNTIMES_${target}-linux-gnu_LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "") + endif() endforeach() -set(LLVM_RUNTIME_TARGETS "default;x86_64-fuchsia;aarch64-fuchsia;x86_64-fuchsia-asan:x86_64-fuchsia;aarch64-fuchsia-asan:aarch64-fuchsia" CACHE STRING "") - -# Set the default target runtimes options. -if(NOT APPLE) - set(LIBUNWIND_ENABLE_SHARED OFF CACHE BOOL "") - set(LIBUNWIND_USE_COMPILER_RT ON CACHE BOOL "") - set(LIBUNWIND_INSTALL_LIBRARY OFF CACHE BOOL "") - set(LIBCXXABI_USE_COMPILER_RT ON CACHE BOOL "") - set(LIBCXXABI_ENABLE_SHARED OFF CACHE BOOL "") - set(LIBCXXABI_USE_LLVM_UNWINDER ON CACHE BOOL "") - set(LIBCXXABI_ENABLE_STATIC_UNWINDER ON CACHE BOOL "") - set(LIBCXXABI_INSTALL_LIBRARY OFF CACHE BOOL "") - set(LIBCXX_USE_COMPILER_RT ON CACHE BOOL "") - set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "") - set(LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "") -endif() - -# Set the per-target runtimes options. foreach(target x86_64;aarch64) - set(RUNTIMES_${target}-fuchsia_CMAKE_SYSTEM_NAME Fuchsia CACHE STRING "") - set(RUNTIMES_${targ
[PATCH] D48564: [CMake] Support passing FUCHSIA_SDK as the only variable
phosek created this revision. phosek added reviewers: mcgrathr, juliehockett, jakehehrlich. Herald added subscribers: cfe-commits, mgorny. Now that the structure of Fuchsia SDK has been formalized, we no longer need to pass all the different CFLAGS/LDFLAGS to the CMake build separately, we can simply set the FUCHSIA_SDK variable and derive all the necessary variables from that one inside the cache file. Repository: rC Clang https://reviews.llvm.org/D48564 Files: clang/cmake/caches/Fuchsia-stage2.cmake Index: clang/cmake/caches/Fuchsia-stage2.cmake === --- clang/cmake/caches/Fuchsia-stage2.cmake +++ clang/cmake/caches/Fuchsia-stage2.cmake @@ -31,18 +31,26 @@ set(FUCHSIA_RUNTIMES_BUILD_TYPE Release CACHE STRING "") set(FUCHSIA_RUNTIMES_ENABLE_ASSERTIONS ON CACHE BOOL "") +set(FUCHSIA_aarch64_NAME arm64) +set(FUCHSIA_x86_64_NAME x64) +foreach(target x86_64;aarch64) + set(FUCHSIA_${target}_COMPILER_FLAGS "-I${FUCHSIA_SDK}/pkg/fdio/include") + set(FUCHSIA_${target}_LINKER_FLAGS "-L${FUCHSIA_SDK}/arch/${FUCHSIA_${target}_NAME}/lib") + set(FUCHSIA_${target}_SYSROOT "${FUCHSIA_SDK}/arch/${FUCHSIA_${target}_NAME}/sysroot") +endforeach() + set(LLVM_BUILTIN_TARGETS "default;x86_64-fuchsia;aarch64-fuchsia" CACHE STRING "") # Set the per-target builtins options. foreach(target x86_64;aarch64) set(BUILTINS_${target}-fuchsia_CMAKE_SYSTEM_NAME Fuchsia CACHE STRING "") set(BUILTINS_${target}-fuchsia_CMAKE_BUILD_TYPE ${FUCHSIA_BUILTINS_BUILD_TYPE} CACHE STRING "") - set(BUILTINS_${target}-fuchsia_CMAKE_ASM_FLAGS ${FUCHSIA_${target}_C_FLAGS} CACHE PATH "") - set(BUILTINS_${target}-fuchsia_CMAKE_C_FLAGS ${FUCHSIA_${target}_C_FLAGS} CACHE PATH "") - set(BUILTINS_${target}-fuchsia_CMAKE_CXX_FLAGS ${FUCHSIA_${target}_CXX_FLAGS} CACHE PATH "") - set(BUILTINS_${target}-fuchsia_CMAKE_EXE_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") + set(BUILTINS_${target}-fuchsia_CMAKE_ASM_FLAGS ${FUCHSIA_${target}_COMPILER_FLAGS} CACHE PATH "") + set(BUILTINS_${target}-fuchsia_CMAKE_C_FLAGS ${FUCHSIA_${target}_COMPILER_FLAGS} CACHE PATH "") + set(BUILTINS_${target}-fuchsia_CMAKE_CXX_FLAGS ${FUCHSIA_${target}_COMPILER_FLAGS} CACHE PATH "") set(BUILTINS_${target}-fuchsia_CMAKE_SHARED_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") set(BUILTINS_${target}-fuchsia_CMAKE_MODULE_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") + set(BUILTINS_${target}-fuchsia_CMAKE_EXE_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") set(BUILTINS_${target}-fuchsia_CMAKE_SYSROOT ${FUCHSIA_${target}_SYSROOT} CACHE PATH "") endforeach() @@ -68,12 +76,12 @@ set(RUNTIMES_${target}-fuchsia_CMAKE_SYSTEM_NAME Fuchsia CACHE STRING "") set(RUNTIMES_${target}-fuchsia_CMAKE_BUILD_TYPE ${FUCHSIA_RUNTIMES_BUILD_TYPE} CACHE STRING "") set(RUNTIMES_${target}-fuchsia_CMAKE_BUILD_WITH_INSTALL_RPATH ON CACHE STRING "") - set(RUNTIMES_${target}-fuchsia_CMAKE_ASM_FLAGS ${FUCHSIA_${target}_C_FLAGS} CACHE PATH "") - set(RUNTIMES_${target}-fuchsia_CMAKE_C_FLAGS ${FUCHSIA_${target}_C_FLAGS} CACHE PATH "") - set(RUNTIMES_${target}-fuchsia_CMAKE_CXX_FLAGS ${FUCHSIA_${target}_CXX_FLAGS} CACHE PATH "") - set(RUNTIMES_${target}-fuchsia_CMAKE_EXE_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") + set(RUNTIMES_${target}-fuchsia_CMAKE_ASM_FLAGS ${FUCHSIA_${target}_COMPILER_FLAGS} CACHE PATH "") + set(RUNTIMES_${target}-fuchsia_CMAKE_C_FLAGS ${FUCHSIA_${target}_COMPILER_FLAGS} CACHE PATH "") + set(RUNTIMES_${target}-fuchsia_CMAKE_CXX_FLAGS ${FUCHSIA_${target}_COMPILER_FLAGS} CACHE PATH "") set(RUNTIMES_${target}-fuchsia_CMAKE_SHARED_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") set(RUNTIMES_${target}-fuchsia_CMAKE_MODULE_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") + set(RUNTIMES_${target}-fuchsia_CMAKE_EXE_LINKER_FLAGS ${FUCHSIA_${target}_LINKER_FLAGS} CACHE PATH "") set(RUNTIMES_${target}-fuchsia_CMAKE_SYSROOT ${FUCHSIA_${target}_SYSROOT} CACHE PATH "") set(RUNTIMES_${target}-fuchsia_LLVM_ENABLE_ASSERTIONS ${FUCHSIA_RUNTIMES_ENABLE_ASSERTIONS} CACHE BOOL "") set(RUNTIMES_${target}-fuchsia_LIBUNWIND_USE_COMPILER_RT ON CACHE BOOL "") Index: clang/cmake/caches/Fuchsia-stage2.cmake === --- clang/cmake/caches/Fuchsia-stage2.cmake +++ clang/cmake/caches/Fuchsia-stage2.cmake @@ -31,18 +31,26 @@ set(FUCHSIA_RUNTIMES_BUILD_TYPE Release CACHE STRING "") set(FUCHSIA_RUNTIMES_ENABLE_ASSERTIONS ON CACHE BOOL "") +set(FUCHSIA_aarch64_NAME arm64) +set(FUCHSIA_x86_64_NAME x64) +foreach(target x86_64;aarch64) + set(FUCHSIA_${target}_COMPILER_FLAGS "-I${FUCHSIA_SDK}/pkg/fdio/include") + set(FUCHSIA_${target}_LINKER_FLAGS "-L${FUCHSIA_SDK}/arch/${FUCHSIA_${target}_NAME}/lib") + set(FUCHSIA_${target}_SYSROOT "${FUCHSIA_SDK}/arch/${FUCHSIA_${target}_NAME}/sysroot") +endforeach()
[PATCH] D48559: [clangd] refactoring for XPC transport layer [NFCI]
jkorous added a comment. Followed by these two patches: [clangd] JSON <-> XPC conversions https://reviews.llvm.org/D48560 [clangd] XPC transport layer https://reviews.llvm.org/D48562 Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D48559 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48562: [clangd] XPC transport layer
arphaman added inline comments. Comment at: xpc/test-client/ClangdXPCTestClient.cpp:51 + dlHandle, "clangd_xpc_get_bundle_identifier"); + xpc_connection_t conn = + xpc_connection_create(clangd_xpc_get_bundle_identifier(), NULL); We should probably use the main queue here too to ensure that we don't get bit by concurrent handler invocations. Repository: rCTE Clang Tools Extra https://reviews.llvm.org/D48562 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48459: Respect CMAKE_SYSROOT and CMAKE_CROSSCOMPILING when searching for libxml2.
srhines added a comment. Rui, I added you to this review (and the other corresponding one), as you reviewed ecbeckmann's original work here. Can you take a quick look at these? Thanks. Repository: rC Clang https://reviews.llvm.org/D48459 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r335491 - Revert "[ASTImporter] Import the whole redecl chain of functions"
When reverting things, please say why in the commit message. (In this case, apparently because it broke the lldb buildbots?) On Mon, Jun 25, 2018 at 12:30 PM Gabor Marton via cfe-commits < cfe-commits@lists.llvm.org> wrote: > Author: martong > Date: Mon Jun 25 09:25:30 2018 > New Revision: 335491 > > URL: http://llvm.org/viewvc/llvm-project?rev=335491&view=rev > Log: > Revert "[ASTImporter] Import the whole redecl chain of functions" > > This reverts commit r335480. > > Modified: > cfe/trunk/include/clang/AST/ASTImporter.h > cfe/trunk/lib/AST/ASTImporter.cpp > cfe/trunk/lib/AST/DeclBase.cpp > cfe/trunk/test/ASTMerge/class/test.cpp > cfe/trunk/unittests/AST/ASTImporterTest.cpp > > Modified: cfe/trunk/include/clang/AST/ASTImporter.h > URL: > http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTImporter.h?rev=335491&r1=335490&r2=335491&view=diff > > == > --- cfe/trunk/include/clang/AST/ASTImporter.h (original) > +++ cfe/trunk/include/clang/AST/ASTImporter.h Mon Jun 25 09:25:30 2018 > @@ -43,15 +43,6 @@ class TagDecl; > class TypeSourceInfo; > class Attr; > > - // \brief Returns with a list of declarations started from the > canonical decl > - // then followed by subsequent decls in the translation unit. > - // This gives a canonical list for each entry in the redecl chain. > - // `Decl::redecls()` gives a list of decls which always start from the > - // previous decl and the next item is actually the previous item in the > order > - // of source locations. Thus, `Decl::redecls()` gives different lists > for > - // the different entries in a given redecl chain. > - llvm::SmallVector getCanonicalForwardRedeclChain(Decl* D); > - >/// Imports selected nodes from one AST context into another context, >/// merging AST nodes where appropriate. >class ASTImporter { > > Modified: cfe/trunk/lib/AST/ASTImporter.cpp > URL: > http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=335491&r1=335490&r2=335491&view=diff > > == > --- cfe/trunk/lib/AST/ASTImporter.cpp (original) > +++ cfe/trunk/lib/AST/ASTImporter.cpp Mon Jun 25 09:25:30 2018 > @@ -71,25 +71,6 @@ > > namespace clang { > > - template > - SmallVector > - getCanonicalForwardRedeclChain(Redeclarable* D) { > -SmallVector Redecls; > -for (auto *R : D->getFirstDecl()->redecls()) { > - if (R != D->getFirstDecl()) > -Redecls.push_back(R); > -} > -Redecls.push_back(D->getFirstDecl()); > -std::reverse(Redecls.begin(), Redecls.end()); > -return Redecls; > - } > - > - SmallVector getCanonicalForwardRedeclChain(Decl* D) { > -// Currently only FunctionDecl is supported > -auto FD = cast(D); > -return getCanonicalForwardRedeclChain(FD); > - } > - >class ASTNodeImporter : public TypeVisitor, >public DeclVisitor, >public StmtVisitor { > @@ -214,12 +195,6 @@ namespace clang { > const InContainerTy &Container, > TemplateArgumentListInfo &Result); > > -using TemplateArgsTy = SmallVector; > -using OptionalTemplateArgsTy = Optional; > -std::tuple > -ImportFunctionTemplateWithTemplateArgsFromSpecialization( > -FunctionDecl *FromFD); > - > bool ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl > *ToFD); > > bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, > @@ -433,8 +408,6 @@ namespace clang { > > // Importing overrides. > void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl > *FromMethod); > - > -FunctionDecl *FindFunctionTemplateSpecialization(FunctionDecl > *FromFD); >}; > > template > @@ -464,25 +437,6 @@ bool ASTNodeImporter::ImportTemplateArgu > From.arguments(), Result); > } > > -std::tuple ASTNodeImporter::OptionalTemplateArgsTy> > -ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization( > -FunctionDecl *FromFD) { > - assert(FromFD->getTemplatedKind() == > - FunctionDecl::TK_FunctionTemplateSpecialization); > - auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); > - auto *Template = cast_or_null( > - Importer.Import(FTSInfo->getTemplate())); > - > - // Import template arguments. > - auto TemplArgs = FTSInfo->TemplateArguments->asArray(); > - TemplateArgsTy ToTemplArgs; > - if (ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(), > - ToTemplArgs)) // Error during import. > -return std::make_tuple(Template, OptionalTemplateArgsTy()); > - > - return std::make_tuple(Template, ToTemplArgs); > -} > - > } // namespace clang > > > > // > @@ -2298,17 +2252,23 @@ bool A
Re: r335491 - Revert "[ASTImporter] Import the whole redecl chain of functions"
Hi Nico, Yes, I reverted because it broke one of the lldb build bots. Next time I'll include the reason in the revert commit. Gábor On Mon, 25 Jun 2018, 22:50 Nico Weber, wrote: > When reverting things, please say why in the commit message. (In this > case, apparently because it broke the lldb buildbots?) > > On Mon, Jun 25, 2018 at 12:30 PM Gabor Marton via cfe-commits < > cfe-commits@lists.llvm.org> wrote: > >> Author: martong >> Date: Mon Jun 25 09:25:30 2018 >> New Revision: 335491 >> >> URL: http://llvm.org/viewvc/llvm-project?rev=335491&view=rev >> Log: >> Revert "[ASTImporter] Import the whole redecl chain of functions" >> >> This reverts commit r335480. >> >> Modified: >> cfe/trunk/include/clang/AST/ASTImporter.h >> cfe/trunk/lib/AST/ASTImporter.cpp >> cfe/trunk/lib/AST/DeclBase.cpp >> cfe/trunk/test/ASTMerge/class/test.cpp >> cfe/trunk/unittests/AST/ASTImporterTest.cpp >> >> Modified: cfe/trunk/include/clang/AST/ASTImporter.h >> URL: >> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTImporter.h?rev=335491&r1=335490&r2=335491&view=diff >> >> == >> --- cfe/trunk/include/clang/AST/ASTImporter.h (original) >> +++ cfe/trunk/include/clang/AST/ASTImporter.h Mon Jun 25 09:25:30 2018 >> @@ -43,15 +43,6 @@ class TagDecl; >> class TypeSourceInfo; >> class Attr; >> >> - // \brief Returns with a list of declarations started from the >> canonical decl >> - // then followed by subsequent decls in the translation unit. >> - // This gives a canonical list for each entry in the redecl chain. >> - // `Decl::redecls()` gives a list of decls which always start from the >> - // previous decl and the next item is actually the previous item in >> the order >> - // of source locations. Thus, `Decl::redecls()` gives different lists >> for >> - // the different entries in a given redecl chain. >> - llvm::SmallVector getCanonicalForwardRedeclChain(Decl* D); >> - >>/// Imports selected nodes from one AST context into another context, >>/// merging AST nodes where appropriate. >>class ASTImporter { >> >> Modified: cfe/trunk/lib/AST/ASTImporter.cpp >> URL: >> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=335491&r1=335490&r2=335491&view=diff >> >> == >> --- cfe/trunk/lib/AST/ASTImporter.cpp (original) >> +++ cfe/trunk/lib/AST/ASTImporter.cpp Mon Jun 25 09:25:30 2018 >> @@ -71,25 +71,6 @@ >> >> namespace clang { >> >> - template >> - SmallVector >> - getCanonicalForwardRedeclChain(Redeclarable* D) { >> -SmallVector Redecls; >> -for (auto *R : D->getFirstDecl()->redecls()) { >> - if (R != D->getFirstDecl()) >> -Redecls.push_back(R); >> -} >> -Redecls.push_back(D->getFirstDecl()); >> -std::reverse(Redecls.begin(), Redecls.end()); >> -return Redecls; >> - } >> - >> - SmallVector getCanonicalForwardRedeclChain(Decl* D) { >> -// Currently only FunctionDecl is supported >> -auto FD = cast(D); >> -return getCanonicalForwardRedeclChain(FD); >> - } >> - >>class ASTNodeImporter : public TypeVisitor, >>public DeclVisitor, >>public StmtVisitor { >> @@ -214,12 +195,6 @@ namespace clang { >> const InContainerTy &Container, >> TemplateArgumentListInfo >> &Result); >> >> -using TemplateArgsTy = SmallVector; >> -using OptionalTemplateArgsTy = Optional; >> -std::tuple >> -ImportFunctionTemplateWithTemplateArgsFromSpecialization( >> -FunctionDecl *FromFD); >> - >> bool ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl >> *ToFD); >> >> bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, >> @@ -433,8 +408,6 @@ namespace clang { >> >> // Importing overrides. >> void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl >> *FromMethod); >> - >> -FunctionDecl *FindFunctionTemplateSpecialization(FunctionDecl >> *FromFD); >>}; >> >> template >> @@ -464,25 +437,6 @@ bool ASTNodeImporter::ImportTemplateArgu >> From.arguments(), Result); >> } >> >> -std::tuple> ASTNodeImporter::OptionalTemplateArgsTy> >> >> -ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization( >> -FunctionDecl *FromFD) { >> - assert(FromFD->getTemplatedKind() == >> - FunctionDecl::TK_FunctionTemplateSpecialization); >> - auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); >> - auto *Template = cast_or_null( >> - Importer.Import(FTSInfo->getTemplate())); >> - >> - // Import template arguments. >> - auto TemplArgs = FTSInfo->TemplateArguments->asArray(); >> - TemplateArgsTy ToTemplArgs; >> - if (ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(), >> -
[PATCH] D48100: Append new attributes to the end of an AttributeList.
erichkeane added inline comments. Comment at: test/Sema/attr-target-mv.c:98 int __attribute__((target("sse4.2"))) diff_cc(void); -// expected-error@+1 {{multiversioned function declaration has a different calling convention}} +// expected-error@+1 {{attribute 'target' multiversioning cannot be combined with other attributes}} __vectorcall int __attribute__((target("arch=sandybridge"))) diff_cc(void); echristo wrote: > This appears to have broken a particular error message? Yeah, I actually noticed this last week, and @aaron.ballman and I have been discussing it. Unfortunately, a small list of attributes (including all calling conventions) cause some redistributing of attributes between DeclSpec and Declarators. Due to a bug in that area, linked-list pointers are being rewritten in a fairly mean fashion (it was previously not noticeable since these were at the end). It is going to take a pretty good sized effort to fix (basically, remove the attributelist linked list-ness), but Aaron and I have been working on it for a few days. Reverting this won't change my effort so I'll try to fix this in the meantime. Repository: rC Clang https://reviews.llvm.org/D48100 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48100: Append new attributes to the end of an AttributeList.
rsmith added a comment. This patch appears to have at least caused us to process attributes too many times in some cases. For example: __attribute__((noreturn,noinline,unused)) void f(); before your patch gives this with `clang -Xclang -ast-dump`: `-FunctionDecl 0xccef1e0 <:1:1, col:50> col:48 f 'void () __attribute__((noreturn))' |-UnusedAttr 0xccef280 unused `-NoInlineAttr 0xccef2c8 and after your patch gives this: `-FunctionDecl 0xb913740 <:1:1, col:50> col:48 f 'void () __attribute__((noreturn))' |-NoInlineAttr 0xb9137e0 |-UnusedAttr 0xb913828 unused |-NoInlineAttr 0xb913838 `-UnusedAttr 0xb913848 unused Repository: rC Clang https://reviews.llvm.org/D48100 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D48459: Respect CMAKE_SYSROOT and CMAKE_CROSSCOMPILING when searching for libxml2.
smeenai added reviewers: beanz, phosek. smeenai added a comment. I think it might be more appropriate to pass NO_SYSTEM_ENVIRONMENT_PATH to find_package in case CMAKE_SYSROOT or CMAKE_CROSSCOMPILING are set? That way, we won't search the host system for libxml2 in those cases, but we'll still be able to find it in the custom sysroot or cross-compilation SDK if it's present. Repository: rC Clang https://reviews.llvm.org/D48459 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47757: [Sema] Produce diagnostics when unavailable aligned allocation/deallocation functions are called
ahatanak added a reviewer: jlebar. ahatanak added a subscriber: jlebar. ahatanak added a comment. ping. @jlebar, is the change I made to call-host-fn-from-device.cu correct? Repository: rC Clang https://reviews.llvm.org/D47757 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D47757: [Sema] Produce diagnostics when unavailable aligned allocation/deallocation functions are called
jlebar added a comment. > @jlebar, is the change I made to call-host-fn-from-device.cu correct? I don't think so -- that's a change in overloading behavior afaict. Repository: rC Clang https://reviews.llvm.org/D47757 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r335084 - Append new attributes to the end of an AttributeList.
2018-06-25 14:20 GMT-05:00 Richard Smith : > (I'm not sure what the problem is, but as a data point, Sema::checkCall > iterates over the FormatAttrs in order, so it's possible that changing the > order may have triggered a new warning. That may be due to a pre-existing > order-dependence bug, or it may be that we're losing an attribute here.) In this case the following patch should fix this. diff --git a/lib/Sema/SemaChecking.cpp b/lib/Sema/SemaChecking.cpp index 12a599b4f1..aeb7a83fa6 100644 --- a/lib/Sema/SemaChecking.cpp +++ b/lib/Sema/SemaChecking.cpp @@ -3172,7 +3172,8 @@ void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, // Printf and scanf checking. llvm::SmallBitVector CheckedVarArgs; if (FDecl) { -for (const auto *I : FDecl->specific_attrs()) { +SmallVector FormatAttrs(FDecl->specific_attrs()); +for (const auto *I : llvm::reverse(FormatAttrs)) { // Only create vector if there are format attributes. CheckedVarArgs.resize(Args.size()); However, if I understand __attribute__((format(...))) correctly, there should be just one FormatAttr. >> > Please let me know your plan. (If I don't hear back in a day or so, I'll >> > go >> > ahead and revert for you as the safe default course of action.) >> >> On a weekend? > > > Yes; our policy is generally to revert to green if a patch causes > regressions that aren't going to be fixed in a few hours. This is generally > good for the committer, because it lets you figure out what's wrong and deal > with it on your own schedule rather than being pressured to fix it urgently > because you're blocking the work of others. Should I revert the commit then? Michael ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits