[PATCH] D34329: [GSoC] Clang AST diffing
arphaman added inline comments. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:156 +int TreeRoot::getSubtreePostorder(std::vector &Ids, NodeId Root) const { + int Leaves = 0; + std::function Traverse = [&](NodeId Id) { Please use a more descriptive name e.g. `NumLeaves`. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:157 + int Leaves = 0; + std::function Traverse = [&](NodeId Id) { +const Node &N = getNode(Id); you should be able to use `auto` instead of `std::function` here I think. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:209 +if (X->hasQualifier() && X->getQualifier()->getAsIdentifier()) + Value += std::string(X->getQualifier()->getAsIdentifier()->getName()); +Value += X->getDecl()->getNameAsString(); Qualifiers (i.e. `NestedNameSpecifier`s) can contain multiple identifiers (e.g. `foo::bar::`). You should use the `print` method from `NestedNameSpecifier` instead. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:226 + if (auto *X = DTN.get()) +return Value; + if (auto *X = DTN.get()) This `Value` will always be `""`, right? You can just return `""` here then. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:755 + size_t Position; + std::tie(Kind, Id1, Id2, Position) = Chg; + std::string S; Looking at the unpacking here it's probably better to make `Change` a struct with named fields instead of a tuple. You would still be able to use `emplace` to create the changes though. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:759 + case Delete: +S = formatv("Delete {0}", T1.showNode(Id1)); +break; You can just get rid of the intermediate `S` here and print directly to `OS` in all cases, e.g.: `OS << "Delete " << T1.showNode(Id1) << "\n"` https://reviews.llvm.org/D34329 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34329: [GSoC] Clang AST diffing
klimek added a comment. Reviewing this mainly from the API view, and leaving the technical details to others :) Comment at: include/clang/Tooling/ASTDiff/ASTDiff.h:124 + +class ASTDiff { + TreeRoot &T1, &T2; Generally, can we put the public interface first in the class? Usually folks read a source file top-down, so if the most relevant pieces of code are at the top, the source file gets easier to read and understand. Thus: 1. try to keep clutter (like classes and typedefs not used by a user of the API) in a different header, or forward declare them and define them in the .cpp file 2. sort things into public first, then private in classes. https://reviews.llvm.org/D34329 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34275: [analyzer] Re-implemente current virtual calls checker in a path-sensitive way
xazax.hun added a comment. In https://reviews.llvm.org/D34275#785294, @wangxindsb wrote: > > What about: > > > > struct A { > > A() { > > X x; > > x.virtualMethod(); // this virtual call is ok > > foo(); // should warn here > > } > > virtual foo(); > > } > > int main() { > > A a; > > } > > > > > > Does the checker warn on the second call? > > Yes, the checker warn on the second call. Oh, I think I see how it works now. How about: struct A; struct X { void callFooOfA(A*); }; struct A { A() { X x; x.virtualMethod(); // this virtual call is ok x.callFooOfA(this) } virtual foo(); }; void X::callFooOfA(A* a) { a->foo(); // Would be good to warn here. } int main() { A a; } Comment at: lib/StaticAnalyzer/Checkers/VirtualCallChecker.cpp:1 -//===- VirtualCallChecker.cpp *- C++ -*-==// -// Please add the license back. https://reviews.llvm.org/D34275 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34399: clang-format: introduce InlineOnly short function style
djasper added inline comments. Comment at: include/clang/Format/Format.h:234 + bool allowEmptyFunctionsOnASingleLine() const { + return AllowShortFunctionsOnASingleLine >= ShortFunctionStyle::SFS_Empty; I'd prefer these functions not to be in the public header file. They are implementation details. Either find a header/cpp-file in the lib/ directory to place them in or just remove them for now. They are both still quite small and called only twice each. Comment at: unittests/Format/FormatTest.cpp:6530 + verifyFormat("int f() {\n" + "}", MergeInlineOnly); + Missing line break. Comment at: unittests/Format/FormatTest.cpp:6548 + "{\n" + "}", MergeInlineOnly); + verifyFormat("class C {\n" Missing line break. Generally use clang-format on the patches :). https://reviews.llvm.org/D34399 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34287: Moved code hanlding precompiled preamble out of the ASTUnit.
klimek accepted this revision. klimek added a comment. This revision is now accepted and ready to land. lg https://reviews.llvm.org/D34287 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D33823: [clang-format] Support sorting using declarations
klimek accepted this revision. klimek added a comment. This revision is now accepted and ready to land. lg https://reviews.llvm.org/D33823 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34287: Moved code hanlding precompiled preamble out of the ASTUnit.
This revision was automatically updated to reflect the committed changes. Closed by commit rL305890: Moved code hanlding precompiled preamble out of the ASTUnit. (authored by ibiryukov). Changed prior to commit: https://reviews.llvm.org/D34287?vs=103216&id=103338#toc Repository: rL LLVM https://reviews.llvm.org/D34287 Files: cfe/trunk/include/clang/Frontend/ASTUnit.h cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h cfe/trunk/lib/Frontend/ASTUnit.cpp cfe/trunk/lib/Frontend/CMakeLists.txt cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp Index: cfe/trunk/include/clang/Frontend/ASTUnit.h === --- cfe/trunk/include/clang/Frontend/ASTUnit.h +++ cfe/trunk/include/clang/Frontend/ASTUnit.h @@ -25,6 +25,7 @@ #include "clang/Lex/PreprocessingRecord.h" #include "clang/Sema/CodeCompleteConsumer.h" #include "clang/Serialization/ASTBitCodes.h" +#include "clang/Frontend/PrecompiledPreamble.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" @@ -199,103 +200,15 @@ /// of that loading. It must be cleared when preamble is recreated. llvm::StringMap PreambleSrcLocCache; -public: - class PreambleData { -const FileEntry *File; -std::vector Buffer; -mutable unsigned NumLines; - - public: -PreambleData() : File(nullptr), NumLines(0) { } - -void assign(const FileEntry *F, const char *begin, const char *end) { - File = F; - Buffer.assign(begin, end); - NumLines = 0; -} - -void clear() { Buffer.clear(); File = nullptr; NumLines = 0; } - -size_t size() const { return Buffer.size(); } -bool empty() const { return Buffer.empty(); } - -const char *getBufferStart() const { return &Buffer[0]; } - -unsigned getNumLines() const { - if (NumLines) -return NumLines; - countLines(); - return NumLines; -} - -SourceRange getSourceRange(const SourceManager &SM) const { - SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID()); - return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1)); -} - - private: -void countLines() const; - }; - - const PreambleData &getPreambleData() const { -return Preamble; - } - - /// Data used to determine if a file used in the preamble has been changed. - struct PreambleFileHash { -/// All files have size set. -off_t Size; - -/// Modification time is set for files that are on disk. For memory -/// buffers it is zero. -time_t ModTime; - -/// Memory buffers have MD5 instead of modification time. We don't -/// compute MD5 for on-disk files because we hope that modification time is -/// enough to tell if the file was changed. -llvm::MD5::MD5Result MD5; - -static PreambleFileHash createForFile(off_t Size, time_t ModTime); -static PreambleFileHash -createForMemoryBuffer(const llvm::MemoryBuffer *Buffer); - -friend bool operator==(const PreambleFileHash &LHS, - const PreambleFileHash &RHS); - -friend bool operator!=(const PreambleFileHash &LHS, - const PreambleFileHash &RHS) { - return !(LHS == RHS); -} - }; - private: - /// \brief The contents of the preamble that has been precompiled to - /// \c PreambleFile. - PreambleData Preamble; - - /// \brief Whether the preamble ends at the start of a new line. - /// - /// Used to inform the lexer as to whether it's starting at the beginning of - /// a line after skipping the preamble. - bool PreambleEndsAtStartOfLine; - - /// \brief Keeps track of the files that were used when computing the - /// preamble, with both their buffer size and their modification time. - /// - /// If any of the files have changed from one compile to the next, - /// the preamble must be thrown away. - llvm::StringMap FilesInPreamble; + /// The contents of the preamble. + llvm::Optional Preamble; /// \brief When non-NULL, this is the buffer used to store the contents of /// the main file when it has been padded for use with the precompiled /// preamble. std::unique_ptr SavedMainFileBuffer; - /// \brief When non-NULL, this is the buffer used to store the - /// contents of the preamble when it has been padded to build the - /// precompiled preamble. - std::unique_ptr PreambleBuffer; - /// \brief The number of warnings that occurred while parsing the preamble. /// /// This value will be used to restore the state of the \c DiagnosticsEngine @@ -438,21 +351,6 @@ std::unique_ptr OverrideMainBuffer, IntrusiveRefCntPtr VFS); - struct ComputedPreamble { -llvm::MemoryBuffer *Buffer; -std::unique_ptr Owner; -unsigned Size; -bool PreambleEndsAtStartOfLine; -ComputedPreamble(llvm::MemoryBuffer *Buffer, - std::unique_ptr Owner, unsigned Size, - bool PreambleEndsAt
r305890 - Moved code hanlding precompiled preamble out of the ASTUnit.
Author: ibiryukov Date: Wed Jun 21 05:24:58 2017 New Revision: 305890 URL: http://llvm.org/viewvc/llvm-project?rev=305890&view=rev Log: Moved code hanlding precompiled preamble out of the ASTUnit. Reviewers: bkramer, krasimir, arphaman, akyrtzi, klimek Reviewed By: klimek Subscribers: mgorny, klimek, cfe-commits Differential Revision: https://reviews.llvm.org/D34287 Added: cfe/trunk/include/clang/Frontend/PrecompiledPreamble.h cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp Modified: cfe/trunk/include/clang/Frontend/ASTUnit.h cfe/trunk/lib/Frontend/ASTUnit.cpp cfe/trunk/lib/Frontend/CMakeLists.txt Modified: cfe/trunk/include/clang/Frontend/ASTUnit.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/ASTUnit.h?rev=305890&r1=305889&r2=305890&view=diff == --- cfe/trunk/include/clang/Frontend/ASTUnit.h (original) +++ cfe/trunk/include/clang/Frontend/ASTUnit.h Wed Jun 21 05:24:58 2017 @@ -25,6 +25,7 @@ #include "clang/Lex/PreprocessingRecord.h" #include "clang/Sema/CodeCompleteConsumer.h" #include "clang/Serialization/ASTBitCodes.h" +#include "clang/Frontend/PrecompiledPreamble.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" @@ -199,103 +200,15 @@ private: /// of that loading. It must be cleared when preamble is recreated. llvm::StringMap PreambleSrcLocCache; -public: - class PreambleData { -const FileEntry *File; -std::vector Buffer; -mutable unsigned NumLines; - - public: -PreambleData() : File(nullptr), NumLines(0) { } - -void assign(const FileEntry *F, const char *begin, const char *end) { - File = F; - Buffer.assign(begin, end); - NumLines = 0; -} - -void clear() { Buffer.clear(); File = nullptr; NumLines = 0; } - -size_t size() const { return Buffer.size(); } -bool empty() const { return Buffer.empty(); } - -const char *getBufferStart() const { return &Buffer[0]; } - -unsigned getNumLines() const { - if (NumLines) -return NumLines; - countLines(); - return NumLines; -} - -SourceRange getSourceRange(const SourceManager &SM) const { - SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID()); - return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1)); -} - - private: -void countLines() const; - }; - - const PreambleData &getPreambleData() const { -return Preamble; - } - - /// Data used to determine if a file used in the preamble has been changed. - struct PreambleFileHash { -/// All files have size set. -off_t Size; - -/// Modification time is set for files that are on disk. For memory -/// buffers it is zero. -time_t ModTime; - -/// Memory buffers have MD5 instead of modification time. We don't -/// compute MD5 for on-disk files because we hope that modification time is -/// enough to tell if the file was changed. -llvm::MD5::MD5Result MD5; - -static PreambleFileHash createForFile(off_t Size, time_t ModTime); -static PreambleFileHash -createForMemoryBuffer(const llvm::MemoryBuffer *Buffer); - -friend bool operator==(const PreambleFileHash &LHS, - const PreambleFileHash &RHS); - -friend bool operator!=(const PreambleFileHash &LHS, - const PreambleFileHash &RHS) { - return !(LHS == RHS); -} - }; - private: - /// \brief The contents of the preamble that has been precompiled to - /// \c PreambleFile. - PreambleData Preamble; - - /// \brief Whether the preamble ends at the start of a new line. - /// - /// Used to inform the lexer as to whether it's starting at the beginning of - /// a line after skipping the preamble. - bool PreambleEndsAtStartOfLine; - - /// \brief Keeps track of the files that were used when computing the - /// preamble, with both their buffer size and their modification time. - /// - /// If any of the files have changed from one compile to the next, - /// the preamble must be thrown away. - llvm::StringMap FilesInPreamble; + /// The contents of the preamble. + llvm::Optional Preamble; /// \brief When non-NULL, this is the buffer used to store the contents of /// the main file when it has been padded for use with the precompiled /// preamble. std::unique_ptr SavedMainFileBuffer; - /// \brief When non-NULL, this is the buffer used to store the - /// contents of the preamble when it has been padded to build the - /// precompiled preamble. - std::unique_ptr PreambleBuffer; - /// \brief The number of warnings that occurred while parsing the preamble. /// /// This value will be used to restore the state of the \c DiagnosticsEngine @@ -438,21 +351,6 @@ private: std::unique_ptr OverrideMainBuffer, IntrusiveRefCntPtr VFS); - struct ComputedPreamble { -llvm
r305891 - Revert r305678: [driver][macOS] Pick the system version for the
Author: arphaman Date: Wed Jun 21 05:27:24 2017 New Revision: 305891 URL: http://llvm.org/viewvc/llvm-project?rev=305891&view=rev Log: Revert r305678: [driver][macOS] Pick the system version for the deployment target if the SDK is newer than the system This commit also reverts follow-up commits r305680 and r305685 that have buildbot fixes. The change in r305678 wasn't correct because it relied on `llvm::sys::getProcessTriple`, which uses a pre-configured OS version. We should lookup the actual macOS version of the system on which the compiler is running. Removed: cfe/trunk/test/Driver/darwin-sdk-vs-os-version.c Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Darwin.cpp?rev=305891&r1=305890&r2=305891&view=diff == --- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp (original) +++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Wed Jun 21 05:27:24 2017 @@ -1118,27 +1118,6 @@ void DarwinClang::AddLinkRuntimeLibArgs( } } -/// Returns the most appropriate macOS target version for the current process. -/// -/// If the macOS SDK version is the same or earlier than the system version, -/// then the SDK version is returned. Otherwise the system version is returned. -static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) { - unsigned Major, Minor, Micro; - llvm::Triple SystemTriple(llvm::sys::getProcessTriple()); - if (!SystemTriple.isMacOSX()) -return MacOSSDKVersion; - SystemTriple.getMacOSXVersion(Major, Minor, Micro); - VersionTuple SystemVersion(Major, Minor, Micro); - bool HadExtra; - if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro, - HadExtra)) -return MacOSSDKVersion; - VersionTuple SDKVersion(Major, Minor, Micro); - if (SDKVersion > SystemVersion) -return SystemVersion.getAsString(); - return MacOSSDKVersion; -} - void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { const OptTable &Opts = getDriver().getOpts(); @@ -1231,7 +1210,7 @@ void Darwin::AddDeploymentTarget(Derived SDK.startswith("iPhoneSimulator")) iOSTarget = Version; else if (SDK.startswith("MacOSX")) - OSXTarget = getSystemOrSDKMacOSVersion(Version); + OSXTarget = Version; else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator")) WatchOSTarget = Version; Removed: cfe/trunk/test/Driver/darwin-sdk-vs-os-version.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/darwin-sdk-vs-os-version.c?rev=305890&view=auto == --- cfe/trunk/test/Driver/darwin-sdk-vs-os-version.c (original) +++ cfe/trunk/test/Driver/darwin-sdk-vs-os-version.c (removed) @@ -1,10 +0,0 @@ -// REQUIRES: system-darwin - -// Ensure that we never pick a version that's based on the SDK that's newer than -// the system version: -// RUN: rm -rf %t/SDKs/MacOSX10.99.99.sdk -// RUN: mkdir -p %t/SDKs/MacOSX10.99.99.sdk -// RUN: %clang -target x86_64-apple-darwin -isysroot %t/SDKs/MacOSX10.99.99.sdk %s -### 2>&1 \ -// RUN: | FileCheck --check-prefix=CHECK-MACOSX-SYSTEM-VERSION %s - -// CHECK-MACOSX-SYSTEM-VERSION-NOT: 10.99.99" ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34198: Fix __has_trivial_destructor crash when the type is incomplete with unknown array bounds.
puneetha updated this revision to Diff 103337. puneetha added a comment. Updated files to address the review comments. https://reviews.llvm.org/D34198 Files: lib/Sema/SemaExprCXX.cpp test/SemaCXX/type-traits.cpp Index: test/SemaCXX/type-traits.cpp === --- test/SemaCXX/type-traits.cpp +++ test/SemaCXX/type-traits.cpp @@ -1572,8 +1572,10 @@ { int arr[T(__has_trivial_destructor(AllDefaulted))]; } { int arr[T(__has_trivial_destructor(AllDeleted))]; } { int arr[T(__has_trivial_destructor(DerivesHasRef))]; } + { int arr[T(__has_trivial_destructor(ACompleteType[]))]; } { int arr[F(__has_trivial_destructor(HasDest))]; } + { int arr[F(__has_trivial_destructor(AnIncompleteType[]))]; } // expected-error {{incomplete type}} { int arr[F(__has_trivial_destructor(void))]; } { int arr[F(__has_trivial_destructor(cvoid))]; } { int arr[F(__has_trivial_destructor(AllPrivate))]; } Index: lib/Sema/SemaExprCXX.cpp === --- lib/Sema/SemaExprCXX.cpp +++ lib/Sema/SemaExprCXX.cpp @@ -4093,15 +4093,9 @@ case UTT_IsStandardLayout: case UTT_IsPOD: case UTT_IsLiteral: -ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); -LLVM_FALLTHROUGH; - - // C++1z [meta.unary.prop]: - // T shall be a complete type, cv void, or an array of unknown bound. - case UTT_IsDestructible: - case UTT_IsNothrowDestructible: - case UTT_IsTriviallyDestructible: - // Per the GCC type traits documentation, the same constraints apply to these. + // Per the GCC type traits documentation, T shall be a complete type, cv void, + // or an array of unknown bound. But GCC actually imposes the same constraints + // as above. case UTT_HasNothrowAssign: case UTT_HasNothrowMoveAssign: case UTT_HasNothrowConstructor: @@ -4113,6 +4107,14 @@ case UTT_HasTrivialCopy: case UTT_HasTrivialDestructor: case UTT_HasVirtualDestructor: +ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); +LLVM_FALLTHROUGH; + + // C++1z [meta.unary.prop]: + // T shall be a complete type, cv void, or an array of unknown bound. + case UTT_IsDestructible: + case UTT_IsNothrowDestructible: + case UTT_IsTriviallyDestructible: if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) return true; Index: test/SemaCXX/type-traits.cpp === --- test/SemaCXX/type-traits.cpp +++ test/SemaCXX/type-traits.cpp @@ -1572,8 +1572,10 @@ { int arr[T(__has_trivial_destructor(AllDefaulted))]; } { int arr[T(__has_trivial_destructor(AllDeleted))]; } { int arr[T(__has_trivial_destructor(DerivesHasRef))]; } + { int arr[T(__has_trivial_destructor(ACompleteType[]))]; } { int arr[F(__has_trivial_destructor(HasDest))]; } + { int arr[F(__has_trivial_destructor(AnIncompleteType[]))]; } // expected-error {{incomplete type}} { int arr[F(__has_trivial_destructor(void))]; } { int arr[F(__has_trivial_destructor(cvoid))]; } { int arr[F(__has_trivial_destructor(AllPrivate))]; } Index: lib/Sema/SemaExprCXX.cpp === --- lib/Sema/SemaExprCXX.cpp +++ lib/Sema/SemaExprCXX.cpp @@ -4093,15 +4093,9 @@ case UTT_IsStandardLayout: case UTT_IsPOD: case UTT_IsLiteral: -ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); -LLVM_FALLTHROUGH; - - // C++1z [meta.unary.prop]: - // T shall be a complete type, cv void, or an array of unknown bound. - case UTT_IsDestructible: - case UTT_IsNothrowDestructible: - case UTT_IsTriviallyDestructible: - // Per the GCC type traits documentation, the same constraints apply to these. + // Per the GCC type traits documentation, T shall be a complete type, cv void, + // or an array of unknown bound. But GCC actually imposes the same constraints + // as above. case UTT_HasNothrowAssign: case UTT_HasNothrowMoveAssign: case UTT_HasNothrowConstructor: @@ -4113,6 +4107,14 @@ case UTT_HasTrivialCopy: case UTT_HasTrivialDestructor: case UTT_HasVirtualDestructor: +ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); +LLVM_FALLTHROUGH; + + // C++1z [meta.unary.prop]: + // T shall be a complete type, cv void, or an array of unknown bound. + case UTT_IsDestructible: + case UTT_IsNothrowDestructible: + case UTT_IsTriviallyDestructible: if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) return true; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34439: Add GCC's noexcept-type alias for c++1z-compat-mangling
teemperor created this revision. GCC has named this `-Wnoexcept-type`, so let's add an alias to stay compatible with the GCC flags. https://reviews.llvm.org/D34439 Files: include/clang/Basic/DiagnosticGroups.td test/SemaCXX/cxx1z-noexcept-function-type.cpp Index: test/SemaCXX/cxx1z-noexcept-function-type.cpp === --- test/SemaCXX/cxx1z-noexcept-function-type.cpp +++ test/SemaCXX/cxx1z-noexcept-function-type.cpp @@ -1,6 +1,7 @@ // RUN: %clang_cc1 -std=c++14 -verify -fexceptions -fcxx-exceptions %s // RUN: %clang_cc1 -std=c++1z -verify -fexceptions -fcxx-exceptions %s -Wno-dynamic-exception-spec // RUN: %clang_cc1 -std=c++14 -verify -fexceptions -fcxx-exceptions -Wno-c++1z-compat-mangling -DNO_COMPAT_MANGLING %s +// RUN: %clang_cc1 -std=c++14 -verify -fexceptions -fcxx-exceptions -Wno-noexcept-type -DNO_COMPAT_MANGLING %s #if __cplusplus > 201402L Index: include/clang/Basic/DiagnosticGroups.td === --- include/clang/Basic/DiagnosticGroups.td +++ include/clang/Basic/DiagnosticGroups.td @@ -150,6 +150,8 @@ def FormatExtraArgs : DiagGroup<"format-extra-args">; def FormatZeroLength : DiagGroup<"format-zero-length">; def CXX1zCompatMangling : DiagGroup<"c++1z-compat-mangling">; +// Name of this warning in GCC. +def NoexceptType : DiagGroup<"noexcept-type", [CXX1zCompatMangling]>; // Warnings for C++1y code which is not compatible with prior C++ standards. def CXXPre14Compat : DiagGroup<"c++98-c++11-compat">; Index: test/SemaCXX/cxx1z-noexcept-function-type.cpp === --- test/SemaCXX/cxx1z-noexcept-function-type.cpp +++ test/SemaCXX/cxx1z-noexcept-function-type.cpp @@ -1,6 +1,7 @@ // RUN: %clang_cc1 -std=c++14 -verify -fexceptions -fcxx-exceptions %s // RUN: %clang_cc1 -std=c++1z -verify -fexceptions -fcxx-exceptions %s -Wno-dynamic-exception-spec // RUN: %clang_cc1 -std=c++14 -verify -fexceptions -fcxx-exceptions -Wno-c++1z-compat-mangling -DNO_COMPAT_MANGLING %s +// RUN: %clang_cc1 -std=c++14 -verify -fexceptions -fcxx-exceptions -Wno-noexcept-type -DNO_COMPAT_MANGLING %s #if __cplusplus > 201402L Index: include/clang/Basic/DiagnosticGroups.td === --- include/clang/Basic/DiagnosticGroups.td +++ include/clang/Basic/DiagnosticGroups.td @@ -150,6 +150,8 @@ def FormatExtraArgs : DiagGroup<"format-extra-args">; def FormatZeroLength : DiagGroup<"format-zero-length">; def CXX1zCompatMangling : DiagGroup<"c++1z-compat-mangling">; +// Name of this warning in GCC. +def NoexceptType : DiagGroup<"noexcept-type", [CXX1zCompatMangling]>; // Warnings for C++1y code which is not compatible with prior C++ standards. def CXXPre14Compat : DiagGroup<"c++98-c++11-compat">; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34198: Fix __has_trivial_destructor crash when the type is incomplete with unknown array bounds.
puneetha marked 2 inline comments as done. puneetha added inline comments. Comment at: lib/Sema/SemaExprCXX.cpp:4128 +return true; +} + rjmccall wrote: > I don't understand the difference you're creating between traits here. Three > specific traits about destructibility allow incomplete array types regardless > of whether the base type is incomplete, but the rest do not? > > Anyway, I think what you want here is basically just: > > if (auto ArrayTy = S.Context.getAsIncompleteArrayType(ArgTy)) { > ArgTy = ArrayTy->getElementType(); > } Of my understanding, these traits are defined by MSVC. There is no mention of them in the GCC type-traits documentation. For these traits, GCC lets us pass an array of incomplete bounds for any base type, complete or incomplete. Please correct me if I am wrong. https://reviews.llvm.org/D34198 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34440: [Clang] Expand response files before loading compilation database
vladimir.plyashkun created this revision. vladimir.plyashkun added a project: clang. Herald added a subscriber: mgorny. Due to command line length restrictions, arguments can be passed through response files. Before trying to load compilation database from command line, response files should be expanded first. Repository: rL LLVM https://reviews.llvm.org/D34440 Files: lib/Tooling/CommonOptionsParser.cpp unittests/Tooling/CMakeLists.txt unittests/Tooling/CommonOptionsParserTest.cpp Index: unittests/Tooling/CMakeLists.txt === --- unittests/Tooling/CMakeLists.txt +++ unittests/Tooling/CMakeLists.txt @@ -12,6 +12,7 @@ add_clang_unittest(ToolingTests CommentHandlerTest.cpp + CommonOptionsParserTest.cpp CompilationDatabaseTest.cpp FixItTest.cpp LookupTest.cpp Index: unittests/Tooling/CommonOptionsParserTest.cpp === --- /dev/null +++ unittests/Tooling/CommonOptionsParserTest.cpp @@ -0,0 +1,68 @@ +//===- unittests/Tooling/CommonOptionsParserTest.cpp +//--===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// + +#include "clang/Tooling/CommonOptionsParser.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Path.h" +#include "gtest/gtest.h" +#include + +using namespace llvm; +using namespace clang::tooling; + +class CommonOptionsParserTest : public testing::Test { +public: + SmallString<128> TestDir; + SmallString<128> ResponseFileName; + + CommonOptionsParserTest() { +std::error_code EC = sys::fs::createUniqueDirectory("unittest", TestDir); +EXPECT_TRUE(!EC); +sys::path::append(ResponseFileName, TestDir, "resp"); + } + void setResponseFileContent(const std::string &content) { +std::ofstream File(ResponseFileName.c_str()); +EXPECT_TRUE(File.is_open()); +File << content; +File.close(); + } + ~CommonOptionsParserTest() override { +sys::fs::remove(ResponseFileName); +sys::fs::remove(TestDir); + } +}; + +TEST_F(CommonOptionsParserTest, + ExpandResponseFileBeforeLoadingCompilationDatabase) { + setResponseFileContent("-option_1 -- -option_2=true -option_3"); + SmallString<128> ResponseRef; + ResponseRef.append(1, '@'); + ResponseRef.append(ResponseFileName.c_str()); + int Argc = 3; + const char *Argv[] = {"pos_1", "pos_2", ResponseRef.c_str()}; + cl::OptionCategory Category("options"); + cl::opt option1("option_1", cl::desc(""), cl::init(false), +cl::cat(Category)); + cl::opt option2("option_2", cl::desc(""), cl::init(false), +cl::cat(Category)); + cl::opt option3("option_3", cl::desc(""), cl::init(false), +cl::cat(Category)); + CommonOptionsParser Parser(Argc, Argv, Category); + CompilationDatabase &Database = Parser.getCompilations(); + std::vector ActualCC = Database.getCompileCommands("source"); + ASSERT_EQ(1u, ActualCC.size()); + std::vector ExpectedCmd; + ExpectedCmd.push_back("clang-tool"); + ExpectedCmd.push_back("-option_2=true"); + ExpectedCmd.push_back("-option_3"); + ExpectedCmd.push_back("source"); + + ASSERT_EQ(ExpectedCmd, ActualCC[0].CommandLine); +} \ No newline at end of file Index: lib/Tooling/CommonOptionsParser.cpp === --- lib/Tooling/CommonOptionsParser.cpp +++ lib/Tooling/CommonOptionsParser.cpp @@ -25,6 +25,7 @@ //===--===// #include "llvm/Support/CommandLine.h" +#include "llvm/Support/StringSaver.h" #include "clang/Tooling/ArgumentsAdjusters.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" @@ -115,7 +116,13 @@ cl::cat(Category)); cl::HideUnrelatedOptions(Category); - + //Expand response files before loading compilation database from command line + SmallVector newArgv(argv, argv + argc); + BumpPtrAllocator A; + StringSaver Saver(A); + cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, newArgv); + argv = &newArgv[0]; + argc = static_cast(newArgv.size()); std::string ErrorMessage; Compilations = FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage); ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305896 - [analyzer] LocalizationChecker: Support new localizable APIs.
Author: dergachev Date: Wed Jun 21 06:12:07 2017 New Revision: 305896 URL: http://llvm.org/viewvc/llvm-project?rev=305896&view=rev Log: [analyzer] LocalizationChecker: Support new localizable APIs. Add support for new methods that were added in macOS High Sierra & iOS 11 and require a localized string. Patch by Kulpreet Chilana! rdar://problem/32795210 Differential Revision: https://reviews.llvm.org/D34266 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp?rev=305896&r1=305895&r2=305896&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp Wed Jun 21 06:12:07 2017 @@ -281,6 +281,9 @@ void NonLocalizedStringChecker::initUIMe IdentifierInfo *setLabelNSSegmentedControl[] = { &Ctx.Idents.get("setLabel"), &Ctx.Idents.get("forSegment")}; ADD_METHOD(NSSegmentedControl, setLabelNSSegmentedControl, 2, 0) + IdentifierInfo *setToolTipNSSegmentedControl[] = { + &Ctx.Idents.get("setToolTip"), &Ctx.Idents.get("forSegment")}; + ADD_METHOD(NSSegmentedControl, setToolTipNSSegmentedControl, 2, 0) NEW_RECEIVER(NSButtonCell) ADD_UNARY_METHOD(NSButtonCell, setTitle, 0) @@ -562,6 +565,46 @@ void NonLocalizedStringChecker::initUIMe IdentifierInfo *setTitleUISegmentedControl[] = { &Ctx.Idents.get("setTitle"), &Ctx.Idents.get("forSegmentAtIndex")}; ADD_METHOD(UISegmentedControl, setTitleUISegmentedControl, 2, 0) + + NEW_RECEIVER(NSAccessibilityCustomRotorItemResult) + IdentifierInfo + *initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult[] = { + &Ctx.Idents.get("initWithItemLoadingToken"), + &Ctx.Idents.get("customLabel")}; + ADD_METHOD(NSAccessibilityCustomRotorItemResult, + initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult, 2, 1) + ADD_UNARY_METHOD(NSAccessibilityCustomRotorItemResult, setCustomLabel, 0) + + NEW_RECEIVER(UIContextualAction) + IdentifierInfo *contextualActionWithStyleUIContextualAction[] = { + &Ctx.Idents.get("contextualActionWithStyle"), &Ctx.Idents.get("title"), + &Ctx.Idents.get("handler")}; + ADD_METHOD(UIContextualAction, contextualActionWithStyleUIContextualAction, 3, + 1) + ADD_UNARY_METHOD(UIContextualAction, setTitle, 0) + + NEW_RECEIVER(NSAccessibilityCustomRotor) + IdentifierInfo *initWithLabelNSAccessibilityCustomRotor[] = { + &Ctx.Idents.get("initWithLabel"), &Ctx.Idents.get("itemSearchDelegate")}; + ADD_METHOD(NSAccessibilityCustomRotor, + initWithLabelNSAccessibilityCustomRotor, 2, 0) + ADD_UNARY_METHOD(NSAccessibilityCustomRotor, setLabel, 0) + + NEW_RECEIVER(NSWindowTab) + ADD_UNARY_METHOD(NSWindowTab, setTitle, 0) + ADD_UNARY_METHOD(NSWindowTab, setToolTip, 0) + + NEW_RECEIVER(NSAccessibilityCustomAction) + IdentifierInfo *initWithNameNSAccessibilityCustomAction[] = { + &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("handler")}; + ADD_METHOD(NSAccessibilityCustomAction, + initWithNameNSAccessibilityCustomAction, 2, 0) + IdentifierInfo *initWithNameTargetNSAccessibilityCustomAction[] = { + &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("target"), + &Ctx.Idents.get("selector")}; + ADD_METHOD(NSAccessibilityCustomAction, + initWithNameTargetNSAccessibilityCustomAction, 3, 0) + ADD_UNARY_METHOD(NSAccessibilityCustomAction, setName, 0) } #define LSF_INSERT(function_name) LSF.insert(&Ctx.Idents.get(function_name)); ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34266: Static Analyzer - Localizability Checker: New Localizable APIs for macOS High Sierra & iOS 11
This revision was automatically updated to reflect the committed changes. Closed by commit rL305896: [analyzer] LocalizationChecker: Support new localizable APIs. (authored by dergachev). Changed prior to commit: https://reviews.llvm.org/D34266?vs=102771&id=103347#toc Repository: rL LLVM https://reviews.llvm.org/D34266 Files: cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp Index: cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp === --- cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp +++ cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp @@ -281,6 +281,9 @@ IdentifierInfo *setLabelNSSegmentedControl[] = { &Ctx.Idents.get("setLabel"), &Ctx.Idents.get("forSegment")}; ADD_METHOD(NSSegmentedControl, setLabelNSSegmentedControl, 2, 0) + IdentifierInfo *setToolTipNSSegmentedControl[] = { + &Ctx.Idents.get("setToolTip"), &Ctx.Idents.get("forSegment")}; + ADD_METHOD(NSSegmentedControl, setToolTipNSSegmentedControl, 2, 0) NEW_RECEIVER(NSButtonCell) ADD_UNARY_METHOD(NSButtonCell, setTitle, 0) @@ -562,6 +565,46 @@ IdentifierInfo *setTitleUISegmentedControl[] = { &Ctx.Idents.get("setTitle"), &Ctx.Idents.get("forSegmentAtIndex")}; ADD_METHOD(UISegmentedControl, setTitleUISegmentedControl, 2, 0) + + NEW_RECEIVER(NSAccessibilityCustomRotorItemResult) + IdentifierInfo + *initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult[] = { + &Ctx.Idents.get("initWithItemLoadingToken"), + &Ctx.Idents.get("customLabel")}; + ADD_METHOD(NSAccessibilityCustomRotorItemResult, + initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult, 2, 1) + ADD_UNARY_METHOD(NSAccessibilityCustomRotorItemResult, setCustomLabel, 0) + + NEW_RECEIVER(UIContextualAction) + IdentifierInfo *contextualActionWithStyleUIContextualAction[] = { + &Ctx.Idents.get("contextualActionWithStyle"), &Ctx.Idents.get("title"), + &Ctx.Idents.get("handler")}; + ADD_METHOD(UIContextualAction, contextualActionWithStyleUIContextualAction, 3, + 1) + ADD_UNARY_METHOD(UIContextualAction, setTitle, 0) + + NEW_RECEIVER(NSAccessibilityCustomRotor) + IdentifierInfo *initWithLabelNSAccessibilityCustomRotor[] = { + &Ctx.Idents.get("initWithLabel"), &Ctx.Idents.get("itemSearchDelegate")}; + ADD_METHOD(NSAccessibilityCustomRotor, + initWithLabelNSAccessibilityCustomRotor, 2, 0) + ADD_UNARY_METHOD(NSAccessibilityCustomRotor, setLabel, 0) + + NEW_RECEIVER(NSWindowTab) + ADD_UNARY_METHOD(NSWindowTab, setTitle, 0) + ADD_UNARY_METHOD(NSWindowTab, setToolTip, 0) + + NEW_RECEIVER(NSAccessibilityCustomAction) + IdentifierInfo *initWithNameNSAccessibilityCustomAction[] = { + &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("handler")}; + ADD_METHOD(NSAccessibilityCustomAction, + initWithNameNSAccessibilityCustomAction, 2, 0) + IdentifierInfo *initWithNameTargetNSAccessibilityCustomAction[] = { + &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("target"), + &Ctx.Idents.get("selector")}; + ADD_METHOD(NSAccessibilityCustomAction, + initWithNameTargetNSAccessibilityCustomAction, 3, 0) + ADD_UNARY_METHOD(NSAccessibilityCustomAction, setName, 0) } #define LSF_INSERT(function_name) LSF.insert(&Ctx.Idents.get(function_name)); Index: cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp === --- cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp +++ cfe/trunk/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp @@ -281,6 +281,9 @@ IdentifierInfo *setLabelNSSegmentedControl[] = { &Ctx.Idents.get("setLabel"), &Ctx.Idents.get("forSegment")}; ADD_METHOD(NSSegmentedControl, setLabelNSSegmentedControl, 2, 0) + IdentifierInfo *setToolTipNSSegmentedControl[] = { + &Ctx.Idents.get("setToolTip"), &Ctx.Idents.get("forSegment")}; + ADD_METHOD(NSSegmentedControl, setToolTipNSSegmentedControl, 2, 0) NEW_RECEIVER(NSButtonCell) ADD_UNARY_METHOD(NSButtonCell, setTitle, 0) @@ -562,6 +565,46 @@ IdentifierInfo *setTitleUISegmentedControl[] = { &Ctx.Idents.get("setTitle"), &Ctx.Idents.get("forSegmentAtIndex")}; ADD_METHOD(UISegmentedControl, setTitleUISegmentedControl, 2, 0) + + NEW_RECEIVER(NSAccessibilityCustomRotorItemResult) + IdentifierInfo + *initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult[] = { + &Ctx.Idents.get("initWithItemLoadingToken"), + &Ctx.Idents.get("customLabel")}; + ADD_METHOD(NSAccessibilityCustomRotorItemResult, + initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult, 2, 1) + ADD_UNARY_METHOD(NSAccessibilityCustomRotorItemResult, setCustomLabel, 0) + + NEW_RECEIVER(UIContextualAction) + IdentifierInfo *contextualActionWithStyleUIContextualAction[] = { + &Ctx.Idents.get("contextualActionWithStyle"), &Ctx.Ident
[PATCH] D34102: [analyzer] Add portability package for the checkers.
NoQ added a comment. In https://reviews.llvm.org/D34102#783161, @zaks.anna wrote: > > eg. checkers for portability across linux/bsd should be off on windows by > > default, checkers for non-portable C++ APIs should be off in plain C code, > > etc > > Is the checker you are moving to portability off and not useful on Windows? It's the same as `MallocChecker`, as i explained above. A relevant code snippet from Driver.cpp: 2130 if (!IsWindowsMSVC) { 2131 CmdArgs.push_back("-analyzer-checker=unix"); 2132 } else { 2133 // Enable "unix" checkers that also work on Windows. 2134 CmdArgs.push_back("-analyzer-checker=unix.API"); 2135 CmdArgs.push_back("-analyzer-checker=unix.Malloc"); 2136 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof"); 2137 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator"); 2138 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg"); 2139 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg"); 2140 } My concern is not about this checker, it's about having to rename this checker if we decide that we need sub-packages for other portability checkers we may add in the future, which is totally realistic. https://reviews.llvm.org/D34102 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34404: [Clang-Tidy] Preserve Message, FileOffset, FilePath in Clang-Tidy YAML output
vladimir.plyashkun updated this revision to Diff 103341. vladimir.plyashkun added a comment. Herald added subscribers: xazax.hun, mgorny. updated CMakeLists.txt Repository: rL LLVM https://reviews.llvm.org/D34404 Files: unittests/Tooling/CMakeLists.txt Index: unittests/Tooling/CMakeLists.txt === --- unittests/Tooling/CMakeLists.txt +++ unittests/Tooling/CMakeLists.txt @@ -13,6 +13,7 @@ add_clang_unittest(ToolingTests CommentHandlerTest.cpp CompilationDatabaseTest.cpp + DiagnosticsYamlTest.cpp FixItTest.cpp LookupTest.cpp QualTypeNamesTest.cpp Index: unittests/Tooling/CMakeLists.txt === --- unittests/Tooling/CMakeLists.txt +++ unittests/Tooling/CMakeLists.txt @@ -13,6 +13,7 @@ add_clang_unittest(ToolingTests CommentHandlerTest.cpp CompilationDatabaseTest.cpp + DiagnosticsYamlTest.cpp FixItTest.cpp LookupTest.cpp QualTypeNamesTest.cpp ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305898 - Fix unused-variable compilation error.
Author: hokein Date: Wed Jun 21 06:26:58 2017 New Revision: 305898 URL: http://llvm.org/viewvc/llvm-project?rev=305898&view=rev Log: Fix unused-variable compilation error. Modified: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp Modified: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp?rev=305898&r1=305897&r2=305898&view=diff == --- cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp (original) +++ cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp Wed Jun 21 06:26:58 2017 @@ -73,12 +73,14 @@ TemporaryFiles::~TemporaryFiles() { void TemporaryFiles::addFile(StringRef File) { llvm::MutexGuard Guard(Mutex); auto IsInserted = Files.insert(File).second; + (void)IsInserted; assert(IsInserted && "File has already been added"); } void TemporaryFiles::removeFile(StringRef File) { llvm::MutexGuard Guard(Mutex); auto WasPresent = Files.erase(File); + (void)WasPresent; assert(WasPresent && "File was not tracked"); llvm::sys::fs::remove(File); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305900 - [analyzer] Bump a few default performance thresholds.
Author: dergachev Date: Wed Jun 21 06:29:35 2017 New Revision: 305900 URL: http://llvm.org/viewvc/llvm-project?rev=305900&view=rev Log: [analyzer] Bump a few default performance thresholds. This makes the analyzer around 10% slower by default, allowing it to find deeper bugs. Default values for the following -analyzer-config change: max-nodes: 15 -> 225000; max-inlinable-size: 50 -> 100. rdar://problem/32539666 Differential Revision: https://reviews.llvm.org/D34277 Modified: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp cfe/trunk/test/Analysis/analyzer-config.c cfe/trunk/test/Analysis/analyzer-config.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp?rev=305900&r1=305899&r2=305900&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp Wed Jun 21 06:29:35 2017 @@ -293,7 +293,7 @@ unsigned AnalyzerOptions::getMaxInlinabl DefaultValue = 4; break; case UMK_Deep: -DefaultValue = 50; +DefaultValue = 100; break; } @@ -332,7 +332,7 @@ unsigned AnalyzerOptions::getMaxNodesPer DefaultValue = 75000; break; case UMK_Deep: -DefaultValue = 15; +DefaultValue = 225000; break; } MaxNodesPerTopLevelFunction = getOptionAsInteger("max-nodes", DefaultValue); Modified: cfe/trunk/test/Analysis/analyzer-config.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/analyzer-config.c?rev=305900&r1=305899&r2=305900&view=diff == --- cfe/trunk/test/Analysis/analyzer-config.c (original) +++ cfe/trunk/test/Analysis/analyzer-config.c Wed Jun 21 06:29:35 2017 @@ -19,8 +19,8 @@ void foo() { // CHECK-NEXT: ipa = dynamic-bifurcate // CHECK-NEXT: ipa-always-inline-size = 3 // CHECK-NEXT: leak-diagnostics-reference-allocation = false -// CHECK-NEXT: max-inlinable-size = 50 -// CHECK-NEXT: max-nodes = 15 +// CHECK-NEXT: max-inlinable-size = 100 +// CHECK-NEXT: max-nodes = 225000 // CHECK-NEXT: max-times-inline-large = 32 // CHECK-NEXT: min-cfg-size-treat-functions-as-large = 14 // CHECK-NEXT: mode = deep Modified: cfe/trunk/test/Analysis/analyzer-config.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/analyzer-config.cpp?rev=305900&r1=305899&r2=305900&view=diff == --- cfe/trunk/test/Analysis/analyzer-config.cpp (original) +++ cfe/trunk/test/Analysis/analyzer-config.cpp Wed Jun 21 06:29:35 2017 @@ -30,8 +30,8 @@ public: // CHECK-NEXT: ipa = dynamic-bifurcate // CHECK-NEXT: ipa-always-inline-size = 3 // CHECK-NEXT: leak-diagnostics-reference-allocation = false -// CHECK-NEXT: max-inlinable-size = 50 -// CHECK-NEXT: max-nodes = 15 +// CHECK-NEXT: max-inlinable-size = 100 +// CHECK-NEXT: max-nodes = 225000 // CHECK-NEXT: max-times-inline-large = 32 // CHECK-NEXT: min-cfg-size-treat-functions-as-large = 14 // CHECK-NEXT: mode = deep ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34277: [analyzer] Bump default performance thresholds?
This revision was automatically updated to reflect the committed changes. Closed by commit rL305900: [analyzer] Bump a few default performance thresholds. (authored by dergachev). Changed prior to commit: https://reviews.llvm.org/D34277?vs=102816&id=103349#toc Repository: rL LLVM https://reviews.llvm.org/D34277 Files: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp cfe/trunk/test/Analysis/analyzer-config.c cfe/trunk/test/Analysis/analyzer-config.cpp Index: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp === --- cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -293,7 +293,7 @@ DefaultValue = 4; break; case UMK_Deep: -DefaultValue = 50; +DefaultValue = 100; break; } @@ -332,7 +332,7 @@ DefaultValue = 75000; break; case UMK_Deep: -DefaultValue = 15; +DefaultValue = 225000; break; } MaxNodesPerTopLevelFunction = getOptionAsInteger("max-nodes", DefaultValue); Index: cfe/trunk/test/Analysis/analyzer-config.cpp === --- cfe/trunk/test/Analysis/analyzer-config.cpp +++ cfe/trunk/test/Analysis/analyzer-config.cpp @@ -30,8 +30,8 @@ // CHECK-NEXT: ipa = dynamic-bifurcate // CHECK-NEXT: ipa-always-inline-size = 3 // CHECK-NEXT: leak-diagnostics-reference-allocation = false -// CHECK-NEXT: max-inlinable-size = 50 -// CHECK-NEXT: max-nodes = 15 +// CHECK-NEXT: max-inlinable-size = 100 +// CHECK-NEXT: max-nodes = 225000 // CHECK-NEXT: max-times-inline-large = 32 // CHECK-NEXT: min-cfg-size-treat-functions-as-large = 14 // CHECK-NEXT: mode = deep Index: cfe/trunk/test/Analysis/analyzer-config.c === --- cfe/trunk/test/Analysis/analyzer-config.c +++ cfe/trunk/test/Analysis/analyzer-config.c @@ -19,8 +19,8 @@ // CHECK-NEXT: ipa = dynamic-bifurcate // CHECK-NEXT: ipa-always-inline-size = 3 // CHECK-NEXT: leak-diagnostics-reference-allocation = false -// CHECK-NEXT: max-inlinable-size = 50 -// CHECK-NEXT: max-nodes = 15 +// CHECK-NEXT: max-inlinable-size = 100 +// CHECK-NEXT: max-nodes = 225000 // CHECK-NEXT: max-times-inline-large = 32 // CHECK-NEXT: min-cfg-size-treat-functions-as-large = 14 // CHECK-NEXT: mode = deep Index: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp === --- cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp +++ cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp @@ -293,7 +293,7 @@ DefaultValue = 4; break; case UMK_Deep: -DefaultValue = 50; +DefaultValue = 100; break; } @@ -332,7 +332,7 @@ DefaultValue = 75000; break; case UMK_Deep: -DefaultValue = 15; +DefaultValue = 225000; break; } MaxNodesPerTopLevelFunction = getOptionAsInteger("max-nodes", DefaultValue); Index: cfe/trunk/test/Analysis/analyzer-config.cpp === --- cfe/trunk/test/Analysis/analyzer-config.cpp +++ cfe/trunk/test/Analysis/analyzer-config.cpp @@ -30,8 +30,8 @@ // CHECK-NEXT: ipa = dynamic-bifurcate // CHECK-NEXT: ipa-always-inline-size = 3 // CHECK-NEXT: leak-diagnostics-reference-allocation = false -// CHECK-NEXT: max-inlinable-size = 50 -// CHECK-NEXT: max-nodes = 15 +// CHECK-NEXT: max-inlinable-size = 100 +// CHECK-NEXT: max-nodes = 225000 // CHECK-NEXT: max-times-inline-large = 32 // CHECK-NEXT: min-cfg-size-treat-functions-as-large = 14 // CHECK-NEXT: mode = deep Index: cfe/trunk/test/Analysis/analyzer-config.c === --- cfe/trunk/test/Analysis/analyzer-config.c +++ cfe/trunk/test/Analysis/analyzer-config.c @@ -19,8 +19,8 @@ // CHECK-NEXT: ipa = dynamic-bifurcate // CHECK-NEXT: ipa-always-inline-size = 3 // CHECK-NEXT: leak-diagnostics-reference-allocation = false -// CHECK-NEXT: max-inlinable-size = 50 -// CHECK-NEXT: max-nodes = 15 +// CHECK-NEXT: max-inlinable-size = 100 +// CHECK-NEXT: max-nodes = 225000 // CHECK-NEXT: max-times-inline-large = 32 // CHECK-NEXT: min-cfg-size-treat-functions-as-large = 14 // CHECK-NEXT: mode = deep ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34275: [analyzer] Re-implemente current virtual calls checker in a path-sensitive way
wangxindsb added a comment. > Oh, I think I see how it works now. How about: > > > struct A; > struct X { > void callFooOfA(A*); > }; > struct A { > A() { > X x; > x.virtualMethod(); // this virtual call is ok > x.callFooOfA(this) > } > virtual foo(); > }; > void X::callFooOfA(A* a) { > a->foo(); // Would be good to warn here. > } > int main() { > A a; > } Yes, you are right, the checker doesn't warn on the //a->foo();//. I will fix this error soon. Thanks, Xin https://reviews.llvm.org/D34275 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34441: [clang-format] Support text proto messages
krasimir updated this revision to Diff 103352. krasimir added a comment. - Remove newline https://reviews.llvm.org/D34441 Files: include/clang/Format/Format.h lib/Format/ContinuationIndenter.cpp lib/Format/Format.cpp lib/Format/TokenAnnotator.cpp lib/Format/UnwrappedLineParser.cpp lib/Format/UnwrappedLineParser.h unittests/Format/CMakeLists.txt unittests/Format/FormatTestTextProto.cpp Index: unittests/Format/FormatTestTextProto.cpp === --- /dev/null +++ unittests/Format/FormatTestTextProto.cpp @@ -0,0 +1,131 @@ +//===- unittest/Format/FormatTestProto.cpp ===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// + +#include "FormatTestUtils.h" +#include "clang/Format/Format.h" +#include "llvm/Support/Debug.h" +#include "gtest/gtest.h" + +#define DEBUG_TYPE "format-test" + +namespace clang { +namespace format { + +class FormatTestTextProto : public ::testing::Test { +protected: + static std::string format(llvm::StringRef Code, unsigned Offset, +unsigned Length, const FormatStyle &Style) { +DEBUG(llvm::errs() << "---\n"); +DEBUG(llvm::errs() << Code << "\n\n"); +std::vector Ranges(1, tooling::Range(Offset, Length)); +tooling::Replacements Replaces = reformat(Style, Code, Ranges); +auto Result = applyAllReplacements(Code, Replaces); +EXPECT_TRUE(static_cast(Result)); +DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); +return *Result; + } + + static std::string format(llvm::StringRef Code) { +FormatStyle Style = getGoogleStyle(FormatStyle::LK_TextProto); +Style.ColumnLimit = 60; // To make writing tests easier. +return format(Code, 0, Code.size(), Style); + } + + static void verifyFormat(llvm::StringRef Code) { +EXPECT_EQ(Code.str(), format(test::messUp(Code))); + } +}; + +TEST_F(FormatTestTextProto, KeepsTopLevelEntriesFittingALine) { + verifyFormat("field_a: OK field_b: OK field_c: OK field_d: OK field_e: OK"); +} + +TEST_F(FormatTestTextProto, SupportsMessageFields) { + verifyFormat("msg_field: {}"); + + verifyFormat("msg_field: {field_a: A}"); + + verifyFormat("msg_field: {field_a: \"OK\" field_b: 123}"); + + verifyFormat("msg_field: {\n" + " field_a: 1\n" + " field_b: OK\n" + " field_c: \"OK\"\n" + " field_d: 123\n" + " field_e: 23\n" + "}"); + + verifyFormat("msg_field{}"); + + verifyFormat("msg_field{field_a: A}"); + + verifyFormat("msg_field{field_a: \"OK\" field_b: 123}"); + + verifyFormat("msg_field{\n" + " field_a: 1\n" + " field_b: OK\n" + " field_c: \"OK\"\n" + " field_d: 123\n" + " field_e: 23.0\n" + " field_f: false\n" + " field_g: 'lala'\n" + " field_h: 1234.567e-89\n" + "}"); + + verifyFormat("msg_field: {msg_field{field_a: 1}}"); + + verifyFormat("id: \"ala.bala\"\n" + "item{type: ITEM_A rank: 1 score: 90.0}\n" + "item{type: ITEM_B rank: 2 score: 70.5}\n" + "item{\n" + " type: ITEM_A\n" + " rank: 3\n" + " score: 20.0\n" + " description: \"the third item has a description\"\n" + "}"); +} + +TEST_F(FormatTestTextProto, AvoidsTopLevelBinPacking) { + verifyFormat("field_a: OK\n" + "field_b: OK\n" + "field_c: OK\n" + "field_d: OK\n" + "field_e: OK\n" + "field_f: OK"); + + verifyFormat("field_a: OK\n" + "field_b: \"OK\"\n" + "field_c: \"OK\"\n" + "msg_field: {field_d: 123}\n" + "field_e: OK\n" + "field_f: OK"); + + verifyFormat("field_a: OK\n" + "field_b: \"OK\"\n" + "field_c: \"OK\"\n" + "msg_field: {field_d: 123 field_e: OK}"); +} + +TEST_F(FormatTestTextProto, AddsNewlinesAfterTrailingComments) { + verifyFormat("field_a: OK // Comment\n" + "field_b: 1"); + + verifyFormat("field_a: OK\n" + "msg_field: {\n" + " field_b: OK // Comment\n" + "}"); + + verifyFormat("field_a: OK\n" + "msg_field{\n" + " field_b: OK // Comment\n" + "}"); +} + +} // end namespace tooling +} // end namespace clang Index: unittests/Format/CMakeLists.txt === --- unittests/Format/CMakeLists.txt +++ unittests/Format/CMakeLists.txt @@ -11,6 +11,7 @@ FormatTestObjC.cpp FormatTestProto.cpp FormatTestSelective.cpp + FormatTe
[PATCH] D34441: [clang-format] Support text proto messages
krasimir added a comment. Tests for `<>`-style message fields are missing because I discovered that they don't really work in a multiline setting in proto options anyways. I'll address this problem separately. https://reviews.llvm.org/D34441 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34404: [Clang-Tidy] Preserve Message, FileOffset, FilePath in Clang-Tidy YAML output
vladimir.plyashkun updated this revision to Diff 103353. vladimir.plyashkun added a comment. correct revision with all changes Repository: rL LLVM https://reviews.llvm.org/D34404 Files: include/clang/Tooling/DiagnosticsYaml.h unittests/Tooling/CMakeLists.txt unittests/Tooling/DiagnosticsYamlTest.cpp Index: unittests/Tooling/DiagnosticsYamlTest.cpp === --- /dev/null +++ unittests/Tooling/DiagnosticsYamlTest.cpp @@ -0,0 +1,170 @@ +//===- unittests/Tooling/DiagnosticsYamlTest.cpp - Serialization tests ---===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// +// +// Tests for serialization of Diagnostics. +// +//===--===// + +#include "clang/Tooling/Core/Diagnostic.h" +#include "clang/Tooling/DiagnosticsYaml.h" +#include "clang/Tooling/ReplacementsYaml.h" +#include "gtest/gtest.h" + +using namespace llvm; +using namespace clang::tooling; + +TEST(DiagnosticsYamlTest, SerializesDiagnostics) { + TranslationUnitDiagnostics TUD; + TUD.MainSourceFile = "path/to/source.cpp"; + DiagnosticMessage Message1; + Message1.Message = "message #1"; + Message1.FileOffset = 55; + Message1.FilePath = "path/to/source.cpp"; + StringMap Fix1{ + {"path/to/source.cpp", Replacements(Replacement("path/to/source.cpp", 100, + 12, "replacement #1"))}}; + DiagnosticMessage Message2; + Message2.Message = "message #2"; + Message2.FileOffset = 60; + Message2.FilePath = "path/to/header.h"; + StringMap Fix2{ + {"path/to/header.h", + Replacements(Replacement("path/to/header.h", 62, 2, "replacement #2"))}}; + SmallVector EmptyNotes; + TUD.Diagnostics.emplace_back("diagnostic#1", Message1, Fix1, EmptyNotes, + Diagnostic::Warning, "path/to/build/directory"); + TUD.Diagnostics.emplace_back("diagnostic#2", Message2, Fix2, EmptyNotes, + Diagnostic::Error, + "path/to/another/build/directory"); + + std::string YamlContent; + raw_string_ostream YamlContentStream(YamlContent); + + yaml::Output YAML(YamlContentStream); + YAML << TUD; + + ASSERT_STREQ("---\n" + "MainSourceFile: path/to/source.cpp\n" + "Diagnostics: \n" + " - DiagnosticName: \"diagnostic#1\"\n" + "Message: \"message #1\"\n" + "FileOffset: 55\n" + "FilePath:path/to/source.cpp\n" + "Replacements:\n" + " - FilePath:path/to/source.cpp\n" + "Offset: 100\n" + "Length: 12\n" + "ReplacementText: \"replacement #1\"\n" + " - DiagnosticName: \"diagnostic#2\"\n" + "Message: \"message #2\"\n" + "FileOffset: 60\n" + "FilePath:path/to/header.h\n" + "Replacements:\n" + " - FilePath:path/to/header.h\n" + "Offset: 62\n" + "Length: 2\n" + "ReplacementText: \"replacement #2\"\n" + "...\n", + YamlContentStream.str().c_str()); +} + +TEST(DiagnosticsYamlTest, SerializesDiagnosticWithNoFix) { + TranslationUnitDiagnostics TUD; + TUD.MainSourceFile = "path/to/source.cpp"; + DiagnosticMessage Message; + Message.Message = "message #1"; + Message.FileOffset = 55; + Message.FilePath = "path/to/source.cpp"; + StringMap EmptyReplacements; + SmallVector EmptyNotes; + TUD.Diagnostics.emplace_back("diagnostic#1", Message, EmptyReplacements, + EmptyNotes, Diagnostic::Warning, + "path/to/build/directory"); + + std::string YamlContent; + raw_string_ostream YamlContentStream(YamlContent); + + yaml::Output YAML(YamlContentStream); + YAML << TUD; + + ASSERT_STREQ("---\n" + "MainSourceFile: path/to/source.cpp\n" + "Diagnostics: \n" + " - DiagnosticName: \"diagnostic#1\"\n" + "Message: \"message #1\"\n" + "FileOffset: 55\n" + "FilePath:path/to/source.cpp\n" + "...\n", + YamlContentStream.str().c_str()); +} + +TEST(DiagnosticsYamlTest, DeserializesDiagnostics) { + std::string YamlContent = "---\n" +"MainSourceFile: path/to/source.cpp\n" +"Diagnostics: \n" +" - DiagnosticName: 'diagnostic#1'\
[PATCH] D34399: clang-format: introduce InlineOnly short function style
Typz marked 3 inline comments as done. Typz added inline comments. Comment at: include/clang/Format/Format.h:234 + bool allowEmptyFunctionsOnASingleLine() const { + return AllowShortFunctionsOnASingleLine >= ShortFunctionStyle::SFS_Empty; djasper wrote: > I'd prefer these functions not to be in the public header file. They are > implementation details. Either find a header/cpp-file in the lib/ directory > to place them in or just remove them for now. They are both still quite small > and called only twice each. This is similar to the isCpp() method, to provide a better abstraction in the implementation. I cannot find any better place, so I will remove them. https://reviews.llvm.org/D34399 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34399: clang-format: introduce InlineOnly short function style
Typz updated this revision to Diff 103357. Typz marked an inline comment as done. Typz added a comment. Fix according to review comments https://reviews.llvm.org/D34399 Files: include/clang/Format/Format.h lib/Format/Format.cpp lib/Format/TokenAnnotator.cpp lib/Format/UnwrappedLineFormatter.cpp unittests/Format/FormatTest.cpp Index: unittests/Format/FormatTest.cpp === --- unittests/Format/FormatTest.cpp +++ unittests/Format/FormatTest.cpp @@ -6509,6 +6509,52 @@ MergeInlineOnly); } +TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { + FormatStyle MergeInlineOnly = getLLVMStyle(); + MergeInlineOnly.AllowShortFunctionsOnASingleLine = + FormatStyle::SFS_InlineOnly; + verifyFormat("class C {\n" + " int f() { return 42; }\n" + "};", + MergeInlineOnly); + verifyFormat("int f() {\n" + " return 42;\n" + "}", + MergeInlineOnly); + + // SFS_InlineOnly does not imply SFS_Empty + verifyFormat("class C {\n" + " int f() {}\n" + "};", + MergeInlineOnly); + verifyFormat("int f() {\n" + "}", + MergeInlineOnly); + + // Also verify behavior when BraceWrapping.AfterFunction = true + MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; + MergeInlineOnly.BraceWrapping.AfterFunction = true; + verifyFormat("class C {\n" + " int f() { return 42; }\n" + "};", + MergeInlineOnly); + verifyFormat("int f()\n" + "{\n" + " return 42;\n" + "}", + MergeInlineOnly); + + // SFS_InlineOnly does not imply SFS_Empty + verifyFormat("int f()\n" + "{\n" + "}", + MergeInlineOnly); + verifyFormat("class C {\n" + " int f() {}\n" + "};", + MergeInlineOnly); +} + TEST_F(FormatTest, SplitEmptyFunctionBody) { FormatStyle Style = getLLVMStyle(); Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; Index: lib/Format/UnwrappedLineFormatter.cpp === --- lib/Format/UnwrappedLineFormatter.cpp +++ lib/Format/UnwrappedLineFormatter.cpp @@ -226,7 +226,7 @@ Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All || (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && I[1]->First->is(tok::r_brace)) || -(Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline && +(Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly && TheLine->Level != 0); if (Style.CompactNamespaces) { Index: lib/Format/TokenAnnotator.cpp === --- lib/Format/TokenAnnotator.cpp +++ lib/Format/TokenAnnotator.cpp @@ -2480,8 +2480,8 @@ return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || (Left.NestingLevel == 0 && Line.Level == 0 && - Style.AllowShortFunctionsOnASingleLine == - FormatStyle::SFS_Inline); + Style.AllowShortFunctionsOnASingleLine & + FormatStyle::SFS_InlineOnly); } else if (Style.Language == FormatStyle::LK_Java) { if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && Right.Next->is(tok::string_literal)) Index: lib/Format/Format.cpp === --- lib/Format/Format.cpp +++ lib/Format/Format.cpp @@ -96,6 +96,7 @@ IO.enumCase(Value, "All", FormatStyle::SFS_All); IO.enumCase(Value, "true", FormatStyle::SFS_All); IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline); +IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly); IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty); } }; Index: include/clang/Format/Format.h === --- include/clang/Format/Format.h +++ include/clang/Format/Format.h @@ -184,9 +184,23 @@ enum ShortFunctionStyle { /// \brief Never merge functions into a single line. SFS_None, +/// \brief Only merge functions defined inside a class. Same as "inline", +/// except it does not implies "empty": i.e. top level empty functions +/// are not merged either. +/// \code +/// class Foo { +/// void f() { foo(); } +/// }; +/// void f() { +/// foo(); +/// } +/// void f() { +/// } +/// \endcode +SFS_InlineOnly, /// \brief Only merge empty functions. /// \code -/// void f() { bar(); } +/// void f() {} /// void f2() { /// bar2(); /// } @@ -197,6 +211,10 @@ ///
r305901 - [clang-format] Support sorting using declarations
Author: krasimir Date: Wed Jun 21 07:03:12 2017 New Revision: 305901 URL: http://llvm.org/viewvc/llvm-project?rev=305901&view=rev Log: [clang-format] Support sorting using declarations Summary: This patch adds UsingDeclarationsSorter, a TokenAnalyzer that sorts consecutive using declarations. Reviewers: klimek Reviewed By: klimek Subscribers: Typz, djasper, cfe-commits, klimek, mgorny Differential Revision: https://reviews.llvm.org/D33823 Added: cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp cfe/trunk/lib/Format/UsingDeclarationsSorter.h cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp Modified: cfe/trunk/include/clang/Format/Format.h cfe/trunk/lib/Format/CMakeLists.txt cfe/trunk/lib/Format/Format.cpp cfe/trunk/unittests/Format/CMakeLists.txt Modified: cfe/trunk/include/clang/Format/Format.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=305901&r1=305900&r2=305901&view=diff == --- cfe/trunk/include/clang/Format/Format.h (original) +++ cfe/trunk/include/clang/Format/Format.h Wed Jun 21 07:03:12 2017 @@ -1641,6 +1641,16 @@ tooling::Replacements fixNamespaceEndCom ArrayRef Ranges, StringRef FileName = ""); +/// \brief Sort consecutive using declarations in the given \p Ranges in +/// \p Code. +/// +/// Returns the ``Replacements`` that sort the using declarations in all +/// \p Ranges in \p Code. +tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, +StringRef Code, +ArrayRef Ranges, +StringRef FileName = ""); + /// \brief Returns the ``LangOpts`` that the formatter expects you to set. /// /// \param Style determines specific settings for lexing mode. Modified: cfe/trunk/lib/Format/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/CMakeLists.txt?rev=305901&r1=305900&r2=305901&view=diff == --- cfe/trunk/lib/Format/CMakeLists.txt (original) +++ cfe/trunk/lib/Format/CMakeLists.txt Wed Jun 21 07:03:12 2017 @@ -13,6 +13,7 @@ add_clang_library(clangFormat TokenAnnotator.cpp UnwrappedLineFormatter.cpp UnwrappedLineParser.cpp + UsingDeclarationsSorter.cpp WhitespaceManager.cpp LINK_LIBS Modified: cfe/trunk/lib/Format/Format.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=305901&r1=305900&r2=305901&view=diff == --- cfe/trunk/lib/Format/Format.cpp (original) +++ cfe/trunk/lib/Format/Format.cpp Wed Jun 21 07:03:12 2017 @@ -23,6 +23,7 @@ #include "TokenAnnotator.h" #include "UnwrappedLineFormatter.h" #include "UnwrappedLineParser.h" +#include "UsingDeclarationsSorter.h" #include "WhitespaceManager.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" @@ -1943,6 +1944,16 @@ tooling::Replacements fixNamespaceEndCom return Fix.process(); } +tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, +StringRef Code, +ArrayRef Ranges, +StringRef FileName) { + std::unique_ptr Env = + Environment::CreateVirtualEnvironment(Code, FileName, Ranges); + UsingDeclarationsSorter Sorter(*Env, Style); + return Sorter.process(); +} + LangOptions getFormattingLangOpts(const FormatStyle &Style) { LangOptions LangOpts; LangOpts.CPlusPlus = 1; Added: cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp?rev=305901&view=auto == --- cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp (added) +++ cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp Wed Jun 21 07:03:12 2017 @@ -0,0 +1,144 @@ +//===--- UsingDeclarationsSorter.cpp *- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// +/// +/// \file +/// \brief This file implements UsingDeclarationsSorter, a TokenAnalyzer that +/// sorts consecutive using declarations. +/// +//===--===// + +#include "UsingDeclarationsSorter.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/Regex.h" + +#include + +#define DEBUG_TYPE "using-declarations-sorter" + +namespace clang { +namespace format { + +n
[PATCH] D33823: [clang-format] Support sorting using declarations
This revision was automatically updated to reflect the committed changes. Closed by commit rL305901: [clang-format] Support sorting using declarations (authored by krasimir). Changed prior to commit: https://reviews.llvm.org/D33823?vs=103032&id=103359#toc Repository: rL LLVM https://reviews.llvm.org/D33823 Files: cfe/trunk/include/clang/Format/Format.h cfe/trunk/lib/Format/CMakeLists.txt cfe/trunk/lib/Format/Format.cpp cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp cfe/trunk/lib/Format/UsingDeclarationsSorter.h cfe/trunk/unittests/Format/CMakeLists.txt cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp Index: cfe/trunk/include/clang/Format/Format.h === --- cfe/trunk/include/clang/Format/Format.h +++ cfe/trunk/include/clang/Format/Format.h @@ -1641,6 +1641,16 @@ ArrayRef Ranges, StringRef FileName = ""); +/// \brief Sort consecutive using declarations in the given \p Ranges in +/// \p Code. +/// +/// Returns the ``Replacements`` that sort the using declarations in all +/// \p Ranges in \p Code. +tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, +StringRef Code, +ArrayRef Ranges, +StringRef FileName = ""); + /// \brief Returns the ``LangOpts`` that the formatter expects you to set. /// /// \param Style determines specific settings for lexing mode. Index: cfe/trunk/lib/Format/CMakeLists.txt === --- cfe/trunk/lib/Format/CMakeLists.txt +++ cfe/trunk/lib/Format/CMakeLists.txt @@ -13,6 +13,7 @@ TokenAnnotator.cpp UnwrappedLineFormatter.cpp UnwrappedLineParser.cpp + UsingDeclarationsSorter.cpp WhitespaceManager.cpp LINK_LIBS Index: cfe/trunk/lib/Format/Format.cpp === --- cfe/trunk/lib/Format/Format.cpp +++ cfe/trunk/lib/Format/Format.cpp @@ -23,6 +23,7 @@ #include "TokenAnnotator.h" #include "UnwrappedLineFormatter.h" #include "UnwrappedLineParser.h" +#include "UsingDeclarationsSorter.h" #include "WhitespaceManager.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" @@ -1943,6 +1944,16 @@ return Fix.process(); } +tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, +StringRef Code, +ArrayRef Ranges, +StringRef FileName) { + std::unique_ptr Env = + Environment::CreateVirtualEnvironment(Code, FileName, Ranges); + UsingDeclarationsSorter Sorter(*Env, Style); + return Sorter.process(); +} + LangOptions getFormattingLangOpts(const FormatStyle &Style) { LangOptions LangOpts; LangOpts.CPlusPlus = 1; Index: cfe/trunk/lib/Format/UsingDeclarationsSorter.h === --- cfe/trunk/lib/Format/UsingDeclarationsSorter.h +++ cfe/trunk/lib/Format/UsingDeclarationsSorter.h @@ -0,0 +1,37 @@ +//===--- UsingDeclarationsSorter.h --*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// +/// +/// \file +/// \brief This file declares UsingDeclarationsSorter, a TokenAnalyzer that +/// sorts consecutive using declarations. +/// +//===--===// + +#ifndef LLVM_CLANG_LIB_FORMAT_USINGDECLARATIONSSORTER_H +#define LLVM_CLANG_LIB_FORMAT_USINGDECLARATIONSSORTER_H + +#include "TokenAnalyzer.h" + +namespace clang { +namespace format { + +class UsingDeclarationsSorter : public TokenAnalyzer { +public: + UsingDeclarationsSorter(const Environment &Env, const FormatStyle &Style); + + tooling::Replacements + analyze(TokenAnnotator &Annotator, + SmallVectorImpl &AnnotatedLines, + FormatTokenLexer &Tokens) override; +}; + +} // end namespace format +} // end namespace clang + +#endif Index: cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp === --- cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp +++ cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp @@ -0,0 +1,144 @@ +//===--- UsingDeclarationsSorter.cpp *- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// +///
[PATCH] D34399: clang-format: introduce InlineOnly short function style
djasper accepted this revision. djasper added a comment. This revision is now accepted and ready to land. Looks good. https://reviews.llvm.org/D34399 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34444: Teach codegen to work in incremental processing mode.
v.g.vassilev created this revision. When `isIncrementalProcessingEnabled` is on we might call multiple times `HandleEndOfTranslationUnit`. This would complete the `llvm::Module` CodeGen is writing to. This patch allows the clients to start a new `llvm::Module`, allowing CodeGen to continue writing. This should give the necessary facilities to write a unittest for https://reviews.llvm.org/D34059. Repository: rL LLVM https://reviews.llvm.org/D3 Files: include/clang/CodeGen/ModuleBuilder.h lib/CodeGen/ModuleBuilder.cpp Index: lib/CodeGen/ModuleBuilder.cpp === --- lib/CodeGen/ModuleBuilder.cpp +++ lib/CodeGen/ModuleBuilder.cpp @@ -119,6 +119,14 @@ return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition)); } +llvm::Module *StartModule(llvm::StringRef ModuleName, llvm::LLVMContext& C, + const CodeGenOptions& CGO) { + assert(!M && "Replacing existing Module?"); + M.reset(new llvm::Module(ModuleName, C)); + Initialize(*Ctx); + return M.get(); +} + void Initialize(ASTContext &Context) override { Ctx = &Context; @@ -317,6 +325,11 @@ ->GetAddrOfGlobal(global, isForDefinition); } +llvm::Module *CodeGenerator::StartModule(const std::string& ModuleName, + llvm::LLVMContext& C) { + return static_cast(this)->StartModule(ModuleName, C); +} + CodeGenerator *clang::CreateLLVMCodeGen( DiagnosticsEngine &Diags, llvm::StringRef ModuleName, const HeaderSearchOptions &HeaderSearchOpts, Index: include/clang/CodeGen/ModuleBuilder.h === --- include/clang/CodeGen/ModuleBuilder.h +++ include/clang/CodeGen/ModuleBuilder.h @@ -84,6 +84,11 @@ /// code generator will schedule the entity for emission if a /// definition has been registered with this code generator. llvm::Constant *GetAddrOfGlobal(GlobalDecl decl, bool isForDefinition); + + /// Create a new \c llvm::Module after calling HandleTranslationUnit. This + /// enable codegen in interactive processing environments. + llvm::Module* StartModule(llvm::StringRef ModuleName, llvm::LLVMContext& C, +const CodeGenOptions& CGO); }; /// CreateLLVMCodeGen - Create a CodeGenerator instance. Index: lib/CodeGen/ModuleBuilder.cpp === --- lib/CodeGen/ModuleBuilder.cpp +++ lib/CodeGen/ModuleBuilder.cpp @@ -119,6 +119,14 @@ return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition)); } +llvm::Module *StartModule(llvm::StringRef ModuleName, llvm::LLVMContext& C, + const CodeGenOptions& CGO) { + assert(!M && "Replacing existing Module?"); + M.reset(new llvm::Module(ModuleName, C)); + Initialize(*Ctx); + return M.get(); +} + void Initialize(ASTContext &Context) override { Ctx = &Context; @@ -317,6 +325,11 @@ ->GetAddrOfGlobal(global, isForDefinition); } +llvm::Module *CodeGenerator::StartModule(const std::string& ModuleName, + llvm::LLVMContext& C) { + return static_cast(this)->StartModule(ModuleName, C); +} + CodeGenerator *clang::CreateLLVMCodeGen( DiagnosticsEngine &Diags, llvm::StringRef ModuleName, const HeaderSearchOptions &HeaderSearchOpts, Index: include/clang/CodeGen/ModuleBuilder.h === --- include/clang/CodeGen/ModuleBuilder.h +++ include/clang/CodeGen/ModuleBuilder.h @@ -84,6 +84,11 @@ /// code generator will schedule the entity for emission if a /// definition has been registered with this code generator. llvm::Constant *GetAddrOfGlobal(GlobalDecl decl, bool isForDefinition); + + /// Create a new \c llvm::Module after calling HandleTranslationUnit. This + /// enable codegen in interactive processing environments. + llvm::Module* StartModule(llvm::StringRef ModuleName, llvm::LLVMContext& C, +const CodeGenOptions& CGO); }; /// CreateLLVMCodeGen - Create a CodeGenerator instance. ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34444: Teach codegen to work in incremental processing mode.
v.g.vassilev updated this revision to Diff 103360. v.g.vassilev added a comment. Fix compilation issue. https://reviews.llvm.org/D3 Files: include/clang/CodeGen/ModuleBuilder.h lib/CodeGen/ModuleBuilder.cpp Index: lib/CodeGen/ModuleBuilder.cpp === --- lib/CodeGen/ModuleBuilder.cpp +++ lib/CodeGen/ModuleBuilder.cpp @@ -119,6 +119,14 @@ return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition)); } +llvm::Module *StartModule(llvm::StringRef ModuleName, llvm::LLVMContext& C, + const CodeGenOptions& CGO) { + assert(!M && "Replacing existing Module?"); + M.reset(new llvm::Module(ModuleName, C)); + Initialize(*Ctx); + return M.get(); +} + void Initialize(ASTContext &Context) override { Ctx = &Context; @@ -317,6 +325,12 @@ ->GetAddrOfGlobal(global, isForDefinition); } +llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName, + llvm::LLVMContext &C, + const CodeGenOptions &CGO) { + return static_cast(this)->StartModule(ModuleName, C, CGO); +} + CodeGenerator *clang::CreateLLVMCodeGen( DiagnosticsEngine &Diags, llvm::StringRef ModuleName, const HeaderSearchOptions &HeaderSearchOpts, Index: include/clang/CodeGen/ModuleBuilder.h === --- include/clang/CodeGen/ModuleBuilder.h +++ include/clang/CodeGen/ModuleBuilder.h @@ -84,6 +84,11 @@ /// code generator will schedule the entity for emission if a /// definition has been registered with this code generator. llvm::Constant *GetAddrOfGlobal(GlobalDecl decl, bool isForDefinition); + + /// Create a new \c llvm::Module after calling HandleTranslationUnit. This + /// enable codegen in interactive processing environments. + llvm::Module* StartModule(llvm::StringRef ModuleName, llvm::LLVMContext &C, +const CodeGenOptions &CGO); }; /// CreateLLVMCodeGen - Create a CodeGenerator instance. Index: lib/CodeGen/ModuleBuilder.cpp === --- lib/CodeGen/ModuleBuilder.cpp +++ lib/CodeGen/ModuleBuilder.cpp @@ -119,6 +119,14 @@ return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition)); } +llvm::Module *StartModule(llvm::StringRef ModuleName, llvm::LLVMContext& C, + const CodeGenOptions& CGO) { + assert(!M && "Replacing existing Module?"); + M.reset(new llvm::Module(ModuleName, C)); + Initialize(*Ctx); + return M.get(); +} + void Initialize(ASTContext &Context) override { Ctx = &Context; @@ -317,6 +325,12 @@ ->GetAddrOfGlobal(global, isForDefinition); } +llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName, + llvm::LLVMContext &C, + const CodeGenOptions &CGO) { + return static_cast(this)->StartModule(ModuleName, C, CGO); +} + CodeGenerator *clang::CreateLLVMCodeGen( DiagnosticsEngine &Diags, llvm::StringRef ModuleName, const HeaderSearchOptions &HeaderSearchOpts, Index: include/clang/CodeGen/ModuleBuilder.h === --- include/clang/CodeGen/ModuleBuilder.h +++ include/clang/CodeGen/ModuleBuilder.h @@ -84,6 +84,11 @@ /// code generator will schedule the entity for emission if a /// definition has been registered with this code generator. llvm::Constant *GetAddrOfGlobal(GlobalDecl decl, bool isForDefinition); + + /// Create a new \c llvm::Module after calling HandleTranslationUnit. This + /// enable codegen in interactive processing environments. + llvm::Module* StartModule(llvm::StringRef ModuleName, llvm::LLVMContext &C, +const CodeGenOptions &CGO); }; /// CreateLLVMCodeGen - Create a CodeGenerator instance. ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305902 - Fixed compiler warnings after r305890.
Author: ibiryukov Date: Wed Jun 21 07:34:27 2017 New Revision: 305902 URL: http://llvm.org/viewvc/llvm-project?rev=305902&view=rev Log: Fixed compiler warnings after r305890. Should fix buildbots that pass -Werror. Modified: cfe/trunk/lib/Frontend/ASTUnit.cpp Modified: cfe/trunk/lib/Frontend/ASTUnit.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/ASTUnit.cpp?rev=305902&r1=305901&r2=305902&view=diff == --- cfe/trunk/lib/Frontend/ASTUnit.cpp (original) +++ cfe/trunk/lib/Frontend/ASTUnit.cpp Wed Jun 21 07:34:27 2017 @@ -924,9 +924,6 @@ public: class ASTUnitPreambleCallbacks : public PreambleCallbacks { public: - ASTUnitPreambleCallbacks(llvm::SmallVectorImpl &StoredDiags) - : StoredDiags(StoredDiags) {} - unsigned getHash() const { return Hash; } std::vector takeTopLevelDecls() { return std::move(TopLevelDecls); } @@ -964,7 +961,6 @@ public: } private: - llvm::SmallVectorImpl &StoredDiags; unsigned Hash = 0; std::vector TopLevelDecls; std::vector TopLevelDeclIDs; @@ -1259,7 +1255,7 @@ ASTUnit::getMainBufferWithPrecompiledPre SmallVector NewPreambleDiagsStandalone; SmallVector NewPreambleDiags; - ASTUnitPreambleCallbacks Callbacks(NewPreambleDiags); + ASTUnitPreambleCallbacks Callbacks; { llvm::Optional Capture; if (CaptureDiagnostics) @@ -1282,18 +1278,16 @@ ASTUnit::getMainBufferWithPrecompiledPre case BuildPreambleError::PreambleIsEmpty: // Try again next time. PreambleRebuildCounter = 1; -break; +return nullptr; case BuildPreambleError::CouldntCreateTargetInfo: case BuildPreambleError::BeginSourceFileFailed: case BuildPreambleError::CouldntEmitPCH: case BuildPreambleError::CouldntCreateVFSOverlay: // These erros are more likely to repeat, retry after some period. PreambleRebuildCounter = DefaultPreambleRebuildInterval; -break; - default: -llvm_unreachable("unexpected BuildPreambleError"); +return nullptr; } - return nullptr; + llvm_unreachable("unexpected BuildPreambleError"); } } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305903 - Function with unparsed body is a definition
Author: sepavloff Date: Wed Jun 21 07:46:57 2017 New Revision: 305903 URL: http://llvm.org/viewvc/llvm-project?rev=305903&view=rev Log: Function with unparsed body is a definition While a function body is being parsed, the function declaration is not considered as a definition because it does not have a body yet. In some cases it leads to incorrect interpretation, the case is presented in https://bugs.llvm.org/show_bug.cgi?id=14785: ``` template struct Somewhat { void internal() const {} friend void operator+(int const &, Somewhat const &) {} }; void operator+(int const &, Somewhat const &x) { x.internal(); } ``` When statement `x.internal()` in the body of global `operator+` is parsed, the type of `x` must be completed, so the instantiation of `Somewhat` is started. It instantiates the declaration of `operator+` defined inline, and makes a check for redefinition. The check does not detect another definition because the declaration of `operator+` is still not defining as does not have a body yet. To solves this problem the function `isThisDeclarationADefinition` considers a function declaration as a definition if it has flag `WillHaveBody` set. This change fixes PR14785. Differential Revision: https://reviews.llvm.org/D30375 This is a recommit of 305379, reverted in 305381, with small changes. Modified: cfe/trunk/include/clang/AST/Decl.h cfe/trunk/lib/Sema/SemaCUDA.cpp cfe/trunk/lib/Sema/SemaDecl.cpp cfe/trunk/lib/Sema/SemaDeclCXX.cpp cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp cfe/trunk/test/SemaCXX/friend2.cpp Modified: cfe/trunk/include/clang/AST/Decl.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=305903&r1=305902&r2=305903&view=diff == --- cfe/trunk/include/clang/AST/Decl.h (original) +++ cfe/trunk/include/clang/AST/Decl.h Wed Jun 21 07:46:57 2017 @@ -1874,7 +1874,7 @@ public: /// bool isThisDeclarationADefinition() const { return IsDeleted || IsDefaulted || Body || IsLateTemplateParsed || - hasDefiningAttr(); + WillHaveBody || hasDefiningAttr(); } /// doesThisDeclarationHaveABody - Returns whether this specific Modified: cfe/trunk/lib/Sema/SemaCUDA.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCUDA.cpp?rev=305903&r1=305902&r2=305903&view=diff == --- cfe/trunk/lib/Sema/SemaCUDA.cpp (original) +++ cfe/trunk/lib/Sema/SemaCUDA.cpp Wed Jun 21 07:46:57 2017 @@ -629,12 +629,6 @@ static bool IsKnownEmitted(Sema &S, Func // emitted, because (say) the definition could include "inline". FunctionDecl *Def = FD->getDefinition(); - // We may currently be parsing the body of FD, in which case - // FD->getDefinition() will be null, but we still want to treat FD as though - // it's a definition. - if (!Def && FD->willHaveBody()) -Def = FD; - if (Def && !isDiscardableGVALinkage(S.getASTContext().GetGVALinkageForFunction(Def))) return true; Modified: cfe/trunk/lib/Sema/SemaDecl.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=305903&r1=305902&r2=305903&view=diff == --- cfe/trunk/lib/Sema/SemaDecl.cpp (original) +++ cfe/trunk/lib/Sema/SemaDecl.cpp Wed Jun 21 07:46:57 2017 @@ -12232,6 +12232,7 @@ Decl *Sema::ActOnFinishFunctionBody(Decl if (FD) { FD->setBody(Body); +FD->setWillHaveBody(false); if (getLangOpts().CPlusPlus14) { if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && Modified: cfe/trunk/lib/Sema/SemaDeclCXX.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclCXX.cpp?rev=305903&r1=305902&r2=305903&view=diff == --- cfe/trunk/lib/Sema/SemaDeclCXX.cpp (original) +++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp Wed Jun 21 07:46:57 2017 @@ -13878,6 +13878,9 @@ void Sema::SetDeclDeleted(Decl *Dcl, Sou return; } + // Deleted function does not have a body. + Fn->setWillHaveBody(false); + if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { // Don't consider the implicit declaration we generate for explicit // specializations. FIXME: Do not generate these implicit declarations. Modified: cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp?rev=305903&r1=305902&r2=305903&view=diff == --- cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp (original) +++ cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp Wed Jun 21 07:46:57 2017 @@ -1782,6 +1782,9 @@ Decl *TemplateDeclInstantiator::VisitFun Previous.clear(); } + if (isFriend) +Function->setObjectOfFri
[PATCH] D30375: Function with unparsed body is a definition
sepavloff added a comment. Initial commit (r305379) was reverted (r305381) because it broke self builds. The reason was not related to the WillHaveBody flag but was due to the change: if (isFriend) { Function->setObjectOfFriendDecl(); if (FunctionTemplate) FunctionTemplate->setObjectOfFriendDecl(); } Attempt to execute `FunctionTemplate->setObjectOfFriendDecl()` caused assertion violation because the declaration had `IDNS_NonMemberOperator` in its IdentifierNamespace. There is nothing wrong with this flag, `setObjectOfFriendDecl` must be updated accordingly. This is however a problem of friend function templates, it will be addressed in other patch. For now the call to `setObjectOfFriendDecl` is made as previously, with the exception that it is called for `Function` prior to call to `CheckFunctionDeclaration`, as it is necessary for proper diagnostics. Repository: rL LLVM https://reviews.llvm.org/D30375 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305911 - [index] Nested class declarations should be annotated with the
Author: arphaman Date: Wed Jun 21 08:51:04 2017 New Revision: 305911 URL: http://llvm.org/viewvc/llvm-project?rev=305911&view=rev Log: [index] Nested class declarations should be annotated with the "specializationOf" relation if they pseudo-override a type in the base template This commit fixes an issue where Xcode's renaming engine couldn't find the reference to the second occurrence of "InnerClass" in this example: template struct Ts { template struct InnerClass { }; }; template<> struct Ts { template struct InnerClass; // This occurrence wasn't renamed }; rdar://31884960 Differential Revision: https://reviews.llvm.org/D34392 Modified: cfe/trunk/lib/Index/IndexDecl.cpp cfe/trunk/test/Index/Core/index-source.cpp Modified: cfe/trunk/lib/Index/IndexDecl.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Index/IndexDecl.cpp?rev=305911&r1=305910&r2=305911&view=diff == --- cfe/trunk/lib/Index/IndexDecl.cpp (original) +++ cfe/trunk/lib/Index/IndexDecl.cpp Wed Jun 21 08:51:04 2017 @@ -351,9 +351,11 @@ public: IndexCtx.indexTagDecl(D, Relations); } else { auto *Parent = dyn_cast(D->getDeclContext()); +SmallVector Relations; +gatherTemplatePseudoOverrides(D, Relations); return IndexCtx.handleReference(D, D->getLocation(), Parent, D->getLexicalDeclContext(), -SymbolRoleSet()); +SymbolRoleSet(), Relations); } } return true; Modified: cfe/trunk/test/Index/Core/index-source.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/Core/index-source.cpp?rev=305911&r1=305910&r2=305911&view=diff == --- cfe/trunk/test/Index/Core/index-source.cpp (original) +++ cfe/trunk/test/Index/Core/index-source.cpp Wed Jun 21 08:51:04 2017 @@ -134,6 +134,9 @@ class PseudoOverridesInSpecializations { template struct InnerTemplate { }; template struct InnerTemplate { }; + + template + class InnerClass { }; }; template<> @@ -195,8 +198,22 @@ class PseudoOverridesInSpecializations2#T#T@PseudoOverridesInSpecializations@ST>1#T@InnerTemplate template struct InnerTemplate { }; + + template + class InnerClass; +// CHECK: [[@LINE-1]]:9 | class(Gen)/C++ | InnerClass | c:@S@PseudoOverridesInSpecializations>#d#I@ST>1#T@InnerClass | | Ref,RelCont,RelSpecialization | rel: 2 +// CHECK-NEXT: RelCont +// CHECK-NEXT: RelSpecialization | InnerClass | c:@ST>2#T#T@PseudoOverridesInSpecializations@ST>1#T@InnerClass }; +template +class PseudoOverridesInSpecializations::InnerClass { +}; +// CHECK: [[@LINE-2]]:54 | class(Gen)/C++ | InnerClass | c:@S@PseudoOverridesInSpecializations>#d#I@ST>1#T@InnerClass | | Def,RelChild | rel: 1 +// CHECK-NEXT: RelChild +// CHECK: [[@LINE-4]]:7 | class(Gen)/C++ | PseudoOverridesInSpecializations | c:@ST>2#T#T@PseudoOverridesInSpecializations | | Ref,RelCont | rel: 1 +// CHECK-NEXT: RelCont + template class PseudoOverridesInSpecializations { typedef float TypealiasOrRecord; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34392: [index] Nested class declarations should be annotated with the "specializationOf" relation if they pseudo-override a type in the base template
This revision was automatically updated to reflect the committed changes. Closed by commit rL305911: [index] Nested class declarations should be annotated with the (authored by arphaman). Changed prior to commit: https://reviews.llvm.org/D34392?vs=103179&id=103369#toc Repository: rL LLVM https://reviews.llvm.org/D34392 Files: cfe/trunk/lib/Index/IndexDecl.cpp cfe/trunk/test/Index/Core/index-source.cpp Index: cfe/trunk/lib/Index/IndexDecl.cpp === --- cfe/trunk/lib/Index/IndexDecl.cpp +++ cfe/trunk/lib/Index/IndexDecl.cpp @@ -351,9 +351,11 @@ IndexCtx.indexTagDecl(D, Relations); } else { auto *Parent = dyn_cast(D->getDeclContext()); +SmallVector Relations; +gatherTemplatePseudoOverrides(D, Relations); return IndexCtx.handleReference(D, D->getLocation(), Parent, D->getLexicalDeclContext(), -SymbolRoleSet()); +SymbolRoleSet(), Relations); } } return true; Index: cfe/trunk/test/Index/Core/index-source.cpp === --- cfe/trunk/test/Index/Core/index-source.cpp +++ cfe/trunk/test/Index/Core/index-source.cpp @@ -134,6 +134,9 @@ template struct InnerTemplate { }; template struct InnerTemplate { }; + + template + class InnerClass { }; }; template<> @@ -195,8 +198,22 @@ // CHECK-NEXT: RelChild // CHECK-NEXT: RelSpecialization | InnerTemplate | c:@ST>2#T#T@PseudoOverridesInSpecializations@ST>1#T@InnerTemplate template struct InnerTemplate { }; + + template + class InnerClass; +// CHECK: [[@LINE-1]]:9 | class(Gen)/C++ | InnerClass | c:@S@PseudoOverridesInSpecializations>#d#I@ST>1#T@InnerClass | | Ref,RelCont,RelSpecialization | rel: 2 +// CHECK-NEXT: RelCont +// CHECK-NEXT: RelSpecialization | InnerClass | c:@ST>2#T#T@PseudoOverridesInSpecializations@ST>1#T@InnerClass }; +template +class PseudoOverridesInSpecializations::InnerClass { +}; +// CHECK: [[@LINE-2]]:54 | class(Gen)/C++ | InnerClass | c:@S@PseudoOverridesInSpecializations>#d#I@ST>1#T@InnerClass | | Def,RelChild | rel: 1 +// CHECK-NEXT: RelChild +// CHECK: [[@LINE-4]]:7 | class(Gen)/C++ | PseudoOverridesInSpecializations | c:@ST>2#T#T@PseudoOverridesInSpecializations | | Ref,RelCont | rel: 1 +// CHECK-NEXT: RelCont + template class PseudoOverridesInSpecializations { typedef float TypealiasOrRecord; Index: cfe/trunk/lib/Index/IndexDecl.cpp === --- cfe/trunk/lib/Index/IndexDecl.cpp +++ cfe/trunk/lib/Index/IndexDecl.cpp @@ -351,9 +351,11 @@ IndexCtx.indexTagDecl(D, Relations); } else { auto *Parent = dyn_cast(D->getDeclContext()); +SmallVector Relations; +gatherTemplatePseudoOverrides(D, Relations); return IndexCtx.handleReference(D, D->getLocation(), Parent, D->getLexicalDeclContext(), -SymbolRoleSet()); +SymbolRoleSet(), Relations); } } return true; Index: cfe/trunk/test/Index/Core/index-source.cpp === --- cfe/trunk/test/Index/Core/index-source.cpp +++ cfe/trunk/test/Index/Core/index-source.cpp @@ -134,6 +134,9 @@ template struct InnerTemplate { }; template struct InnerTemplate { }; + + template + class InnerClass { }; }; template<> @@ -195,8 +198,22 @@ // CHECK-NEXT: RelChild // CHECK-NEXT: RelSpecialization | InnerTemplate | c:@ST>2#T#T@PseudoOverridesInSpecializations@ST>1#T@InnerTemplate template struct InnerTemplate { }; + + template + class InnerClass; +// CHECK: [[@LINE-1]]:9 | class(Gen)/C++ | InnerClass | c:@S@PseudoOverridesInSpecializations>#d#I@ST>1#T@InnerClass | | Ref,RelCont,RelSpecialization | rel: 2 +// CHECK-NEXT: RelCont +// CHECK-NEXT: RelSpecialization | InnerClass | c:@ST>2#T#T@PseudoOverridesInSpecializations@ST>1#T@InnerClass }; +template +class PseudoOverridesInSpecializations::InnerClass { +}; +// CHECK: [[@LINE-2]]:54 | class(Gen)/C++ | InnerClass | c:@S@PseudoOverridesInSpecializations>#d#I@ST>1#T@InnerClass | | Def,RelChild | rel: 1 +// CHECK-NEXT: RelChild +// CHECK: [[@LINE-4]]:7 | class(Gen)/C++ | PseudoOverridesInSpecializations | c:@ST>2#T#T@PseudoOverridesInSpecializations | | Ref,RelCont | rel: 1 +// CHECK-NEXT: RelCont + template class PseudoOverridesInSpecializations { typedef float TypealiasOrRecord; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305912 - clang-format: introduce InlineOnly short function style
Author: typz Date: Wed Jun 21 08:56:02 2017 New Revision: 305912 URL: http://llvm.org/viewvc/llvm-project?rev=305912&view=rev Log: clang-format: introduce InlineOnly short function style Summary: This is the same as Inline, except it does not imply all empty functions are merged: with this style, empty functions are merged only if they also match the 'inline' criteria (i.e. defined in a class). This is helpful to avoid inlining functions in implementations files. Reviewers: djasper, krasimir Reviewed By: djasper Subscribers: klimek, rengolin, cfe-commits Differential Revision: https://reviews.llvm.org/D34399 Modified: cfe/trunk/include/clang/Format/Format.h cfe/trunk/lib/Format/Format.cpp cfe/trunk/lib/Format/TokenAnnotator.cpp cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp cfe/trunk/unittests/Format/FormatTest.cpp Modified: cfe/trunk/include/clang/Format/Format.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=305912&r1=305911&r2=305912&view=diff == --- cfe/trunk/include/clang/Format/Format.h (original) +++ cfe/trunk/include/clang/Format/Format.h Wed Jun 21 08:56:02 2017 @@ -184,9 +184,23 @@ struct FormatStyle { enum ShortFunctionStyle { /// \brief Never merge functions into a single line. SFS_None, +/// \brief Only merge functions defined inside a class. Same as "inline", +/// except it does not implies "empty": i.e. top level empty functions +/// are not merged either. +/// \code +/// class Foo { +/// void f() { foo(); } +/// }; +/// void f() { +/// foo(); +/// } +/// void f() { +/// } +/// \endcode +SFS_InlineOnly, /// \brief Only merge empty functions. /// \code -/// void f() { bar(); } +/// void f() {} /// void f2() { /// bar2(); /// } @@ -197,6 +211,10 @@ struct FormatStyle { /// class Foo { /// void f() { foo(); } /// }; +/// void f() { +/// foo(); +/// } +/// void f() {} /// \endcode SFS_Inline, /// \brief Merge all functions fitting on a single line. Modified: cfe/trunk/lib/Format/Format.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=305912&r1=305911&r2=305912&view=diff == --- cfe/trunk/lib/Format/Format.cpp (original) +++ cfe/trunk/lib/Format/Format.cpp Wed Jun 21 08:56:02 2017 @@ -97,6 +97,7 @@ template <> struct ScalarEnumerationTrai IO.enumCase(Value, "All", FormatStyle::SFS_All); IO.enumCase(Value, "true", FormatStyle::SFS_All); IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline); +IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly); IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty); } }; Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=305912&r1=305911&r2=305912&view=diff == --- cfe/trunk/lib/Format/TokenAnnotator.cpp (original) +++ cfe/trunk/lib/Format/TokenAnnotator.cpp Wed Jun 21 08:56:02 2017 @@ -2480,8 +2480,8 @@ bool TokenAnnotator::mustBreakBefore(con return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || (Left.NestingLevel == 0 && Line.Level == 0 && - Style.AllowShortFunctionsOnASingleLine == - FormatStyle::SFS_Inline); + Style.AllowShortFunctionsOnASingleLine & + FormatStyle::SFS_InlineOnly); } else if (Style.Language == FormatStyle::LK_Java) { if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && Right.Next->is(tok::string_literal)) Modified: cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp?rev=305912&r1=305911&r2=305912&view=diff == --- cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp (original) +++ cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp Wed Jun 21 08:56:02 2017 @@ -226,7 +226,7 @@ private: Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All || (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && I[1]->First->is(tok::r_brace)) || -(Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline && +(Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly && TheLine->Level != 0); if (Style.CompactNamespaces) { Modified: cfe/trunk/unittests/Format/FormatTest.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?r
[PATCH] D34399: clang-format: introduce InlineOnly short function style
This revision was automatically updated to reflect the committed changes. Closed by commit rL305912: clang-format: introduce InlineOnly short function style (authored by Typz). Changed prior to commit: https://reviews.llvm.org/D34399?vs=103357&id=103370#toc Repository: rL LLVM https://reviews.llvm.org/D34399 Files: cfe/trunk/include/clang/Format/Format.h cfe/trunk/lib/Format/Format.cpp cfe/trunk/lib/Format/TokenAnnotator.cpp cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp cfe/trunk/unittests/Format/FormatTest.cpp Index: cfe/trunk/include/clang/Format/Format.h === --- cfe/trunk/include/clang/Format/Format.h +++ cfe/trunk/include/clang/Format/Format.h @@ -184,9 +184,23 @@ enum ShortFunctionStyle { /// \brief Never merge functions into a single line. SFS_None, +/// \brief Only merge functions defined inside a class. Same as "inline", +/// except it does not implies "empty": i.e. top level empty functions +/// are not merged either. +/// \code +/// class Foo { +/// void f() { foo(); } +/// }; +/// void f() { +/// foo(); +/// } +/// void f() { +/// } +/// \endcode +SFS_InlineOnly, /// \brief Only merge empty functions. /// \code -/// void f() { bar(); } +/// void f() {} /// void f2() { /// bar2(); /// } @@ -197,6 +211,10 @@ /// class Foo { /// void f() { foo(); } /// }; +/// void f() { +/// foo(); +/// } +/// void f() {} /// \endcode SFS_Inline, /// \brief Merge all functions fitting on a single line. Index: cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp === --- cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp +++ cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp @@ -226,7 +226,7 @@ Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All || (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && I[1]->First->is(tok::r_brace)) || -(Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline && +(Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly && TheLine->Level != 0); if (Style.CompactNamespaces) { Index: cfe/trunk/lib/Format/Format.cpp === --- cfe/trunk/lib/Format/Format.cpp +++ cfe/trunk/lib/Format/Format.cpp @@ -97,6 +97,7 @@ IO.enumCase(Value, "All", FormatStyle::SFS_All); IO.enumCase(Value, "true", FormatStyle::SFS_All); IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline); +IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly); IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty); } }; Index: cfe/trunk/lib/Format/TokenAnnotator.cpp === --- cfe/trunk/lib/Format/TokenAnnotator.cpp +++ cfe/trunk/lib/Format/TokenAnnotator.cpp @@ -2480,8 +2480,8 @@ return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || (Left.NestingLevel == 0 && Line.Level == 0 && - Style.AllowShortFunctionsOnASingleLine == - FormatStyle::SFS_Inline); + Style.AllowShortFunctionsOnASingleLine & + FormatStyle::SFS_InlineOnly); } else if (Style.Language == FormatStyle::LK_Java) { if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && Right.Next->is(tok::string_literal)) Index: cfe/trunk/unittests/Format/FormatTest.cpp === --- cfe/trunk/unittests/Format/FormatTest.cpp +++ cfe/trunk/unittests/Format/FormatTest.cpp @@ -6509,6 +6509,52 @@ MergeInlineOnly); } +TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { + FormatStyle MergeInlineOnly = getLLVMStyle(); + MergeInlineOnly.AllowShortFunctionsOnASingleLine = + FormatStyle::SFS_InlineOnly; + verifyFormat("class C {\n" + " int f() { return 42; }\n" + "};", + MergeInlineOnly); + verifyFormat("int f() {\n" + " return 42;\n" + "}", + MergeInlineOnly); + + // SFS_InlineOnly does not imply SFS_Empty + verifyFormat("class C {\n" + " int f() {}\n" + "};", + MergeInlineOnly); + verifyFormat("int f() {\n" + "}", + MergeInlineOnly); + + // Also verify behavior when BraceWrapping.AfterFunction = true + MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; + MergeInlineOnly.BraceWrapping.AfterFunction = true; + verifyFormat("class C {\n" + " int f() { return 42; }\n" + "};", + Merg
[PATCH] D34449: [Clang-tidy] Enable constexpr definitions in headers.
xazax.hun created this revision. xazax.hun added a project: clang-tools-extra. Herald added a subscriber: whisperity. Constexpr variable definitions should be ok in headers. https://stackoverflow.com/questions/34445336/constexpr-global-constants-in-a-header-file-and-odr Repository: rL LLVM https://reviews.llvm.org/D34449 Files: clang-tidy/misc/DefinitionsInHeadersCheck.cpp test/clang-tidy/misc-definitions-in-headers.hpp Index: test/clang-tidy/misc-definitions-in-headers.hpp === --- test/clang-tidy/misc-definitions-in-headers.hpp +++ test/clang-tidy/misc-definitions-in-headers.hpp @@ -1,4 +1,4 @@ -// RUN: %check_clang_tidy %s misc-definitions-in-headers %t +// RUN: %check_clang_tidy %s misc-definitions-in-headers %t -- -- -std=c++1z int f() { // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: function 'f' defined in a header file; function definitions in header files can lead to ODR violations [misc-definitions-in-headers] @@ -175,3 +175,7 @@ int CD::f() { // OK: partial template specialization. return 0; } + +class CE { + constexpr static int i = 5; // OK: constexpr definition. +}; Index: clang-tidy/misc/DefinitionsInHeadersCheck.cpp === --- clang-tidy/misc/DefinitionsInHeadersCheck.cpp +++ clang-tidy/misc/DefinitionsInHeadersCheck.cpp @@ -54,7 +54,7 @@ return; auto DefinitionMatcher = anyOf(functionDecl(isDefinition(), unless(isDeleted())), -varDecl(isDefinition())); +varDecl(isDefinition(), unless(isConstexpr(; if (UseHeaderFileExtension) { Finder->addMatcher(namedDecl(DefinitionMatcher, usesHeaderFileExtension(HeaderFileExtensions)) Index: test/clang-tidy/misc-definitions-in-headers.hpp === --- test/clang-tidy/misc-definitions-in-headers.hpp +++ test/clang-tidy/misc-definitions-in-headers.hpp @@ -1,4 +1,4 @@ -// RUN: %check_clang_tidy %s misc-definitions-in-headers %t +// RUN: %check_clang_tidy %s misc-definitions-in-headers %t -- -- -std=c++1z int f() { // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: function 'f' defined in a header file; function definitions in header files can lead to ODR violations [misc-definitions-in-headers] @@ -175,3 +175,7 @@ int CD::f() { // OK: partial template specialization. return 0; } + +class CE { + constexpr static int i = 5; // OK: constexpr definition. +}; Index: clang-tidy/misc/DefinitionsInHeadersCheck.cpp === --- clang-tidy/misc/DefinitionsInHeadersCheck.cpp +++ clang-tidy/misc/DefinitionsInHeadersCheck.cpp @@ -54,7 +54,7 @@ return; auto DefinitionMatcher = anyOf(functionDecl(isDefinition(), unless(isDeleted())), -varDecl(isDefinition())); +varDecl(isDefinition(), unless(isConstexpr(; if (UseHeaderFileExtension) { Finder->addMatcher(namedDecl(DefinitionMatcher, usesHeaderFileExtension(HeaderFileExtensions)) ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34430: [Clang][TypoCorrection] Clang hangs in typo correction
iid_iunknown added a comment. No hang with this patch on the test case from PR33484. Clang reports a number of expected compilation errors instead. Repository: rL LLVM https://reviews.llvm.org/D34430 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34449: [clang-tidy] Enable constexpr definitions in headers.
aaron.ballman added inline comments. Comment at: test/clang-tidy/misc-definitions-in-headers.hpp:180 +class CE { + constexpr static int i = 5; // OK: constexpr definition. +}; This is not as safe as you might think. As-is, this is fine, however, if the class is given an inline function where that variable is odr-used, you will get an ODR violation. I think it's mildly better to err on the side of safety here and diagnose. Repository: rL LLVM https://reviews.llvm.org/D34449 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D33645: [analyzer] Add missing documentation for static analyzer checkers
szdominik updated this revision to Diff 103378. szdominik marked 3 inline comments as done. szdominik added a comment. Fixed alpha.core.CallAndMessageUnInitRefArg. https://reviews.llvm.org/D33645 Files: www/analyzer/alpha_checks.html www/analyzer/available_checks.html www/analyzer/implicit_checks.html Index: www/analyzer/implicit_checks.html === --- www/analyzer/implicit_checks.html +++ www/analyzer/implicit_checks.html @@ -27,7 +27,7 @@ OS X Implicit Checkers - + Core Implicit Checkers @@ -124,7 +124,7 @@ - + OS X Implicit Checkers Index: www/analyzer/available_checks.html === --- www/analyzer/available_checks.html +++ www/analyzer/available_checks.html @@ -38,12 +38,14 @@ Core Checkers model core language features and perform general-purpose checks such as division by zero, null pointer dereference, usage of uninitialized values, etc. C++ Checkers perform C++-specific checks Dead Code Checkers check for unused code +Nullability Checkers +Optin Checkers OS X Checkers perform Objective-C-specific checks and check the use of Apple's SDKs (OS X and iOS) Security Checkers check for insecure API usage and perform checks based on the CERT Secure Coding Standards Unix Checkers check the use of Unix and POSIX APIs - + Core Checkers @@ -360,7 +362,7 @@ - + C++ Checkers @@ -421,9 +423,21 @@ } + +cplusplus.NewDeleteLeaks +(C++) +Check for memory leaks. Traces memory managed by new/ +delete. + + +void test() { + int *p = new int; +} // warn + + - + Dead Code Checkers @@ -444,7 +458,157 @@ - + +Nullability Checkers + + +Name, DescriptionExample + + + +nullability.NullPassedToNonnull +(ObjC) +Warns when a null pointer is passed to a pointer which has a +_Nonnull type. + + +typedef struct Dummy { int val; } Dummy; +void takesNonnull(Dummy *_Nonnull); + +void test() { + Dummy *q = 0; + takesNonnull(q); // warn +} + + + + +nullability.NullReturnedFromNonnull +(ObjC) +Warns when a null pointer is returned from a function that has +_Nonnull return type. + + +typedef struct Dummy { int val; } Dummy; + +Dummy *_Nonnull test() { + Dummy *p = 0; + return p; // warn +} + + + + +nullability.NullableDereferenced +(ObjC) +Warns when a nullable pointer is dereferenced. + + +typedef struct Dummy { int val; } Dummy; +Dummy *_Nullable returnsNullable(); + +void test() { + Dummy *p = returnsNullable(); + Dummy &r = *p; // warn +} + + + + +nullability.NullablePassedToNonnull +(ObjC) +Warns when a nullable pointer is passed to a pointer which has a _Nonnull type. + + +typedef struct Dummy { int val; } Dummy; +Dummy *_Nullable returnsNullable(); +void takesNonnull(Dummy *_Nonnull); + +void test() { + Dummy *p = returnsNullable(); + takesNonnull(p); // warn +} + + + + + +Optin Checkers + + +Name, DescriptionExample + + + +optin.mpi.MPI-Checker +(C) +Checks MPI code + + +void test() { + double buf = 0; + MPI_Request sendReq1; + MPI_Ireduce(MPI_IN_PLACE, &buf, 1, MPI_DOUBLE, MPI_SUM, + 0, MPI_COMM_WORLD, &sendReq1); +} // warn: request 'sendReq1' has no matching wait. + + +void test() { + double buf = 0; + MPI_Request sendReq; + MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); + MPI_Irecv(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn + MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn + MPI_Wait(&sendReq, MPI_STATUS_IGNORE); +} + + +void missingNonBlocking() { + int rank = 0; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Request sendReq1[10][10][10]; + MPI_Wait(&sendReq1[1][7][9], MPI_STATUS_IGNORE); // warn +} + + + + +optin.osx.cocoa.localizability.EmptyLocalizationContextChecker +(ObjC) +Check that NSLocalizedString macros include a comment for context. + + +- (void)test { + NSString *string = NSLocalizedString(@"LocalizedString", nil); // warn + NSString *string2 = NSLocalizedString(@"LocalizedString", @" "); // warn + NSString *string3 = NSLocalizedStringWithDefaultValue( +@"LocalizedString", nil, [[NSBundle alloc] init], nil,@""); // warn +} + + + + +optin.osx.cocoa.localizability.NonLocalizedStringChecker +(ObjC) +Warns about uses of non-localized NSStrings passed to UI methods +expecting localized NSStrings + + +- (void)test { + UILabel *testLabel = [[UILabel alloc] init]; + NSString *bar = NSLocalizedString(@"Hello", @"Comment"); + + if (random()) { +bar = @"Unlocalized string"; + } + + [testLabel setText:bar]; // warn +} + + + + + OS X Checkers @@ -466,6 +630,37 @@ +osx.NumberObjectConversion +(C, C++, ObjC) +Check for erroneous conversions of objects representing numbers +into numbers + + +typedef const struct __CFNumber *CFNumberRef; +void takes_int(int); + +void test(CFNumberRef p) { +#ifdef PEDANTIC + if (p) {} // warn + if (!p) {} // warn + p ? 1 : 2; // warn + if (p == 0) {} // warn +#else + if (p) {} // no
[PATCH] D34342: [OpenCL] Fix code generation of function-scope constant samplers.
Anastasia added a comment. In https://reviews.llvm.org/D34342#785454, @bader wrote: > Wow... > Nice catch. > For some reason I can't reproduce the problem neither. > I will drop source code change, but I'd like to modify the test anyway. I think we probably had this issue at some point... Can't think of any recent commit that fixed it apart from may be r288163. > https://reviews.llvm.org/rL277024 added test/CodeGenOpenCL/sampler.cl and > modified test/SemaOpenCL/sampler_t.cl. > I want to move the parts of the test/SemaOpenCL/sampler_t.cl, which are > supposed to pass semantic analysis to test/CodeGenOpenCL/sampler.cl and > validate the LLVM IR after code generation. > Are you OK with this? Sure. Sounds like a good improvement to testing! Thanks! https://reviews.llvm.org/D34342 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D33722: [clang-tidy] Add checker for undelegated copy of base classes
szdominik updated this revision to Diff 103385. szdominik marked 4 inline comments as done. szdominik added a comment. Updated loop for searching the beginning of the initlist. https://reviews.llvm.org/D33722 Files: clang-tidy/misc/CMakeLists.txt clang-tidy/misc/CopyConstructorInitCheck.cpp clang-tidy/misc/CopyConstructorInitCheck.h clang-tidy/misc/MiscTidyModule.cpp docs/ReleaseNotes.rst docs/clang-tidy/checks/list.rst docs/clang-tidy/checks/misc-copy-constructor-init.rst test/clang-tidy/misc-copy-constructor-init.cpp Index: test/clang-tidy/misc-copy-constructor-init.cpp === --- /dev/null +++ test/clang-tidy/misc-copy-constructor-init.cpp @@ -0,0 +1,96 @@ +// RUN: %check_clang_tidy %s misc-copy-constructor-init %t + +class Copyable { + public: + Copyable() = default; + Copyable(const Copyable&) = default; +}; +class X : public Copyable { + X(const X& other) : Copyable(other) {} + //Good code: the copy ctor call the ctor of the base class. +}; + +class Copyable2 { + public: + Copyable2() = default; + Copyable2(const Copyable2&) = default; +}; +class X2 : public Copyable2 { + X2(const X2& other) {}; +// CHECK-MESSAGES: :[[@LINE-1]]:22: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: : Copyable2(other) +}; + +class X3 : public Copyable, public Copyable2 { + X3(const X3& other): Copyable(other) {}; + // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: Copyable2(other), +}; + +class X4 : public Copyable { + X4(const X4& other): Copyable() {}; + // CHECK-MESSAGES: :[[@LINE-1]]:32: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: other +}; + +class Copyable3 : public Copyable { + public: + Copyable3() = default; + Copyable3(const Copyable3&) = default; +}; +class X5 : public Copyable3 { + X5(const X5& other) {}; +// CHECK-MESSAGES: :[[@LINE-1]]:22: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: : Copyable3(other) +}; + +class X6 : public Copyable2, public Copyable3 { + X6(const X6& other) {}; + // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: : Copyable2(other), Copyable3(other) +}; + +class X7 : public Copyable, public Copyable2 { + X7(const X7& other): Copyable() {}; + // CHECK-MESSAGES: :[[@LINE-1]]:32: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: other + // CHECK-MESSAGES: :[[@LINE-3]]:22: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: Copyable2(other), +}; + +template +class Copyable4 { + public: + Copyable4() = default; + Copyable4(const Copyable4&) = default; +}; + +class X8 : public Copyable4 { + X8(const X8& other): Copyable4(other) {}; + //Good code: the copy ctor call the ctor of the base class. +}; + +class X9 : public Copyable4 { + X9(const X9& other): Copyable4() {}; + // CHECK-MESSAGES: :[[@LINE-1]]:37: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: other +}; + +class X10 : public Copyable4 { + X10(const X10& other) {}; + // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: : Copyable4(other) +}; + +template +class Copyable5 { + public: + Copyable5() = default; + Copyable5(const Copyable5&) = default; +}; + +class X11 : public Copyable5 { + X11(const X11& other) {}; + // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: calling an inherited constructor other than the copy constructor [misc-copy-constructor-init] + // CHECK-FIXES: : Copyable5(other) +}; Index: docs/clang-tidy/checks/misc-copy-constructor-init.rst === --- /dev/null +++ docs/clang-tidy/checks/misc-copy-constructor-init.rst @@ -0,0 +1,30 @@ +.. title:: clang-tidy - misc-copy-constructor-init + +misc-copy-constructor-init += + +Finds copy constructors where the constructor don't call +the constructor of the base class. + +.. code-block:: c++ + +class Copyable { +public: +Copyable() = default; +Copyable(const Copyable&) = default; +}; +class X2 : public Copyable { +X2(const X2& other) {}; // Copyable(other) is missing +}; + +Also finds copy constructors where the constructor of +the base class don't have parameter. + +.. code-block:: c++ + +class X4 : public Copyable { +X4(const X4& other): Copyable() {}; // other is missing +}; + +The chec
[PATCH] D34454: SwiftAggregateLowering: Use type alloc size to determine the size of types
aschwaighofer created this revision. The layout must be compatible with the input layout, offsets are defined in terms of offsets within a packed struct which are computed in terms of the alloc size of a type. Using the store size we would insert padding for the following type for example: struct { int3 v; long long l; } __attribute((packed)) On x86-64 int3 is padded to int4 alignment. The swiftcc type would be <{ <3 x float>, [4 x i8], i64 }> which is not compatible with <{ <3 x float>, i64 }>. The latter has i64 at offset 16 and the former at offset 20. rdar://32618125 https://reviews.llvm.org/D34454 Files: lib/CodeGen/SwiftCallingConv.cpp test/CodeGen/64bit-swiftcall.c test/CodeGen/windows-swiftcall.c Index: test/CodeGen/windows-swiftcall.c === --- test/CodeGen/windows-swiftcall.c +++ test/CodeGen/windows-swiftcall.c @@ -455,4 +455,4 @@ int3 v __attribute__((packed)); } misaligned_int3; TEST(misaligned_int3) -// CHECK-LABEL: define swiftcc void @take_misaligned_int3(i64, i64) +// CHECK-LABEL: define swiftcc void @take_misaligned_int3(i64, i64, i32) Index: test/CodeGen/64bit-swiftcall.c === --- test/CodeGen/64bit-swiftcall.c +++ test/CodeGen/64bit-swiftcall.c @@ -1,4 +1,5 @@ // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s --check-prefix=X86-64 // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM64 @@ -463,7 +464,7 @@ int3 v __attribute__((packed)); } misaligned_int3; TEST(misaligned_int3) -// CHECK-LABEL: define swiftcc void @take_misaligned_int3(i64, i64) +// CHECK-LABEL: define swiftcc void @take_misaligned_int3(i64, i64, i32) typedef struct { float f0; @@ -1014,3 +1015,19 @@ TEST(struct_v1f3) // ARM64-LABEL: define swiftcc { <2 x float>, float } @return_struct_v1f3() // ARM64-LABEL: define swiftcc void @take_struct_v1f3(<2 x float>, float) + +typedef struct { + int3 vect; + unsigned long long val; +} __attribute__((packed)) padded_alloc_size_vector; +TEST(padded_alloc_size_vector) +// X86-64-LABEL: take_padded_alloc_size_vector(<3 x i32>, i64) +// ARM64-LABEL: take_padded_alloc_size_vector(<2 x i32>, i32, i64) + +typedef union { + float f1; + float3 fv2; +} union_hom_fp_partial2; +TEST(union_hom_fp_partial2) +// X86-64-LABEL: take_union_hom_fp_partial2(i64, i64) +// ARM64-LABEL: take_union_hom_fp_partial2(i64, float) Index: lib/CodeGen/SwiftCallingConv.cpp === --- lib/CodeGen/SwiftCallingConv.cpp +++ lib/CodeGen/SwiftCallingConv.cpp @@ -57,6 +57,10 @@ return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type)); } +static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) { + return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type)); +} + void SwiftAggLowering::addTypedData(QualType type, CharUnits begin) { // Deal with various aggregate types as special cases: @@ -189,24 +193,24 @@ void SwiftAggLowering::addTypedData(llvm::Type *type, CharUnits begin) { assert(type && "didn't provide type for typed data"); - addTypedData(type, begin, begin + getTypeStoreSize(CGM, type)); + addTypedData(type, begin, begin + getTypeAllocSize(CGM, type)); } void SwiftAggLowering::addTypedData(llvm::Type *type, CharUnits begin, CharUnits end) { assert(type && "didn't provide type for typed data"); - assert(getTypeStoreSize(CGM, type) == end - begin); + assert(getTypeAllocSize(CGM, type) == end - begin); // Legalize vector types. if (auto vecTy = dyn_cast(type)) { SmallVector componentTys; -legalizeVectorType(CGM, end - begin, vecTy, componentTys); +legalizeVectorType(CGM, getTypeStoreSize(CGM, type), vecTy, componentTys); assert(componentTys.size() >= 1); // Walk the initial components. for (size_t i = 0, e = componentTys.size(); i != e - 1; ++i) { llvm::Type *componentTy = componentTys[i]; - auto componentSize = getTypeStoreSize(CGM, componentTy); + auto componentSize = getTypeAllocSize(CGM, componentTy); assert(componentSize < end - begin); addLegalTypedData(componentTy, begin, begin + componentSize); begin += componentSize; @@ -236,14 +240,15 @@ auto eltTy = split.first; auto numElts = split.second; - auto eltSize = (end - begin) / numElts; - assert(eltSize == getTypeStoreSize(CGM, eltTy)); - for (size_t i = 0, e = numElts; i != e; ++i) { -addLegalTypedData(eltTy, begin, begin + eltSize); -begin += eltSize; + auto eltSize = getTypeAl
[PATCH] D32439: Fix for incorrect source position of dependent c'tor initializer (bug:26195)
arphaman added a comment. Thanks for the fix! The implementation looks correct. A couple of misc comments: - Please move the test to `test/Index` (Since it uses `c-index-test`). - In the future please upload patches with full context (`git diff -U`). Comment at: lib/Sema/SemaDeclCXX.cpp:3771 + TInfo = Context.CreateTypeSourceInfo(BaseType); + DependentNameTypeLoc TL = TInfo->getTypeLoc().castAs(); + if (!TL.isNull()) { This line violates the 80 columns. Please use clang-format! https://reviews.llvm.org/D32439 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34449: [clang-tidy] Enable constexpr definitions in headers.
hokein added inline comments. Comment at: test/clang-tidy/misc-definitions-in-headers.hpp:1 -// RUN: %check_clang_tidy %s misc-definitions-in-headers %t +// RUN: %check_clang_tidy %s misc-definitions-in-headers %t -- -- -std=c++1z The original code should work as `-std=c++11` will be added defaultly by `check_clang_tidy` script. Comment at: test/clang-tidy/misc-definitions-in-headers.hpp:180 +class CE { + constexpr static int i = 5; // OK: constexpr definition. +}; aaron.ballman wrote: > This is not as safe as you might think. As-is, this is fine, however, if the > class is given an inline function where that variable is odr-used, you will > get an ODR violation. > > I think it's mildly better to err on the side of safety here and diagnose. I think the current code (Line `97` in `DefinitionsInHeadersCheck.cpp`) has already guaranteed this case. Can you try to run it without your change in the `DefinitionsInHeadersCheck.cpp`? I think it still makes sense to add `constexpr` test cases. Repository: rL LLVM https://reviews.llvm.org/D34449 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34455: Correct VectorCall x86 (32 bit) behavior for SSE Register Assignment
erichkeane created this revision. In running some internal vectorcall tests in 32 bit mode, we discovered that the behavior I'd previously implemented for x64 (and applied to x32) regarding the assignment of SSE registers was incorrect. See spec here: https://msdn.microsoft.com/en-us/library/dn375768.aspx My previous implementation applied register argument position from the x64 version to both. This isn't correct for x86, so this removes and refactors that section. Additionally, it corrects the integer/int-pointer assignments. Unlike x64, x86 permits integers to be assigned independent of position. Finally, the code for 32 bit was cleaned up a little to clarify the intent, as well as given a descriptive comment. https://reviews.llvm.org/D34455 Files: lib/CodeGen/TargetInfo.cpp test/CodeGen/vectorcall.c Index: lib/CodeGen/TargetInfo.cpp === --- lib/CodeGen/TargetInfo.cpp +++ lib/CodeGen/TargetInfo.cpp @@ -951,8 +951,7 @@ Class classify(QualType Ty) const; ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; - ABIArgInfo reclassifyHvaArgType(QualType RetTy, CCState &State, - const ABIArgInfo& current) const; + /// \brief Updates the number of available free registers, returns /// true if any registers were allocated. bool updateFreeRegs(QualType Ty, CCState &State) const; @@ -1536,27 +1535,6 @@ return true; } -ABIArgInfo -X86_32ABIInfo::reclassifyHvaArgType(QualType Ty, CCState &State, -const ABIArgInfo ¤t) const { - // Assumes vectorCall calling convention. - const Type *Base = nullptr; - uint64_t NumElts = 0; - - if (!Ty->isBuiltinType() && !Ty->isVectorType() && - isHomogeneousAggregate(Ty, Base, NumElts)) { -if (State.FreeSSERegs >= NumElts) { - // HVA types get passed directly in registers if there is room. - State.FreeSSERegs -= NumElts; - return getDirectX86Hva(); -} -// If there's no room, the HVA gets passed as normal indirect -// structure. -return getIndirectResult(Ty, /*ByVal=*/false, State); - } - return current; -} - ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State) const { // FIXME: Set alignment on indirect arguments. @@ -1575,35 +1553,20 @@ } } - // vectorcall adds the concept of a homogenous vector aggregate, similar - // to other targets, regcall uses some of the HVA rules. + // Regcall uses the concept of a homogenous vector aggregate, similar + // to other targets. const Type *Base = nullptr; uint64_t NumElts = 0; - if ((State.CC == llvm::CallingConv::X86_VectorCall || - State.CC == llvm::CallingConv::X86_RegCall) && + if (State.CC == llvm::CallingConv::X86_RegCall && isHomogeneousAggregate(Ty, Base, NumElts)) { -if (State.CC == llvm::CallingConv::X86_RegCall) { - if (State.FreeSSERegs >= NumElts) { -State.FreeSSERegs -= NumElts; -if (Ty->isBuiltinType() || Ty->isVectorType()) - return ABIArgInfo::getDirect(); -return ABIArgInfo::getExpand(); - - } - return getIndirectResult(Ty, /*ByVal=*/false, State); -} else if (State.CC == llvm::CallingConv::X86_VectorCall) { - if (State.FreeSSERegs >= NumElts && (Ty->isBuiltinType() || Ty->isVectorType())) { -// Actual floating-point types get registers first time through if -// there is registers available -State.FreeSSERegs -= NumElts; +if (State.FreeSSERegs >= NumElts) { + State.FreeSSERegs -= NumElts; + if (Ty->isBuiltinType() || Ty->isVectorType()) return ABIArgInfo::getDirect(); - } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { -// HVA Types only get registers after everything else has been -// set, so it gets set as indirect for now. -return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty)); - } + return ABIArgInfo::getExpand(); } +return getIndirectResult(Ty, /*ByVal=*/false, State); } if (isAggregateTypeForABI(Ty)) { @@ -1684,31 +1647,53 @@ void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State, bool &UsedInAlloca) const { - // Vectorcall only allows the first 6 parameters to be passed in registers, - // and homogeneous vector aggregates are only put into registers as a second - // priority. - unsigned Count = 0; - CCState ZeroState = State; - ZeroState.FreeRegs = ZeroState.FreeSSERegs = 0; - // HVAs must be done as a second priority for registers, so the deferred - // items are dealt with by going through the pattern a second time. + // Vectorcall x86 works subtly different than in x64, so the format is + // a bit different than the x64 version. First, al
[PATCH] D34342: [OpenCL] Fix code generation of function-scope constant samplers.
bader added a comment. I think I found the way to reproduce the issue. There are two pre-requisites: sampler must be declared in the constant address space and clang must be build in Debug mode. I'll fix the test and add the test cases from test/SemaOpenCL/sampler_t.cl as mentioned earlier. https://reviews.llvm.org/D34342 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D33719: Add _Float16 as a C/C++ source language type
SjoerdMeijer updated this revision to Diff 103397. SjoerdMeijer added a comment. This fixes the “DefaultVariadicArgumentPromotion” for Float16: they should be promoted to double, which makes now e.g. printf work. I have added printf tests to both the AST and codegen test to check variadic functions (and thus checked that printf works), and also restructured the AST test a bit so that the check lines are near the corresponding program statement. Yesterday I fixed mixed type (fp16 and float16) expressions, and with this fix for variadic arguments, I think the C support is ready. Do you agree @bruno, or do you think I've missed anything? https://reviews.llvm.org/D33719 Files: include/clang-c/Index.h include/clang/AST/ASTContext.h include/clang/AST/BuiltinTypes.def include/clang/Basic/Specifiers.h include/clang/Basic/TokenKinds.def include/clang/Lex/LiteralSupport.h include/clang/Sema/DeclSpec.h include/clang/Serialization/ASTBitCodes.h lib/AST/ASTContext.cpp lib/AST/ItaniumMangle.cpp lib/AST/MicrosoftMangle.cpp lib/AST/NSAPI.cpp lib/AST/StmtPrinter.cpp lib/AST/Type.cpp lib/AST/TypeLoc.cpp lib/Analysis/PrintfFormatString.cpp lib/CodeGen/CGDebugInfo.cpp lib/CodeGen/CGExprScalar.cpp lib/CodeGen/CodeGenTypes.cpp lib/CodeGen/ItaniumCXXABI.cpp lib/Format/FormatToken.cpp lib/Index/USRGeneration.cpp lib/Lex/LiteralSupport.cpp lib/Parse/ParseDecl.cpp lib/Parse/ParseExpr.cpp lib/Parse/ParseExprCXX.cpp lib/Parse/ParseTentative.cpp lib/Sema/DeclSpec.cpp lib/Sema/SemaDecl.cpp lib/Sema/SemaExpr.cpp lib/Sema/SemaTemplateVariadic.cpp lib/Sema/SemaType.cpp lib/Serialization/ASTCommon.cpp lib/Serialization/ASTReader.cpp test/CodeGenCXX/float16-declarations.cpp test/Frontend/float16.cpp test/Lexer/half-literal.cpp tools/libclang/CXType.cpp Index: tools/libclang/CXType.cpp === --- tools/libclang/CXType.cpp +++ tools/libclang/CXType.cpp @@ -53,6 +53,7 @@ BTCASE(Float); BTCASE(Double); BTCASE(LongDouble); +BTCASE(Float16); BTCASE(Float128); BTCASE(NullPtr); BTCASE(Overload); @@ -520,7 +521,7 @@ TKIND(Char_U); TKIND(UChar); TKIND(Char16); -TKIND(Char32); +TKIND(Char32); TKIND(UShort); TKIND(UInt); TKIND(ULong); @@ -538,6 +539,7 @@ TKIND(Float); TKIND(Double); TKIND(LongDouble); +TKIND(Float16); TKIND(Float128); TKIND(NullPtr); TKIND(Overload); Index: test/Lexer/half-literal.cpp === --- test/Lexer/half-literal.cpp +++ test/Lexer/half-literal.cpp @@ -1,3 +1,6 @@ // RUN: %clang_cc1 -fsyntax-only -verify -pedantic %s float a = 1.0h; // expected-error{{invalid suffix 'h' on floating constant}} float b = 1.0H; // expected-error{{invalid suffix 'H' on floating constant}} + +_Float16 c = 1.f166; // expected-error{{invalid suffix 'f166' on floating constant}} +_Float16 d = 1.f1; // expected-error{{invalid suffix 'f1' on floating constant}} Index: test/Frontend/float16.cpp === --- /dev/null +++ test/Frontend/float16.cpp @@ -0,0 +1,314 @@ +// RUN: %clang_cc1 -std=c++11 -ast-dump %s | FileCheck %s +// RUN: %clang_cc1 -std=c++11 -ast-dump -fnative-half-type %s | FileCheck %s --check-prefix=CHECK-NATIVE + +/* Various contexts where type _Float16 can appear. */ + +/* Namespace */ +namespace { + _Float16 f1n; + _Float16 f2n = 33.f16; + _Float16 arr1n[10]; + _Float16 arr2n[] = { 1.2, 3.0, 3.e4 }; + const volatile _Float16 func1n(const _Float16 &arg) { +return arg + f2n + arr1n[4] - arr2n[1]; + } +} + +//CHECK: |-NamespaceDecl +//CHECK: | |-VarDecl {{.*}} f1n '_Float16' +//CHECK: | |-VarDecl {{.*}} f2n '_Float16' cinit +//CHECK: | | `-FloatingLiteral {{.*}} '_Float16' 3.30e+01 +//CHECK: | |-VarDecl {{.*}} arr1n '_Float16 [10]' +//CHECK: | |-VarDecl {{.*}} arr2n '_Float16 [3]' cinit +//CHECK: | | `-InitListExpr {{.*}} '_Float16 [3]' +//CHECK: | | |-ImplicitCastExpr {{.*}} '_Float16' +//CHECK: | | | `-FloatingLiteral {{.*}} 'double' 1.20e+00 +//CHECK: | | |-ImplicitCastExpr {{.*}} '_Float16' +//CHECK: | | | `-FloatingLiteral {{.*}} 'double' 3.00e+00 +//CHECK: | | `-ImplicitCastExpr {{.*}} '_Float16' +//CHECK: | | `-FloatingLiteral {{.*}} 'double' 3.00e+04 +//CHECK: | `-FunctionDecl {{.*}} func1n 'const volatile _Float16 (const _Float16 &)' + +/* File */ +_Float16 f1f; +_Float16 f2f = 32.4; +_Float16 arr1f[10]; +_Float16 arr2f[] = { -1.2, -3.0, -3.e4 }; +_Float16 func1f(_Float16 arg); + +//CHECK: |-VarDecl {{.*}} f1f '_Float16' +//CHECK: |-VarDecl {{.*}} f2f '_Float16' cinit +//CHECK: | `-ImplicitCastExpr {{.*}} '_Float16' +//CHECK: | `-FloatingLiteral {{.*}} 'double' 3.24e+01 +//CHECK: |-VarDecl {{.*}} arr1f '_Float16 [10]' +//CHECK: |-VarDecl {{.*}} arr2f '_Float16 [3]' cinit +//CHECK: | `-InitListExpr {{.*}} '_Flo
[libunwind] r305924 - Change -1LL to -1ULL to silence a gcc warning about left shifting a negative value. Fixes https://bugs.llvm.org/show_bug.cgi?id=33358
Author: marshall Date: Wed Jun 21 11:02:53 2017 New Revision: 305924 URL: http://llvm.org/viewvc/llvm-project?rev=305924&view=rev Log: Change -1LL to -1ULL to silence a gcc warning about left shifting a negative value. Fixes https://bugs.llvm.org/show_bug.cgi?id=33358 Modified: libunwind/trunk/src/AddressSpace.hpp Modified: libunwind/trunk/src/AddressSpace.hpp URL: http://llvm.org/viewvc/llvm-project/libunwind/trunk/src/AddressSpace.hpp?rev=305924&r1=305923&r2=305924&view=diff == --- libunwind/trunk/src/AddressSpace.hpp (original) +++ libunwind/trunk/src/AddressSpace.hpp Wed Jun 21 11:02:53 2017 @@ -168,7 +168,7 @@ inline int64_t LocalAddressSpace::getSLE } while (byte & 0x80); // sign extend negative numbers if ((byte & 0x40) != 0) -result |= (-1LL) << bit; +result |= (-1ULL) << bit; addr = (pint_t) p; return result; } @@ -265,7 +265,7 @@ LocalAddressSpace::getEncodedP(pint_t &a return result; } -#ifdef __APPLE__ +#ifdef __APPLE__ struct dyld_unwind_sections { @@ -284,7 +284,7 @@ LocalAddressSpace::getEncodedP(pint_t &a // In 10.6.x and earlier, we need to implement this functionality. Note // that this requires a newer version of libmacho (from cctools) than is // present in libSystem on 10.6.x (for getsectiondata). -static inline bool _dyld_find_unwind_sections(void* addr, +static inline bool _dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info) { // Find mach-o image containing address. Dl_info dlinfo; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34269: [clangd] Add "Go to Declaration" functionality
malaperle-ericsson updated this revision to Diff 103405. malaperle-ericsson marked 12 inline comments as done. malaperle-ericsson added a comment. Address comments https://reviews.llvm.org/D34269 Files: clangd/CMakeLists.txt clangd/ClangdLSPServer.cpp clangd/ClangdServer.cpp clangd/ClangdServer.h clangd/ClangdUnit.cpp clangd/ClangdUnit.h clangd/Protocol.cpp clangd/Protocol.h clangd/ProtocolHandlers.cpp clangd/ProtocolHandlers.h test/clangd/definitions.test test/clangd/formatting.test Index: test/clangd/formatting.test === --- test/clangd/formatting.test +++ test/clangd/formatting.test @@ -4,14 +4,15 @@ Content-Length: 125 {"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}} -# CHECK: Content-Length: 424 +# CHECK: Content-Length: 462 # CHECK: {"jsonrpc":"2.0","id":0,"result":{"capabilities":{ # CHECK: "textDocumentSync": 1, # CHECK: "documentFormattingProvider": true, # CHECK: "documentRangeFormattingProvider": true, # CHECK: "documentOnTypeFormattingProvider": {"firstTriggerCharacter":"}","moreTriggerCharacter":[]}, # CHECK: "codeActionProvider": true, -# CHECK: "completionProvider": {"resolveProvider": false, "triggerCharacters": [".",">"]} +# CHECK: "completionProvider": {"resolveProvider": false, "triggerCharacters": [".",">"]}, +# CHECK: "definitionProvider": true # CHECK: }}} # Content-Length: 193 Index: test/clangd/definitions.test === --- /dev/null +++ test/clangd/definitions.test @@ -0,0 +1,168 @@ +# RUN: clangd -run-synchronously < %s | FileCheck %s +# It is absolutely vital that this file has CRLF line endings. +# +Content-Length: 125 + +{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}} + +Content-Length: 172 + +{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"int main() {\nint a;\na;\n}\n"}}} + +Content-Length: 148 + +{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":2,"character":0}}} +# Go to local variable +# CHECK: {"jsonrpc":"2.0","id":1,"result":[{"uri": "file:///main.cpp", "range": {"start": {"line": 1, "character": 0}, "end": {"line": 1, "character": 5}}}]} + +Content-Length: 148 + +{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":2,"character":1}}} +# Go to local variable, end of token +# CHECK: {"jsonrpc":"2.0","id":1,"result":[{"uri": "file:///main.cpp", "range": {"start": {"line": 1, "character": 0}, "end": {"line": 1, "character": 5}}}]} + +Content-Length: 214 + +{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"file:///main.cpp","version":2},"contentChanges":[{"text":"struct Foo {\nint x;\n};\nint main() {\n Foo bar = { x : 1 };\n}\n"}]}} + +Content-Length: 149 + +{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":4,"character":14}}} +# Go to field, GNU old-style field designator +# CHECK: {"jsonrpc":"2.0","id":1,"result":[{"uri": "file:///main.cpp", "range": {"start": {"line": 1, "character": 0}, "end": {"line": 1, "character": 5}}}]} + +Content-Length: 215 + +{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"file:///main.cpp","version":3},"contentChanges":[{"text":"struct Foo {\nint x;\n};\nint main() {\n Foo baz = { .x = 2 };\n}\n"}]}} + +Content-Length: 149 + +{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":4,"character":15}}} +# Go to field, field designator +# CHECK: {"jsonrpc":"2.0","id":1,"result":[{"uri": "file:///main.cpp", "range": {"start": {"line": 1, "character": 0}, "end": {"line": 1, "character": 5}}}]} + +Content-Length: 187 + +{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"file:///main.cpp","version":4},"contentChanges":[{"text":"int main() {\n main();\n return 0;\n}"}]}} + +Content-Length: 148 + +{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":1,"character":3}}} +# Go to function declaration, function call +# CHECK: {"jsonrpc":"2.0","id":1,"result":[{"uri": "file:///main.cpp", "range": {"start": {"line": 0, "character": 0}, "end": {"line": 3, "character": 1}}}]} + +Content-Length: 208 + +{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"file:///main.cpp","version":5},"contentChanges":[{"text":"struct Foo {\n};\nint main() {\n Foo bar;\n return 0;\n}\n"}]}} + +Content-Length: 148 + +{"jsonrpc":"2.0","i
[PATCH] D34269: [clangd] Add "Go to Declaration" functionality
malaperle-ericsson added inline comments. Comment at: clangd/ClangdUnit.cpp:303 + // fo|o -> foo| good! + if (InputLocation == SourceLocationBeg && Pos.character > 0) { +SourceLocation PeekBeforeLocation = Unit->getLocation(FE, Pos.line + 1, ilya-biryukov wrote: > Minor: Maybe invert condition to reduce nesting, i.e. if (InputLocation != > SourceLocationBeg || Pos.character == 0) return SourceLocationBeg; > > PS. I'm perfectly fine if this comment is ignored, it's just a matter of > preference. I like it better with the return Comment at: clangd/ClangdUnit.cpp:306 +Pos.character); +SourceLocation PeekBeforeLocationEnd = Lexer::getLocForEndOfToken( +PeekBeforeLocation, 0, SourceMgr, Unit->getASTContext().getLangOpts()); ilya-biryukov wrote: > Just wondering: is there a way to not do the lexing multiple times? I was able to simplify this a bit. There's on only one call to getRawToken and one to GetBeginningOfToken. Comment at: clangd/DeclarationLocationsFinder.cpp:48 + // This can happen when nodes in the AST are visited twice. + if (std::none_of(DeclarationLocations.begin(), DeclarationLocations.end(), + [&L](const Location& Loc) { ilya-biryukov wrote: > ilya-biryukov wrote: > > Is it possible for DeclarationLocation to become large, so that quadratic > > behavior is observed? > > > > If not, maybe add an assert that it's smaller than some threshold? > > If yes, maybe use std::set instead of std::vector or use vector and later > > std::sort and std::unique in the end? > Maybe use std::find instead of std::none_of? > ``` > std::find(DeclarationLocations.begin(), DeclarationLocations.end(), L) == > DeclarationLocations.end() > ``` I went with std::sort/std::unique. I don't think this will ever be large but I don't think it would be good to have an arbitrary limit either. I think keeping the vector and cleaning it later is nice and simple. Comment at: clangd/DeclarationLocationsFinder.cpp:59 + Token Result; + if (!Lexer::getRawToken(SearchedLocation, Result, Unit.getSourceManager(), + Unit.getASTContext().getLangOpts(), false)) { ilya-biryukov wrote: > Could we implement ` handleMacroOccurence` instead? > I suspect current code won't work if macro is undef'ed/redefined later: > > ``` > #define FOO 123 > > int b = FO|O; > > #define FOO 125 > // or > // #undef FOO > ``` > > Maybe also add this to tests? You're right! It didn't work properly in this case. I added a few tests. For handleMacroOccurence, it actually isn't even called so we'd have to improve the clangIndex code to do this. I think this is a good first step though. Comment at: clangd/Protocol.cpp:57 std::string URI::unparse(const URI &U) { - return U.uri; + return "\"" + U.uri + "\""; } ilya-biryukov wrote: > Why this didn't require any changes to other code? This method hasn't been > used before? No it wasn't used before. Comment at: test/clangd/definitions.test:1 +# RUN: clangd -run-synchronously < %s | FileCheck %s +# It is absolutely vital that this file has CRLF line endings. ilya-biryukov wrote: > Could we also add more readable tests specifically for that? > I propose to have a tool that could read files like: > ``` > int aaa; > int b = a/*{l1}*/aa; > int c = /*{l2}*/b; > ``` > > And have it output the resulting goto results: > ``` > l1 -> {main.cpp:0:4} int |aaa; > l2 -> {main.cpp:1:4} int |b; > ``` > And we could also have a tool that prints expected clangd input/output based > on that to check that action actually works. > It's not directly relevant to this patch, though. Just random thoughts of > what we should do for easier testing. I think it's a good idea! Although I wonder if it's a bit too much work for something that very specific to "textDocument/definition". I fully agree that the tests need to be more readable and it would be worth a try! https://reviews.llvm.org/D34269 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34455: Correct VectorCall x86 (32 bit) behavior for SSE Register Assignment
rnk accepted this revision. rnk added a comment. This revision is now accepted and ready to land. Oh joy. :) lgtm, thanks for debugging this. The difference makes sense after the fact when you think about Win x64's approach to va_arg and /homeparams, and how that isn't relevant for x86. https://reviews.llvm.org/D34455 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34329: [GSoC] Clang AST diffing
johannes updated this revision to Diff 103409. johannes marked 4 inline comments as done. johannes added a comment. - move some unnecessary things out of the public header Is this a proper way to declutter the header file? Using inheritance would also be possible. I have to define a destructor for ASTDiff because TreeComparator is forward-declared https://reviews.llvm.org/D34329 Files: include/clang/Tooling/ASTDiff/ASTDiff.h lib/Tooling/ASTDiff/ASTDiff.cpp lib/Tooling/ASTDiff/CMakeLists.txt lib/Tooling/CMakeLists.txt test/Tooling/clang-diff-basic.cpp tools/CMakeLists.txt tools/clang-diff/CMakeLists.txt tools/clang-diff/ClangDiff.cpp Index: tools/clang-diff/ClangDiff.cpp === --- /dev/null +++ tools/clang-diff/ClangDiff.cpp @@ -0,0 +1,107 @@ +//===- ClangDiff.cpp - compare source files by AST nodes --*- C++ -*- -===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// +// +// This file implements a tool for syntax tree based comparison using +// Tooling/ASTDiff. +// +//===--===// + +#include "clang/Tooling/ASTDiff/ASTDiff.h" +#include "clang/Tooling/CommonOptionsParser.h" +#include "clang/Tooling/Tooling.h" +#include "llvm/Support/CommandLine.h" + +using namespace llvm; +using namespace clang; +using namespace tooling; + +static cl::OptionCategory ClangDiffCategory("clang-diff options"); + +static cl::opt +DumpAST("ast-dump", +cl::desc("Print the internal representation of the AST as JSON."), +cl::init(false), cl::cat(ClangDiffCategory)); + +static cl::opt NoCompilationDatabase( +"no-compilation-database", +cl::desc( +"Do not attempt to load build settigns from a compilation database"), +cl::init(false), cl::cat(ClangDiffCategory)); + +static cl::opt SourcePath(cl::Positional, cl::desc(""), + cl::Required, + cl::cat(ClangDiffCategory)); + +static cl::opt DestinationPath(cl::Positional, +cl::desc(""), +cl::Optional, +cl::cat(ClangDiffCategory)); + +static std::unique_ptr getAST(const StringRef Filename) { + std::string ErrorMessage; + std::unique_ptr Compilations; + if (!NoCompilationDatabase) +Compilations = +CompilationDatabase::autoDetectFromSource(Filename, ErrorMessage); + if (!Compilations) { +if (!NoCompilationDatabase) + llvm::errs() + << "Error while trying to load a compilation database, running " + "without flags.\n" + << ErrorMessage; +Compilations.reset( +new FixedCompilationDatabase(".", std::vector())); + } + std::array Files = {{Filename}}; + ClangTool Tool(*Compilations, Files); + std::vector> ASTs; + Tool.buildASTs(ASTs); + if (ASTs.size() != Files.size()) +return nullptr; + return std::move(ASTs[0]); +} + +int main(int argc, const char **argv) { + cl::HideUnrelatedOptions(ClangDiffCategory); + if (!cl::ParseCommandLineOptions(argc, argv)) { +cl::PrintOptionValues(); +return 1; + } + + if (DumpAST) { +if (!DestinationPath.empty()) { + llvm::errs() << "Error: Please specify exactly one filename.\n"; + return 1; +} +std::unique_ptr AST = getAST(SourcePath); +if (!AST) + return 1; +clang::diff::TreeRoot Tree(AST->getASTContext()); +Tree.printAsJson(); +return 0; + } + + if (DestinationPath.empty()) { +llvm::errs() << "Error: Exactly two paths are required.\n"; +return 1; + } + + std::unique_ptr Src = getAST(SourcePath); + std::unique_ptr Dst = getAST(DestinationPath); + if (!Src || !Dst) +return 1; + + diff::ASTDiff DiffTool(Src->getASTContext(), Dst->getASTContext()); + for (const auto &Match : DiffTool.getMatches()) +DiffTool.printMatch(Match); + for (const auto &Change : DiffTool.getChanges()) +DiffTool.printChange(Change); + + return 0; +} Index: tools/clang-diff/CMakeLists.txt === --- /dev/null +++ tools/clang-diff/CMakeLists.txt @@ -0,0 +1,13 @@ +set(LLVM_LINK_COMPONENTS + Support + ) + +add_clang_executable(clang-diff + ClangDiff.cpp + ) + +target_link_libraries(clang-diff + clangFrontend + clangTooling + clangToolingASTDiff + ) Index: tools/CMakeLists.txt === --- tools/CMakeLists.txt +++ tools/CMakeLists.txt @@ -2,6 +2,7 @@ add_clang_subdirectory(diagtool) add_clang_subdirectory(driver) +add_clang_subdirectory(clang-diff) add_clang_subdirectory(clang-format) add_clan
[PATCH] D34329: [GSoC] Clang AST diffing
johannes added inline comments. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:157 + int Leaves = 0; + std::function Traverse = [&](NodeId Id) { +const Node &N = getNode(Id); arphaman wrote: > you should be able to use `auto` instead of `std::function` here I think. It does not work because the function is recursive. I'm not sure whether it is good practise to do it like this. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:209 +if (X->hasQualifier() && X->getQualifier()->getAsIdentifier()) + Value += std::string(X->getQualifier()->getAsIdentifier()->getName()); +Value += X->getDecl()->getNameAsString(); arphaman wrote: > Qualifiers (i.e. `NestedNameSpecifier`s) can contain multiple identifiers > (e.g. `foo::bar::`). You should use the `print` method from > `NestedNameSpecifier` instead. Ok nice, this works properly! This function needs a lot of work. I try to extract relevant information from base classes first. https://reviews.llvm.org/D34329 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34455: Correct VectorCall x86 (32 bit) behavior for SSE Register Assignment
This revision was automatically updated to reflect the committed changes. Closed by commit rL305928: Correct VectorCall x86 (32 bit) behavior for SSE Register Assignment (authored by erichkeane). Changed prior to commit: https://reviews.llvm.org/D34455?vs=103391&id=103412#toc Repository: rL LLVM https://reviews.llvm.org/D34455 Files: cfe/trunk/lib/CodeGen/TargetInfo.cpp cfe/trunk/test/CodeGen/vectorcall.c Index: cfe/trunk/test/CodeGen/vectorcall.c === --- cfe/trunk/test/CodeGen/vectorcall.c +++ cfe/trunk/test/CodeGen/vectorcall.c @@ -100,8 +100,19 @@ // X32: define x86_vectorcallcc void @"\01odd_size_hva@@32"(%struct.OddSizeHVA inreg %a.coerce) // X64: define x86_vectorcallcc void @"\01odd_size_hva@@32"(%struct.OddSizeHVA inreg %a.coerce) -// The Vectorcall ABI only allows passing the first 6 items in registers, so this shouldn't +// The Vectorcall ABI only allows passing the first 6 items in registers in x64, so this shouldn't // consider 'p7' as a register. Instead p5 gets put into the register on the second pass. -struct HFA2 __vectorcall AddParticles(struct HFA2 p1, float p2, struct HFA4 p3, int p4, struct HFA2 p5, float p6, float p7){ return p1;} -// X32: define x86_vectorcallcc %struct.HFA2 @"\01AddParticles@@80"(%struct.HFA2 inreg %p1.coerce, float %p2, %struct.HFA4* inreg %p3, i32 inreg %p4, %struct.HFA2 inreg %p5.coerce, float %p6, float %p7) -// X64: define x86_vectorcallcc %struct.HFA2 @"\01AddParticles@@96"(%struct.HFA2 inreg %p1.coerce, float %p2, %struct.HFA4* %p3, i32 %p4, %struct.HFA2 inreg %p5.coerce, float %p6, float %p7) +// x86 should pass p2, p6 and p7 in registers, then p1 in the second pass. +struct HFA2 __vectorcall AddParticles(struct HFA2 p1, float p2, struct HFA4 p3, int p4, struct HFA2 p5, float p6, float p7, int p8){ return p1;} +// X32: define x86_vectorcallcc %struct.HFA2 @"\01AddParticles@@84"(%struct.HFA2 inreg %p1.coerce, float %p2, %struct.HFA4* inreg %p3, i32 inreg %p4, %struct.HFA2* %p5, float %p6, float %p7, i32 %p8) +// X64: define x86_vectorcallcc %struct.HFA2 @"\01AddParticles@@104"(%struct.HFA2 inreg %p1.coerce, float %p2, %struct.HFA4* %p3, i32 %p4, %struct.HFA2 inreg %p5.coerce, float %p6, float %p7, i32 %p8) + +// Vectorcall in both architectures allows passing of an HVA as long as there is room, +// even if it is not one of the first 6 arguments. First pass puts p4 into a +// register on both. p9 ends up in a register in x86 only. Second pass puts p1 +// in a register, does NOT put p7 in a register (since theres no room), then puts +// p8 in a register. +void __vectorcall HVAAnywhere(struct HFA2 p1, int p2, int p3, float p4, int p5, int p6, struct HFA4 p7, struct HFA2 p8, float p9){} +// X32: define x86_vectorcallcc void @"\01HVAAnywhere@@88"(%struct.HFA2 inreg %p1.coerce, i32 inreg %p2, i32 inreg %p3, float %p4, i32 %p5, i32 %p6, %struct.HFA4* %p7, %struct.HFA2 inreg %p8.coerce, float %p9) +// X64: define x86_vectorcallcc void @"\01HVAAnywhere@@112"(%struct.HFA2 inreg %p1.coerce, i32 %p2, i32 %p3, float %p4, i32 %p5, i32 %p6, %struct.HFA4* %p7, %struct.HFA2 inreg %p8.coerce, float %p9) + Index: cfe/trunk/lib/CodeGen/TargetInfo.cpp === --- cfe/trunk/lib/CodeGen/TargetInfo.cpp +++ cfe/trunk/lib/CodeGen/TargetInfo.cpp @@ -951,8 +951,7 @@ Class classify(QualType Ty) const; ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; - ABIArgInfo reclassifyHvaArgType(QualType RetTy, CCState &State, - const ABIArgInfo& current) const; + /// \brief Updates the number of available free registers, returns /// true if any registers were allocated. bool updateFreeRegs(QualType Ty, CCState &State) const; @@ -1536,27 +1535,6 @@ return true; } -ABIArgInfo -X86_32ABIInfo::reclassifyHvaArgType(QualType Ty, CCState &State, -const ABIArgInfo ¤t) const { - // Assumes vectorCall calling convention. - const Type *Base = nullptr; - uint64_t NumElts = 0; - - if (!Ty->isBuiltinType() && !Ty->isVectorType() && - isHomogeneousAggregate(Ty, Base, NumElts)) { -if (State.FreeSSERegs >= NumElts) { - // HVA types get passed directly in registers if there is room. - State.FreeSSERegs -= NumElts; - return getDirectX86Hva(); -} -// If there's no room, the HVA gets passed as normal indirect -// structure. -return getIndirectResult(Ty, /*ByVal=*/false, State); - } - return current; -} - ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State) const { // FIXME: Set alignment on indirect arguments. @@ -1575,35 +1553,20 @@ } } - // vectorcall adds the concept of a homogenous vector aggregate, similar - // to other targets, regcall uses some of the
r305928 - Correct VectorCall x86 (32 bit) behavior for SSE Register Assignment
Author: erichkeane Date: Wed Jun 21 11:37:22 2017 New Revision: 305928 URL: http://llvm.org/viewvc/llvm-project?rev=305928&view=rev Log: Correct VectorCall x86 (32 bit) behavior for SSE Register Assignment In running some internal vectorcall tests in 32 bit mode, we discovered that the behavior I'd previously implemented for x64 (and applied to x32) regarding the assignment of SSE registers was incorrect. See spec here: https://msdn.microsoft.com/en-us/library/dn375768.aspx My previous implementation applied register argument position from the x64 version to both. This isn't correct for x86, so this removes and refactors that section. Additionally, it corrects the integer/int-pointer assignments. Unlike x64, x86 permits integers to be assigned independent of position. Finally, the code for 32 bit was cleaned up a little to clarify the intent, as well as given a descriptive comment. Differential Revision: https://reviews.llvm.org/D34455 Modified: cfe/trunk/lib/CodeGen/TargetInfo.cpp cfe/trunk/test/CodeGen/vectorcall.c Modified: cfe/trunk/lib/CodeGen/TargetInfo.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/TargetInfo.cpp?rev=305928&r1=305927&r2=305928&view=diff == --- cfe/trunk/lib/CodeGen/TargetInfo.cpp (original) +++ cfe/trunk/lib/CodeGen/TargetInfo.cpp Wed Jun 21 11:37:22 2017 @@ -951,8 +951,7 @@ class X86_32ABIInfo : public SwiftABIInf Class classify(QualType Ty) const; ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; - ABIArgInfo reclassifyHvaArgType(QualType RetTy, CCState &State, - const ABIArgInfo& current) const; + /// \brief Updates the number of available free registers, returns /// true if any registers were allocated. bool updateFreeRegs(QualType Ty, CCState &State) const; @@ -1536,27 +1535,6 @@ bool X86_32ABIInfo::shouldPrimitiveUseIn return true; } -ABIArgInfo -X86_32ABIInfo::reclassifyHvaArgType(QualType Ty, CCState &State, -const ABIArgInfo ¤t) const { - // Assumes vectorCall calling convention. - const Type *Base = nullptr; - uint64_t NumElts = 0; - - if (!Ty->isBuiltinType() && !Ty->isVectorType() && - isHomogeneousAggregate(Ty, Base, NumElts)) { -if (State.FreeSSERegs >= NumElts) { - // HVA types get passed directly in registers if there is room. - State.FreeSSERegs -= NumElts; - return getDirectX86Hva(); -} -// If there's no room, the HVA gets passed as normal indirect -// structure. -return getIndirectResult(Ty, /*ByVal=*/false, State); - } - return current; -} - ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState &State) const { // FIXME: Set alignment on indirect arguments. @@ -1575,35 +1553,20 @@ ABIArgInfo X86_32ABIInfo::classifyArgume } } - // vectorcall adds the concept of a homogenous vector aggregate, similar - // to other targets, regcall uses some of the HVA rules. + // Regcall uses the concept of a homogenous vector aggregate, similar + // to other targets. const Type *Base = nullptr; uint64_t NumElts = 0; - if ((State.CC == llvm::CallingConv::X86_VectorCall || - State.CC == llvm::CallingConv::X86_RegCall) && + if (State.CC == llvm::CallingConv::X86_RegCall && isHomogeneousAggregate(Ty, Base, NumElts)) { -if (State.CC == llvm::CallingConv::X86_RegCall) { - if (State.FreeSSERegs >= NumElts) { -State.FreeSSERegs -= NumElts; -if (Ty->isBuiltinType() || Ty->isVectorType()) - return ABIArgInfo::getDirect(); -return ABIArgInfo::getExpand(); - - } - return getIndirectResult(Ty, /*ByVal=*/false, State); -} else if (State.CC == llvm::CallingConv::X86_VectorCall) { - if (State.FreeSSERegs >= NumElts && (Ty->isBuiltinType() || Ty->isVectorType())) { -// Actual floating-point types get registers first time through if -// there is registers available -State.FreeSSERegs -= NumElts; +if (State.FreeSSERegs >= NumElts) { + State.FreeSSERegs -= NumElts; + if (Ty->isBuiltinType() || Ty->isVectorType()) return ABIArgInfo::getDirect(); - } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { -// HVA Types only get registers after everything else has been -// set, so it gets set as indirect for now. -return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty)); - } + return ABIArgInfo::getExpand(); } +return getIndirectResult(Ty, /*ByVal=*/false, State); } if (isAggregateTypeForABI(Ty)) { @@ -1684,31 +1647,53 @@ ABIArgInfo X86_32ABIInfo::classifyArgume void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
[PATCH] D34462: [index] "SpecializationOf" relation should be added even to forward declarations of class template specializations
arphaman created this revision. This patch fixes an issue where a forward declaration of a class template specialization was not related to the base template. We need to relate even forward declarations because specializations don't have to be defined. Repository: rL LLVM https://reviews.llvm.org/D34462 Files: lib/Index/IndexDecl.cpp test/Index/Core/index-source.cpp Index: test/Index/Core/index-source.cpp === --- test/Index/Core/index-source.cpp +++ test/Index/Core/index-source.cpp @@ -282,7 +282,9 @@ template<> class SpecializationDecl; -// CHECK: [[@LINE-1]]:7 | class(Gen)/C++ | SpecializationDecl | c:@ST>1#T@SpecializationDecl | | Ref | rel: 0 +// CHECK: [[@LINE-1]]:7 | class(Gen,TS)/C++ | SpecializationDecl | c:@S@SpecializationDecl>#I | | Decl,RelSpecialization | rel: 1 +// CHECK-NEXT: RelSpecialization | SpecializationDecl | c:@ST>1#T@SpecializationDecl +// CHECK: [[@LINE-3]]:7 | class(Gen)/C++ | SpecializationDecl | c:@ST>1#T@SpecializationDecl | | Ref | rel: 0 template<> class SpecializationDecl { }; @@ -292,8 +294,10 @@ template class PartialSpecilizationClass; -// CHECK: [[@LINE-1]]:7 | class(Gen)/C++ | PartialSpecilizationClass | c:@ST>2#T#T@PartialSpecilizationClass | | Ref | rel: 0 -// CHECK-NEXT: [[@LINE-2]]:33 | class/C++ | Cls | c:@S@Cls | | Ref | rel: 0 +// CHECK: [[@LINE-1]]:7 | class(Gen,TPS)/C++ | PartialSpecilizationClass | c:@SP>1#T@PartialSpecilizationClass>#$@S@Cls#t0.0 | | Decl,RelSpecialization | rel: 1 +// CHECK-NEXT: RelSpecialization | PartialSpecilizationClass | c:@ST>2#T#T@PartialSpecilizationClass +// CHECK: [[@LINE-3]]:7 | class(Gen)/C++ | PartialSpecilizationClass | c:@ST>2#T#T@PartialSpecilizationClass | | Ref | rel: 0 +// CHECK-NEXT: [[@LINE-4]]:33 | class/C++ | Cls | c:@S@Cls | | Ref | rel: 0 template<> class PartialSpecilizationClass : Cls { }; Index: lib/Index/IndexDecl.cpp === --- lib/Index/IndexDecl.cpp +++ lib/Index/IndexDecl.cpp @@ -611,18 +611,16 @@ ClassTemplateSpecializationDecl *D) { // FIXME: Notify subsequent callbacks if info comes from implicit // instantiation. -if (D->isThisDeclarationADefinition()) { - llvm::PointerUnion - Template = D->getSpecializedTemplateOrPartial(); - const Decl *SpecializationOf = - Template.is() - ? (Decl *)Template.get() - : Template.get(); - IndexCtx.indexTagDecl( - D, SymbolRelation(SymbolRoleSet(SymbolRole::RelationSpecializationOf), -SpecializationOf)); -} +llvm::PointerUnion +Template = D->getSpecializedTemplateOrPartial(); +const Decl *SpecializationOf = +Template.is() +? (Decl *)Template.get() +: Template.get(); +IndexCtx.indexTagDecl( +D, SymbolRelation(SymbolRoleSet(SymbolRole::RelationSpecializationOf), + SpecializationOf)); if (TypeSourceInfo *TSI = D->getTypeAsWritten()) IndexCtx.indexTypeSourceInfo(TSI, /*Parent=*/nullptr, D->getLexicalDeclContext()); Index: test/Index/Core/index-source.cpp === --- test/Index/Core/index-source.cpp +++ test/Index/Core/index-source.cpp @@ -282,7 +282,9 @@ template<> class SpecializationDecl; -// CHECK: [[@LINE-1]]:7 | class(Gen)/C++ | SpecializationDecl | c:@ST>1#T@SpecializationDecl | | Ref | rel: 0 +// CHECK: [[@LINE-1]]:7 | class(Gen,TS)/C++ | SpecializationDecl | c:@S@SpecializationDecl>#I | | Decl,RelSpecialization | rel: 1 +// CHECK-NEXT: RelSpecialization | SpecializationDecl | c:@ST>1#T@SpecializationDecl +// CHECK: [[@LINE-3]]:7 | class(Gen)/C++ | SpecializationDecl | c:@ST>1#T@SpecializationDecl | | Ref | rel: 0 template<> class SpecializationDecl { }; @@ -292,8 +294,10 @@ template class PartialSpecilizationClass; -// CHECK: [[@LINE-1]]:7 | class(Gen)/C++ | PartialSpecilizationClass | c:@ST>2#T#T@PartialSpecilizationClass | | Ref | rel: 0 -// CHECK-NEXT: [[@LINE-2]]:33 | class/C++ | Cls | c:@S@Cls | | Ref | rel: 0 +// CHECK: [[@LINE-1]]:7 | class(Gen,TPS)/C++ | PartialSpecilizationClass | c:@SP>1#T@PartialSpecilizationClass>#$@S@Cls#t0.0 | | Decl,RelSpecialization | rel: 1 +// CHECK-NEXT: RelSpecialization | PartialSpecilizationClass | c:@ST>2#T#T@PartialSpecilizationClass +// CHECK: [[@LINE-3]]:7 | class(Gen)/C++ | PartialSpecilizationClass | c:@ST>2#T#T@PartialSpecilizationClass | | Ref | rel: 0 +// CHECK-NEXT: [[@LINE-4]]:33 | class/C++ | Cls | c:@S@Cls | | Ref | rel: 0 template<> class PartialSpecilizationClass : Cls { }; Index: lib/Index/IndexDecl.cpp === --- lib/Index/IndexDecl.cpp +++ lib/Index/IndexDecl.cpp @@ -611,18 +611,16 @@
[PATCH] D34455: Correct VectorCall x86 (32 bit) behavior for SSE Register Assignment
erichkeane added a comment. Thanks Reid! Repository: rL LLVM https://reviews.llvm.org/D34455 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305930 - Use -NOT prefix instead of adding `not` to FileCheck.
Author: ruiu Date: Wed Jun 21 11:50:38 2017 New Revision: 305930 URL: http://llvm.org/viewvc/llvm-project?rev=305930&view=rev Log: Use -NOT prefix instead of adding `not` to FileCheck. If we want to make sure that a particular string is not in an output, the regular way of doing it is to add `-NOT` prefix instead of checking if FileCheck resulted in an error. Differential Revision: https://reviews.llvm.org/D34435 Modified: cfe/trunk/test/Driver/autocomplete.c Modified: cfe/trunk/test/Driver/autocomplete.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/autocomplete.c?rev=305930&r1=305929&r2=305930&view=diff == --- cfe/trunk/test/Driver/autocomplete.c (original) +++ cfe/trunk/test/Driver/autocomplete.c Wed Jun 21 11:50:38 2017 @@ -2,8 +2,8 @@ // FSYN: -fsyntax-only // RUN: %clang --autocomplete=-s | FileCheck %s -check-prefix=STD // STD: -std={{.*}}-stdlib= -// RUN: %clang --autocomplete=foo | not FileCheck %s -check-prefix=NONE -// NONE: foo +// RUN: %clang --autocomplete=foo | FileCheck %s -check-prefix=FOO +// FOO-NOT: foo // RUN: %clang --autocomplete=-stdlib=,l | FileCheck %s -check-prefix=STDLIB // STDLIB: libc++ libstdc++ // RUN: %clang --autocomplete=-stdlib=, | FileCheck %s -check-prefix=STDLIBALL ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34329: [GSoC] Clang AST diffing
arphaman added a comment. The API looks better IMHO. Some more comments: Comment at: include/clang/Tooling/ASTDiff/ASTDiff.h:57 +/// Within a tree, this identifies a node by its preorder offset. +using NodeId = int; + I think that it's better to make make `NodeId` a structure as well and make `InvalidNodeId` a private member. I suggest the following interface for `NodeId`: ``` struct NodeId { private: static const int InvalidNodeId; public: int Id; NodeId() : Id(InvalidNodeId) { } NodeId(int Id) : Id(Id) { } bool isValid() const { return Id != InvalidNodeId; } bool isInvalid() const { return Id == InvalidNodeId; } }; ``` This way you'll get rid of a couple of variable initializations that use `InvalidNodeId`. You also won't need to call the `memset` when creating the unique pointer array of `NodeId`s. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:33 +/// Supports fast insertion and lookup. +class Mapping { +public: Mapping should use the C++ move semantics IMHO. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:35 +public: + bool Done = false; + Mapping() = default; This field is used only in `TreeComparator`, so you might as well move it there and rename to something like `IsMappingDone`. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:318 +return ""; + if (auto *X = DTN.get()) +llvm_unreachable("Types are not included.\n"); We don't really need this check. Let's use just one unreachable here. Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:638 + NodeId Id2) const { + const Node &N1 = T1.getNode(Id1); + const Node &N2 = T2.getNode(Id2); I think this function would would be clearer and faster (you'll be able to avoid redundant work) if you use early exists for the main conditions of the `return`, e.g.: `if (M.hasSrc(Id1) || M.hasDst(Id2)) return false; // Both nodes must not be mapped.` And so on. https://reviews.llvm.org/D34329 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34439: Add GCC's noexcept-type alias for c++1z-compat-mangling
ahatanak added a comment. I didn't know gcc had its own option. This change seems reasonable to me. Since c++1z-compat-mangling was added just a few days ago, should we just rename it instead of adding an alias? https://reviews.llvm.org/D34439 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34342: [OpenCL] Fix code generation of function-scope constant samplers.
bader updated this revision to Diff 103421. bader added a comment. This revision is now accepted and ready to land. Added test case reproducing the issue described in the description. Removed test cases from test/SemaOpenCL/sampler_t.cl covered by test/CodeGenOpenCL/sampler.cl. While I was moving one test case from test/SemaOpenCL/sampler_t.cl, I found another bug in CodeGen library that crashes the compilation if sampler is initialized with non-constant expression. Here is a short reproducer: int get_sampler_initializer(void); kernel void foo() { const sampler_t const_smp_func_init = get_sampler_initializer(); } The problem is that clang does not discard this code as invalid, but CodeGen library expects sampler initializer to be a constant expression: llvm::Value * CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF) { llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF); // for the reproducer expression here is CallExpr. auto SamplerT = getOpenCLRuntime().getSamplerType(); auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); } There are two ways to handle this issue: 1. Implement diagnostics allowing only compile time constant initializers. 2. Add non-constant sampler initializer support to CodeGen library. OpenCL specification examples give me impression that samplers declared inside OpenCL programs must be known at compile time. On the other hand OpenCL allows samplers passed via kernel parameters to be unknown at compile time. Thoughts? https://reviews.llvm.org/D34342 Files: lib/CodeGen/CGDecl.cpp test/CodeGenOpenCL/sampler.cl test/SemaOpenCL/sampler_t.cl Index: test/SemaOpenCL/sampler_t.cl === --- test/SemaOpenCL/sampler_t.cl +++ test/SemaOpenCL/sampler_t.cl @@ -46,36 +46,11 @@ void kernel ker(sampler_t argsmp) { local sampler_t smp; // expected-error{{sampler type cannot be used with the __local and __global address space qualifiers}} - const sampler_t const_smp = CLK_ADDRESS_CLAMP_TO_EDGE | CLK_NORMALIZED_COORDS_TRUE | CLK_FILTER_LINEAR; - const sampler_t const_smp2; - const sampler_t const_smp3 = const_smp; - const sampler_t const_smp4 = f(); const sampler_t const_smp5 = 1.0f; // expected-error{{initializing 'const sampler_t' with an expression of incompatible type 'float'}} const sampler_t const_smp6 = 0x1LL; // expected-error{{sampler_t initialization requires 32-bit integer, not 'long long'}} - foo(glb_smp); - foo(glb_smp2); - foo(glb_smp3); - foo(glb_smp4); - foo(glb_smp5); - foo(glb_smp6); - foo(glb_smp7); - foo(glb_smp8); - foo(glb_smp9); - foo(smp); - foo(sampler_str.smp); - foo(const_smp); - foo(const_smp2); - foo(const_smp3); - foo(const_smp4); - foo(const_smp5); - foo(const_smp6); - foo(argsmp); - foo(5); foo(5.0f); // expected-error {{passing 'float' to parameter of incompatible type 'sampler_t'}} - sampler_t sa[] = {argsmp, const_smp}; // expected-error {{array of 'sampler_t' type is invalid in OpenCL}} - foo(sa[0]); - foo(bad()); + sampler_t sa[] = {argsmp, glb_smp}; // expected-error {{array of 'sampler_t' type is invalid in OpenCL}} } void bad(sampler_t*); // expected-error{{pointer to type 'sampler_t' is invalid in OpenCL}} Index: test/CodeGenOpenCL/sampler.cl === --- test/CodeGenOpenCL/sampler.cl +++ test/CodeGenOpenCL/sampler.cl @@ -20,6 +20,8 @@ constant sampler_t glb_smp = CLK_ADDRESS_CLAMP_TO_EDGE | CLK_NORMALIZED_COORDS_TRUE | CLK_FILTER_LINEAR; // CHECK-NOT: glb_smp +int get_sampler_initializer(void); + void fnc4smp(sampler_t s) {} // CHECK: define spir_func void @fnc4smp(%opencl.sampler_t addrspace(2)* % @@ -58,4 +60,20 @@ fnc4smp(5); // CHECK: [[SAMP:%[0-9]+]] = call %opencl.sampler_t addrspace(2)* @__translate_sampler_initializer(i32 5) // CHECK: call spir_func void @fnc4smp(%opencl.sampler_t addrspace(2)* [[SAMP]]) + + const sampler_t const_smp = CLK_ADDRESS_CLAMP_TO_EDGE | CLK_NORMALIZED_COORDS_TRUE | CLK_FILTER_LINEAR; + fnc4smp(const_smp); + // CHECK: [[CONST_SAMP:%[0-9]+]] = call %opencl.sampler_t addrspace(2)* @__translate_sampler_initializer(i32 35) + // CHECK: store %opencl.sampler_t addrspace(2)* [[CONST_SAMP]], %opencl.sampler_t addrspace(2)** [[CONST_SMP_PTR:%[a-zA-Z0-9]+]] + fnc4smp(const_smp); + // CHECK: [[SAMP:%[0-9]+]] = load %opencl.sampler_t addrspace(2)*, %opencl.sampler_t addrspace(2)** [[CONST_SMP_PTR]] + // CHECK: call spir_func void @fnc4smp(%opencl.sampler_t addrspace(2)* [[SAMP]]) + + constant sampler_t constant_smp = CLK_ADDRESS_CLAMP_TO_EDGE | CLK_NORMALIZED_COORDS_TRUE | CLK_FILTER_LINEAR; +
Re: [PATCH] D34439: Add GCC's noexcept-type alias for c++1z-compat-mangling
Does the GCC warning warn on the same cases? On 21 Jun 2017 10:24 am, "Akira Hatanaka via Phabricator" < revi...@reviews.llvm.org> wrote: > ahatanak added a comment. > > I didn't know gcc had its own option. This change seems reasonable to me. > > Since c++1z-compat-mangling was added just a few days ago, should we just > rename it instead of adding an alias? > > > https://reviews.llvm.org/D34439 > > > > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: [PATCH] D34439: Add GCC's noexcept-type alias for c++1z-compat-mangling
I couldn't find a case where both gcc and clang agreed at the same time that they should emit this warning, but I think that's just bugs in the way we detect these cases. From the near-identical warning message I would say they both should emit warnings for the same cases (and probably will in the future). 2017-06-21 19:41 GMT+02:00 Richard Smith : > Does the GCC warning warn on the same cases? > > On 21 Jun 2017 10:24 am, "Akira Hatanaka via Phabricator" > wrote: >> >> ahatanak added a comment. >> >> I didn't know gcc had its own option. This change seems reasonable to me. >> >> Since c++1z-compat-mangling was added just a few days ago, should we just >> rename it instead of adding an alias? >> >> >> https://reviews.llvm.org/D34439 >> >> >> > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34439: Add GCC's noexcept-type alias for c++1z-compat-mangling
teemperor added a comment. @ahatanak I think we can leave the more expressive clang name for this warning and just add the bit cryptic GCC name for compability. But I don't have a strong opinion on this. https://reviews.llvm.org/D34439 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34198: Fix __has_trivial_destructor crash when the type is incomplete with unknown array bounds.
rjmccall added inline comments. Comment at: lib/Sema/SemaExprCXX.cpp:4128 +return true; +} + puneetha wrote: > rjmccall wrote: > > I don't understand the difference you're creating between traits here. > > Three specific traits about destructibility allow incomplete array types > > regardless of whether the base type is incomplete, but the rest do not? > > > > Anyway, I think what you want here is basically just: > > > > if (auto ArrayTy = S.Context.getAsIncompleteArrayType(ArgTy)) { > > ArgTy = ArrayTy->getElementType(); > > } > Of my understanding, these traits are defined by MSVC. There is no mention of > them in the GCC type-traits documentation. For these traits, GCC lets us pass > an array of incomplete bounds for any base type, complete or incomplete. > > Please correct me if I am wrong. I see. If we're matching GCC bug-for-bug, it doesn't really matter if the behavior seems inconsistent. https://reviews.llvm.org/D34198 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34329: [GSoC] Clang AST diffing
johannes updated this revision to Diff 103432. https://reviews.llvm.org/D34329 Files: include/clang/Tooling/ASTDiff/ASTDiff.h lib/Tooling/ASTDiff/ASTDiff.cpp lib/Tooling/ASTDiff/CMakeLists.txt lib/Tooling/CMakeLists.txt test/Tooling/clang-diff-basic.cpp tools/CMakeLists.txt tools/clang-diff/CMakeLists.txt tools/clang-diff/ClangDiff.cpp Index: tools/clang-diff/ClangDiff.cpp === --- /dev/null +++ tools/clang-diff/ClangDiff.cpp @@ -0,0 +1,107 @@ +//===- ClangDiff.cpp - compare source files by AST nodes --*- C++ -*- -===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// +// +// This file implements a tool for syntax tree based comparison using +// Tooling/ASTDiff. +// +//===--===// + +#include "clang/Tooling/ASTDiff/ASTDiff.h" +#include "clang/Tooling/CommonOptionsParser.h" +#include "clang/Tooling/Tooling.h" +#include "llvm/Support/CommandLine.h" + +using namespace llvm; +using namespace clang; +using namespace tooling; + +static cl::OptionCategory ClangDiffCategory("clang-diff options"); + +static cl::opt +DumpAST("ast-dump", +cl::desc("Print the internal representation of the AST as JSON."), +cl::init(false), cl::cat(ClangDiffCategory)); + +static cl::opt NoCompilationDatabase( +"no-compilation-database", +cl::desc( +"Do not attempt to load build settigns from a compilation database"), +cl::init(false), cl::cat(ClangDiffCategory)); + +static cl::opt SourcePath(cl::Positional, cl::desc(""), + cl::Required, + cl::cat(ClangDiffCategory)); + +static cl::opt DestinationPath(cl::Positional, +cl::desc(""), +cl::Optional, +cl::cat(ClangDiffCategory)); + +static std::unique_ptr getAST(const StringRef Filename) { + std::string ErrorMessage; + std::unique_ptr Compilations; + if (!NoCompilationDatabase) +Compilations = +CompilationDatabase::autoDetectFromSource(Filename, ErrorMessage); + if (!Compilations) { +if (!NoCompilationDatabase) + llvm::errs() + << "Error while trying to load a compilation database, running " + "without flags.\n" + << ErrorMessage; +Compilations.reset( +new FixedCompilationDatabase(".", std::vector())); + } + std::array Files = {{Filename}}; + ClangTool Tool(*Compilations, Files); + std::vector> ASTs; + Tool.buildASTs(ASTs); + if (ASTs.size() != Files.size()) +return nullptr; + return std::move(ASTs[0]); +} + +int main(int argc, const char **argv) { + cl::HideUnrelatedOptions(ClangDiffCategory); + if (!cl::ParseCommandLineOptions(argc, argv)) { +cl::PrintOptionValues(); +return 1; + } + + if (DumpAST) { +if (!DestinationPath.empty()) { + llvm::errs() << "Error: Please specify exactly one filename.\n"; + return 1; +} +std::unique_ptr AST = getAST(SourcePath); +if (!AST) + return 1; +clang::diff::TreeRoot Tree(AST->getASTContext()); +Tree.printAsJson(); +return 0; + } + + if (DestinationPath.empty()) { +llvm::errs() << "Error: Exactly two paths are required.\n"; +return 1; + } + + std::unique_ptr Src = getAST(SourcePath); + std::unique_ptr Dst = getAST(DestinationPath); + if (!Src || !Dst) +return 1; + + diff::ASTDiff DiffTool(Src->getASTContext(), Dst->getASTContext()); + for (const auto &Match : DiffTool.getMatches()) +DiffTool.printMatch(Match); + for (const auto &Change : DiffTool.getChanges()) +DiffTool.printChange(Change); + + return 0; +} Index: tools/clang-diff/CMakeLists.txt === --- /dev/null +++ tools/clang-diff/CMakeLists.txt @@ -0,0 +1,13 @@ +set(LLVM_LINK_COMPONENTS + Support + ) + +add_clang_executable(clang-diff + ClangDiff.cpp + ) + +target_link_libraries(clang-diff + clangFrontend + clangTooling + clangToolingASTDiff + ) Index: tools/CMakeLists.txt === --- tools/CMakeLists.txt +++ tools/CMakeLists.txt @@ -2,6 +2,7 @@ add_clang_subdirectory(diagtool) add_clang_subdirectory(driver) +add_clang_subdirectory(clang-diff) add_clang_subdirectory(clang-format) add_clang_subdirectory(clang-format-vs) add_clang_subdirectory(clang-fuzzer) Index: test/Tooling/clang-diff-basic.cpp === --- /dev/null +++ test/Tooling/clang-diff-basic.cpp @@ -0,0 +1,61 @@ +// RUN: %clang_cc1 -E %s > %T/src.cpp +// RUN: %clang_cc1 -E
r305940 - [preprocessor] Fix assertion hit when 'SingleFileParseMode' option is enabled and #if with an undefined identifier and without #else
Author: akirtzidis Date: Wed Jun 21 13:52:44 2017 New Revision: 305940 URL: http://llvm.org/viewvc/llvm-project?rev=305940&view=rev Log: [preprocessor] Fix assertion hit when 'SingleFileParseMode' option is enabled and #if with an undefined identifier and without #else 'HandleEndifDirective' asserts that 'WasSkipping' is false, so switch to using 'FoundNonSkip' as the hint for 'SingleFileParseMode' to keep going with parsing. Modified: cfe/trunk/lib/Lex/PPDirectives.cpp cfe/trunk/test/Index/single-file-parse.m Modified: cfe/trunk/lib/Lex/PPDirectives.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPDirectives.cpp?rev=305940&r1=305939&r2=305940&view=diff == --- cfe/trunk/lib/Lex/PPDirectives.cpp (original) +++ cfe/trunk/lib/Lex/PPDirectives.cpp Wed Jun 21 13:52:44 2017 @@ -2658,7 +2658,7 @@ void Preprocessor::HandleIfdefDirective( // In 'single-file-parse mode' undefined identifiers trigger parsing of all // the directive blocks. CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), - /*wasskip*/true, /*foundnonskip*/false, + /*wasskip*/false, /*foundnonskip*/false, /*foundelse*/false); } else if (!MI == isIfndef) { // Yes, remember that we are inside a conditional, then lex the next token. @@ -2705,7 +2705,7 @@ void Preprocessor::HandleIfDirective(Tok if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) { // In 'single-file-parse mode' undefined identifiers trigger parsing of all // the directive blocks. -CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/true, +CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false, /*foundnonskip*/false, /*foundelse*/false); } else if (ConditionalTrue) { // Yes, remember that we are inside a conditional, then lex the next token. @@ -2768,11 +2768,11 @@ void Preprocessor::HandleElseDirective(T if (Callbacks) Callbacks->Else(Result.getLocation(), CI.IfLoc); - if (PPOpts->SingleFileParseMode && CI.WasSkipping) { + if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) { // In 'single-file-parse mode' undefined identifiers trigger parsing of all // the directive blocks. CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false, - /*foundnonskip*/true, /*foundelse*/true); + /*foundnonskip*/false, /*foundelse*/true); return; } @@ -2811,10 +2811,10 @@ void Preprocessor::HandleElifDirective(T SourceRange(ConditionalBegin, ConditionalEnd), PPCallbacks::CVK_NotEvaluated, CI.IfLoc); - if (PPOpts->SingleFileParseMode && CI.WasSkipping) { + if (PPOpts->SingleFileParseMode && !CI.FoundNonSkip) { // In 'single-file-parse mode' undefined identifiers trigger parsing of all // the directive blocks. -CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/true, +CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false, /*foundnonskip*/false, /*foundelse*/false); return; } Modified: cfe/trunk/test/Index/single-file-parse.m URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/single-file-parse.m?rev=305940&r1=305939&r2=305940&view=diff == --- cfe/trunk/test/Index/single-file-parse.m (original) +++ cfe/trunk/test/Index/single-file-parse.m Wed Jun 21 13:52:44 2017 @@ -109,3 +109,13 @@ // CHECK: [[@LINE+1]]:12: ObjCInterfaceDecl=Test28 @interface Test28 @end #endif + +#if SOMETHING_NOT_DEFINED +// CHECK: [[@LINE+1]]:12: ObjCInterfaceDecl=Test29 +@interface Test29 @end +#endif + +#ifdef SOMETHING_NOT_DEFINED +// CHECK: [[@LINE+1]]:12: ObjCInterfaceDecl=Test30 +@interface Test30 @end +#endif ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34329: [GSoC] Clang AST diffing
johannes added inline comments. Comment at: include/clang/Tooling/ASTDiff/ASTDiff.h:57 +/// Within a tree, this identifies a node by its preorder offset. +using NodeId = int; + arphaman wrote: > I think that it's better to make make `NodeId` a structure as well and make > `InvalidNodeId` a private member. I suggest the following interface for > `NodeId`: > > ``` > struct NodeId { > private: > static const int InvalidNodeId; > public: > int Id; > > NodeId() : Id(InvalidNodeId) { } > NodeId(int Id) : Id(Id) { } > > bool isValid() const { return Id != InvalidNodeId; } > bool isInvalid() const { return Id == InvalidNodeId; } > }; > ``` > > > This way you'll get rid of a couple of variable initializations that use > `InvalidNodeId`. You also won't need to call the `memset` when creating the > unique pointer array of `NodeId`s. Ok, I did it like this. Can I create a header file inside lib/Tooling/ASTDiff and include it from the public interface? This would help reduce the clutter. Instead of NodeId we could also just use references / pointer types. I don't see any particularly good reason for choosing either one above the other. I guess indices make it more obvious how to compute the number of descendants and such. On the other hand, when using reference types, there is less boilerplate to write for loops. https://reviews.llvm.org/D34329 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34469: Use vfs::FileSystem in ASTUnit when creating CompilerInvocation.
ilya-biryukov created this revision. It used to always call into the RealFileSystem before. https://reviews.llvm.org/D34469 Files: include/clang/Frontend/Utils.h lib/Frontend/ASTUnit.cpp lib/Frontend/CreateInvocationFromCommandLine.cpp Index: lib/Frontend/CreateInvocationFromCommandLine.cpp === --- lib/Frontend/CreateInvocationFromCommandLine.cpp +++ lib/Frontend/CreateInvocationFromCommandLine.cpp @@ -31,8 +31,8 @@ /// \return A CompilerInvocation, or 0 if none was built for the given /// argument vector. std::unique_ptr clang::createInvocationFromCommandLine( -ArrayRef ArgList, -IntrusiveRefCntPtr Diags) { +ArrayRef ArgList, IntrusiveRefCntPtr Diags, +IntrusiveRefCntPtr VFS) { if (!Diags.get()) { // No diagnostics engine was provided, so create our own diagnostics object // with the default options. @@ -46,7 +46,7 @@ // FIXME: We shouldn't have to pass in the path info. driver::Driver TheDriver(Args[0], llvm::sys::getDefaultTargetTriple(), - *Diags); + *Diags, VFS); // Don't check that inputs exist, they may have been remapped. TheDriver.setCheckInputsExist(false); Index: lib/Frontend/ASTUnit.cpp === --- lib/Frontend/ASTUnit.cpp +++ lib/Frontend/ASTUnit.cpp @@ -1638,7 +1638,7 @@ &StoredDiagnostics, nullptr); CI = clang::createInvocationFromCommandLine( -llvm::makeArrayRef(ArgBegin, ArgEnd), Diags); +llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS); if (!CI) return nullptr; } Index: include/clang/Frontend/Utils.h === --- include/clang/Frontend/Utils.h +++ include/clang/Frontend/Utils.h @@ -184,10 +184,11 @@ /// /// \return A CompilerInvocation, or 0 if none was built for the given /// argument vector. -std::unique_ptr -createInvocationFromCommandLine(ArrayRef Args, -IntrusiveRefCntPtr Diags = -IntrusiveRefCntPtr()); +std::unique_ptr createInvocationFromCommandLine( +ArrayRef Args, +IntrusiveRefCntPtr Diags = +IntrusiveRefCntPtr(), +IntrusiveRefCntPtr VFS = nullptr); /// Return the value of the last argument as an integer, or a default. If Diags /// is non-null, emits an error if the argument is given, but non-integral. Index: lib/Frontend/CreateInvocationFromCommandLine.cpp === --- lib/Frontend/CreateInvocationFromCommandLine.cpp +++ lib/Frontend/CreateInvocationFromCommandLine.cpp @@ -31,8 +31,8 @@ /// \return A CompilerInvocation, or 0 if none was built for the given /// argument vector. std::unique_ptr clang::createInvocationFromCommandLine( -ArrayRef ArgList, -IntrusiveRefCntPtr Diags) { +ArrayRef ArgList, IntrusiveRefCntPtr Diags, +IntrusiveRefCntPtr VFS) { if (!Diags.get()) { // No diagnostics engine was provided, so create our own diagnostics object // with the default options. @@ -46,7 +46,7 @@ // FIXME: We shouldn't have to pass in the path info. driver::Driver TheDriver(Args[0], llvm::sys::getDefaultTargetTriple(), - *Diags); + *Diags, VFS); // Don't check that inputs exist, they may have been remapped. TheDriver.setCheckInputsExist(false); Index: lib/Frontend/ASTUnit.cpp === --- lib/Frontend/ASTUnit.cpp +++ lib/Frontend/ASTUnit.cpp @@ -1638,7 +1638,7 @@ &StoredDiagnostics, nullptr); CI = clang::createInvocationFromCommandLine( -llvm::makeArrayRef(ArgBegin, ArgEnd), Diags); +llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS); if (!CI) return nullptr; } Index: include/clang/Frontend/Utils.h === --- include/clang/Frontend/Utils.h +++ include/clang/Frontend/Utils.h @@ -184,10 +184,11 @@ /// /// \return A CompilerInvocation, or 0 if none was built for the given /// argument vector. -std::unique_ptr -createInvocationFromCommandLine(ArrayRef Args, -IntrusiveRefCntPtr Diags = -IntrusiveRefCntPtr()); +std::unique_ptr createInvocationFromCommandLine( +ArrayRef Args, +IntrusiveRefCntPtr Diags = +IntrusiveRefCntPtr(), +IntrusiveRefCntPtr VFS = nullptr); /// Return the value of the last argument as an integer, or a default. If Diags /// is non-null, emits an error if the argument is given, but non-integral. ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34470: [clangd] Allow to override resource dir in ClangdServer.
ilya-biryukov created this revision. https://reviews.llvm.org/D34470 Files: clangd/ClangdServer.cpp clangd/ClangdServer.h clangd/ClangdUnit.cpp clangd/ClangdUnit.h clangd/ClangdUnitStore.h Index: clangd/ClangdUnitStore.h === --- clangd/ClangdUnitStore.h +++ clangd/ClangdUnitStore.h @@ -30,32 +30,34 @@ /// store, ClangdUnit::reparse will be called with the new contents before /// running \p Action. template - void runOnUnit(PathRef File, StringRef FileContents, + void runOnUnit(PathRef File, StringRef FileContents, StringRef ResourceDir, GlobalCompilationDatabase &CDB, std::shared_ptr PCHs, IntrusiveRefCntPtr VFS, Func Action) { -runOnUnitImpl(File, FileContents, CDB, PCHs, /*ReparseBeforeAction=*/true, - VFS, std::forward(Action)); +runOnUnitImpl(File, FileContents, ResourceDir, CDB, PCHs, + /*ReparseBeforeAction=*/true, VFS, + std::forward(Action)); } /// Run specified \p Action on the ClangdUnit for \p File. /// If the file is not present in ClangdUnitStore, a new ClangdUnit will be /// created from the \p FileContents. If the file is already present in the /// store, the \p Action will be run directly on it. template void runOnUnitWithoutReparse(PathRef File, StringRef FileContents, + StringRef ResourceDir, GlobalCompilationDatabase &CDB, std::shared_ptr PCHs, IntrusiveRefCntPtr VFS, Func Action) { -runOnUnitImpl(File, FileContents, CDB, PCHs, /*ReparseBeforeAction=*/false, - VFS, std::forward(Action)); +runOnUnitImpl(File, FileContents, ResourceDir, CDB, PCHs, + /*ReparseBeforeAction=*/false, VFS, + std::forward(Action)); } /// Run the specified \p Action on the ClangdUnit for \p File. /// Unit for \p File should exist in the store. - template - void runOnExistingUnit(PathRef File, Func Action) { + template void runOnExistingUnit(PathRef File, Func Action) { std::lock_guard Lock(Mutex); auto It = OpenedFiles.find(File); @@ -71,7 +73,7 @@ /// Run specified \p Action on the ClangdUnit for \p File. template void runOnUnitImpl(PathRef File, StringRef FileContents, - GlobalCompilationDatabase &CDB, + StringRef ResourceDir, GlobalCompilationDatabase &CDB, std::shared_ptr PCHs, bool ReparseBeforeAction, IntrusiveRefCntPtr VFS, Func Action) { @@ -85,8 +87,9 @@ auto It = OpenedFiles.find(File); if (It == OpenedFiles.end()) { It = OpenedFiles - .insert(std::make_pair( - File, ClangdUnit(File, FileContents, PCHs, Commands, VFS))) + .insert(std::make_pair(File, ClangdUnit(File, FileContents, + ResourceDir, PCHs, + Commands, VFS))) .first; } else if (ReparseBeforeAction) { It->second.reparse(FileContents, VFS); Index: clangd/ClangdUnit.h === --- clangd/ClangdUnit.h +++ clangd/ClangdUnit.h @@ -44,7 +44,7 @@ /// would want to perform on parsed C++ files. class ClangdUnit { public: - ClangdUnit(PathRef FileName, StringRef Contents, + ClangdUnit(PathRef FileName, StringRef Contents, StringRef ResourceDir, std::shared_ptr PCHs, std::vector Commands, IntrusiveRefCntPtr VFS); Index: clangd/ClangdUnit.cpp === --- clangd/ClangdUnit.cpp +++ clangd/ClangdUnit.cpp @@ -19,18 +19,16 @@ using namespace clang; ClangdUnit::ClangdUnit(PathRef FileName, StringRef Contents, + StringRef ResourceDir, std::shared_ptr PCHs, std::vector Commands, IntrusiveRefCntPtr VFS) : FileName(FileName), PCHs(PCHs) { assert(!Commands.empty() && "No compile commands provided"); // Inject the resource dir. // FIXME: Don't overwrite it if it's already there. - static int Dummy; // Just an address in this process. - std::string ResourceDir = - CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy); - Commands.front().CommandLine.push_back("-resource-dir=" + ResourceDir); + Commands.front().CommandLine.push_back("-resource-dir=" + std::string(ResourceDir)); IntrusiveRefCntPtr Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions); Index: clangd/ClangdServer.h === --- clangd/ClangdServer.h +++ clangd/
[PATCH] D34269: [clangd] Add "Go to Declaration" functionality
ilya-biryukov added a comment. Looks good now, but I think we definitely need to change `unique_ptr>` to `vector` before submitting it. I won't be available until next Wednesday, so feel free to submit without my final approval. Comment at: clangd/ClangdUnit.cpp:276 +class DeclarationLocationsFinder : public index::IndexDataConsumer { + std::unique_ptr> DeclarationLocations; + const SourceLocation &SearchedLocation; Why do we need to use `unique_ptr>` here and in other places instead of `vector`? Comment at: clangd/DeclarationLocationsFinder.cpp:48 + // This can happen when nodes in the AST are visited twice. + if (std::none_of(DeclarationLocations.begin(), DeclarationLocations.end(), + [&L](const Location& Loc) { malaperle-ericsson wrote: > ilya-biryukov wrote: > > ilya-biryukov wrote: > > > Is it possible for DeclarationLocation to become large, so that quadratic > > > behavior is observed? > > > > > > If not, maybe add an assert that it's smaller than some threshold? > > > If yes, maybe use std::set instead of std::vector or use vector and later > > > std::sort and std::unique in the end? > > Maybe use std::find instead of std::none_of? > > ``` > > std::find(DeclarationLocations.begin(), DeclarationLocations.end(), L) == > > DeclarationLocations.end() > > ``` > I went with std::sort/std::unique. I don't think this will ever be large but > I don't think it would be good to have an arbitrary limit either. I think > keeping the vector and cleaning it later is nice and simple. Totally agree, nice and simple. Comment at: clangd/DeclarationLocationsFinder.cpp:59 + Token Result; + if (!Lexer::getRawToken(SearchedLocation, Result, Unit.getSourceManager(), + Unit.getASTContext().getLangOpts(), false)) { malaperle-ericsson wrote: > ilya-biryukov wrote: > > Could we implement ` handleMacroOccurence` instead? > > I suspect current code won't work if macro is undef'ed/redefined later: > > > > ``` > > #define FOO 123 > > > > int b = FO|O; > > > > #define FOO 125 > > // or > > // #undef FOO > > ``` > > > > Maybe also add this to tests? > You're right! It didn't work properly in this case. I added a few tests. > For handleMacroOccurence, it actually isn't even called so we'd have to > improve the clangIndex code to do this. I think this is a good first step > though. Awesome! clangIndex indeed never calls `handleMacroOccurence`, I wonder why it's there in the first place. Comment at: test/clangd/definitions.test:1 +# RUN: clangd -run-synchronously < %s | FileCheck %s +# It is absolutely vital that this file has CRLF line endings. malaperle-ericsson wrote: > ilya-biryukov wrote: > > Could we also add more readable tests specifically for that? > > I propose to have a tool that could read files like: > > ``` > > int aaa; > > int b = a/*{l1}*/aa; > > int c = /*{l2}*/b; > > ``` > > > > And have it output the resulting goto results: > > ``` > > l1 -> {main.cpp:0:4} int |aaa; > > l2 -> {main.cpp:1:4} int |b; > > ``` > > And we could also have a tool that prints expected clangd input/output > > based on that to check that action actually works. > > It's not directly relevant to this patch, though. Just random thoughts of > > what we should do for easier testing. > I think it's a good idea! Although I wonder if it's a bit too much work for > something that very specific to "textDocument/definition". I fully agree that > the tests need to be more readable and it would be worth a try! We could also reuse most of the code for all caret-based action, so it's actually useful for other things as well. https://reviews.llvm.org/D34269 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34269: [clangd] Add "Go to Declaration" functionality
malaperle-ericsson added inline comments. Comment at: clangd/ClangdUnit.cpp:276 +class DeclarationLocationsFinder : public index::IndexDataConsumer { + std::unique_ptr> DeclarationLocations; + const SourceLocation &SearchedLocation; ilya-biryukov wrote: > Why do we need to use `unique_ptr>` here and in other places > instead of `vector`? It was to implement "takeLocations". Calling it claims ownship of the vector. Did you have something else in mind when you suggested to implement takeLocations with a std::move? Disclaimer: this c++11 stuff is all new to me so I wouldn't be surprised if I'm doing it in a terrible way. https://reviews.llvm.org/D34269 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34269: [clangd] Add "Go to Declaration" functionality
malaperle-ericsson added inline comments. Comment at: clangd/ClangdUnit.cpp:276 +class DeclarationLocationsFinder : public index::IndexDataConsumer { + std::unique_ptr> DeclarationLocations; + const SourceLocation &SearchedLocation; malaperle-ericsson wrote: > ilya-biryukov wrote: > > Why do we need to use `unique_ptr>` here and in other > > places instead of `vector`? > It was to implement "takeLocations". Calling it claims ownship of the vector. > Did you have something else in mind when you suggested to implement > takeLocations with a std::move? Disclaimer: this c++11 stuff is all new to me > so I wouldn't be surprised if I'm doing it in a terrible way. I guess I can make takeLocations return a vector&& and the other places will return a normal vector RVO will take care of not making copies? https://reviews.llvm.org/D34269 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305947 - [test] Make absolute line numbers relative; NFC
Author: gbiv Date: Wed Jun 21 14:59:05 2017 New Revision: 305947 URL: http://llvm.org/viewvc/llvm-project?rev=305947&view=rev Log: [test] Make absolute line numbers relative; NFC Done to remove noise from https://reviews.llvm.org/D32332 (and to make this test more resilient to changes in general). Modified: cfe/trunk/test/Sema/overloadable.c Modified: cfe/trunk/test/Sema/overloadable.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/overloadable.c?rev=305947&r1=305946&r2=305947&view=diff == --- cfe/trunk/test/Sema/overloadable.c (original) +++ cfe/trunk/test/Sema/overloadable.c Wed Jun 21 14:59:05 2017 @@ -106,8 +106,8 @@ void fn_type_conversions() { void foo(char *c) __attribute__((overloadable)); void (*ptr1)(void *) = &foo; void (*ptr2)(char *) = &foo; - void (*ambiguous)(int *) = &foo; // expected-error{{initializing 'void (*)(int *)' with an expression of incompatible type ''}} expected-note@105{{candidate function}} expected-note@106{{candidate function}} - void *vp_ambiguous = &foo; // expected-error{{initializing 'void *' with an expression of incompatible type ''}} expected-note@105{{candidate function}} expected-note@106{{candidate function}} + void (*ambiguous)(int *) = &foo; // expected-error{{initializing 'void (*)(int *)' with an expression of incompatible type ''}} expected-note@-4{{candidate function}} expected-note@-3{{candidate function}} + void *vp_ambiguous = &foo; // expected-error{{initializing 'void *' with an expression of incompatible type ''}} expected-note@-5{{candidate function}} expected-note@-4{{candidate function}} void (*specific1)(int *) = (void (*)(void *))&foo; // expected-warning{{incompatible function pointer types initializing 'void (*)(int *)' with an expression of type 'void (*)(void *)'}} void *specific2 = (void (*)(void *))&foo; @@ -117,8 +117,8 @@ void fn_type_conversions() { void disabled(char *c) __attribute__((overloadable, enable_if(1, "The function name lies."))); // To be clear, these should all point to the last overload of 'disabled' void (*dptr1)(char *c) = &disabled; - void (*dptr2)(void *c) = &disabled; // expected-warning{{incompatible pointer types initializing 'void (*)(void *)' with an expression of type ''}} expected-note@115{{candidate function made ineligible by enable_if}} expected-note@116{{candidate function made ineligible by enable_if}} expected-note@117{{candidate function has type mismatch at 1st parameter (expected 'void *' but has 'char *')}} - void (*dptr3)(int *c) = &disabled; // expected-warning{{incompatible pointer types initializing 'void (*)(int *)' with an expression of type ''}} expected-note@115{{candidate function made ineligible by enable_if}} expected-note@116{{candidate function made ineligible by enable_if}} expected-note@117{{candidate function has type mismatch at 1st parameter (expected 'int *' but has 'char *')}} + void (*dptr2)(void *c) = &disabled; // expected-warning{{incompatible pointer types initializing 'void (*)(void *)' with an expression of type ''}} expected-note@-5{{candidate function made ineligible by enable_if}} expected-note@-4{{candidate function made ineligible by enable_if}} expected-note@-3{{candidate function has type mismatch at 1st parameter (expected 'void *' but has 'char *')}} + void (*dptr3)(int *c) = &disabled; // expected-warning{{incompatible pointer types initializing 'void (*)(int *)' with an expression of type ''}} expected-note@-6{{candidate function made ineligible by enable_if}} expected-note@-5{{candidate function made ineligible by enable_if}} expected-note@-4{{candidate function has type mismatch at 1st parameter (expected 'int *' but has 'char *')}} void *specific_disabled = &disabled; } @@ -131,14 +131,14 @@ void incompatible_pointer_type_conversio void foo(char *c) __attribute__((overloadable)); void foo(short *c) __attribute__((overloadable)); foo(charbuf); - foo(ucharbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@131{{candidate function}} expected-note@132{{candidate function}} - foo(intbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@131{{candidate function}} expected-note@132{{candidate function}} + foo(ucharbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@-3{{candidate function}} expected-note@-2{{candidate function}} + foo(intbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@-4{{candidate function}} expected-note@-3{{candidate function}} void bar(unsigned char *c) __attribute__((overloadable)); void bar(signed char *c) __attribute__((overloadable)); - bar(charbuf); // expected-error{{call to 'bar' is ambiguous}} expected-note@137{{candidate function}} expected-note@138{{candidate function}} + bar(charbuf); // expected-error{{call to 'bar' is ambiguous}} expected-note@-2{{candidate function}} expected-not
[PATCH] D30863: [clang-format] make docs/tools/{dump_format_style.py, dump_ast_matchers.py} flake8 compliant
sylvestre.ledru added a comment. @klimek ping? https://reviews.llvm.org/D30863 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D32332: Add support for transparent overloadable functions in clang
george.burgess.iv updated this revision to Diff 103448. george.burgess.iv marked 6 inline comments as done. george.burgess.iv added a comment. Addressed all feedback https://reviews.llvm.org/D32332 Files: include/clang/Basic/AttrDocs.td include/clang/Basic/DiagnosticSemaKinds.td lib/Lex/PPMacroExpansion.cpp lib/Sema/SemaDecl.cpp test/CodeGen/mangle-ms.c test/CodeGen/mangle.c test/CodeGenCXX/mangle-ms.cpp test/PCH/attrs.c test/Sema/overloadable.c Index: test/Sema/overloadable.c === --- test/Sema/overloadable.c +++ test/Sema/overloadable.c @@ -3,12 +3,15 @@ int var __attribute__((overloadable)); // expected-error{{'overloadable' attribute only applies to functions}} void params(void) __attribute__((overloadable(12))); // expected-error {{'overloadable' attribute takes no arguments}} -int *f(int) __attribute__((overloadable)); // expected-note 2{{previous overload of function is here}} -float *f(float); // expected-error{{overloaded function 'f' must have the 'overloadable' attribute}} +int *f(int) __attribute__((overloadable)); // expected-note{{previous overload of function is here}} +float *f(float); int *f(int); // expected-error{{redeclaration of 'f' must have the 'overloadable' attribute}} \ // expected-note{{previous declaration is here}} double *f(double) __attribute__((overloadable)); // okay, new +// Ensure we don't complain about overloadable on implicitly declared functions. +int isdigit(int) __attribute__((overloadable)); + void test_f(int iv, float fv, double dv) { int *ip = f(iv); float *fp = f(fv); @@ -71,19 +74,19 @@ f1(); } -void before_local_1(int) __attribute__((overloadable)); // expected-note {{here}} +void before_local_1(int) __attribute__((overloadable)); void before_local_2(int); // expected-note {{here}} void before_local_3(int) __attribute__((overloadable)); void local() { - void before_local_1(char); // expected-error {{must have the 'overloadable' attribute}} - void before_local_2(char) __attribute__((overloadable)); // expected-error {{conflicting types}} + void before_local_1(char); + void before_local_2(char); // expected-error {{conflicting types}} void before_local_3(char) __attribute__((overloadable)); - void after_local_1(char); // expected-note {{here}} - void after_local_2(char) __attribute__((overloadable)); // expected-note {{here}} + void after_local_1(char); + void after_local_2(char) __attribute__((overloadable)); void after_local_3(char) __attribute__((overloadable)); } -void after_local_1(int) __attribute__((overloadable)); // expected-error {{conflicting types}} -void after_local_2(int); // expected-error {{must have the 'overloadable' attribute}} +void after_local_1(int) __attribute__((overloadable)); +void after_local_2(int); void after_local_3(int) __attribute__((overloadable)); // Make sure we allow C-specific conversions in C. @@ -152,6 +155,85 @@ foo(vcharbuf); // expected-error{{call to 'foo' is ambiguous}} expected-note@-4{{candidate function}} expected-note@-3{{candidate function}} } +void overloadable_with_global() { + void wg_foo(void) __attribute__((overloadable)); // expected-note{{previous}} + void wg_foo(int) __attribute__((overloadable)); +} + +int wg_foo; // expected-error{{redefinition of 'wg_foo' as different kind of symbol}} + +#if !__has_extension(overloadable_unmarked) +#error "We should have unmarked overload support" +#endif + +void to_foo0(int); +void to_foo0(double) __attribute__((overloadable)); // expected-note{{previous overload}} +void to_foo0(int); +void to_foo0(double); // expected-error{{must have the 'overloadable' attribute}} +void to_foo0(int); + +void to_foo1(int) __attribute__((overloadable)); // expected-note 2{{previous overload}} +void to_foo1(double); +void to_foo1(int); // expected-error{{must have the 'overloadable' attribute}} +void to_foo1(double); +void to_foo1(int); // expected-error{{must have the 'overloadable' attribute}} + +void to_foo2(int); // expected-note{{previous unmarked overload}} +void to_foo2(double) __attribute__((overloadable)); // expected-note 2{{previous overload}} +void to_foo2(int) __attribute__((overloadable)); // expected-error {{must not have the 'overloadable' attribute}} +void to_foo2(double); // expected-error{{must have the 'overloadable' attribute}} +void to_foo2(int); +void to_foo2(double); // expected-error{{must have the 'overloadable' attribute}} +void to_foo2(int); + +void to_foo3(int); +void to_foo3(double) __attribute__((overloadable)); // expected-note{{previous overload}} +void to_foo3(int); +void to_foo3(double); // expected-error{{must have the 'overloadable' attribute}} + +void to_foo4(int) __attribute__((overloadable)); // expected-note{{previous overload}} +void to_foo4(int); // expected-error{{must have the 'overloadable' attribute}} +void to_foo4(double) __attribute__((overloadable)); + +void to_foo5(int); +void to_foo5(int
[PATCH] D32332: Add support for transparent overloadable functions in clang
george.burgess.iv added a comment. Thank you both for the comments! Comment at: include/clang/Basic/DiagnosticSemaKinds.td:3294-3295 +def err_attribute_overloadable_multiple_unmarked_overloads : Error< + "at most one 'overloadable' function for a given name may lack the " + "'overloadable' attribute">; def warn_ns_attribute_wrong_return_type : Warning< rsmith wrote: > I think calling the functions 'overloadable' in this case is confusing. Yeah, I couldn't think of a good name, either. Is this better? Comment at: lib/Lex/PPMacroExpansion.cpp:1136 .Case("nullability_on_arrays", true) + .Case("overloadable_unmarked", true) .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory)) rsmith wrote: > Should this be `__has_extension` rather than `__has_feature`, since it's not > a standard feature? (Per > http://clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension > `__has_feature` is only for detecting standard features, despite us using it > for other things.) Ah, I missed the "For backward compatibility" bit. Good call Comment at: lib/Sema/SemaDecl.cpp:9225 +/*NewIsUsingDecl=*/false)) { + case Sema::Ovl_Match: + case Sema::Ovl_NonFunction: aaron.ballman wrote: > Why add `Sema::` to these? Artifact of me moving code around and then putting it back. :) Comment at: lib/Sema/SemaDecl.cpp:9249-9252 +case Ovl_Match: + // We're not guaranteed to be handed the most recent decl, and + // __attribute__((overloadable)) depends somewhat on source order. + OldDecl = OldDecl->getMostRecentDecl(); rsmith wrote: > `checkForConflictWithnonVisibleExternC` should probably be responsible for > finding the most recent declaration of the entity that is actually visible > (and not, say, a block-scope declaration in some unrelated function, or a > declaration in an unimported module). Isn't part of the goal of `checkForConflictWithNonVisibleExternC` to report things that (potentially) aren't visible? If so, I don't see how it can also be its responsibility to always report things that are visible, unless it's a best-effort sort of thing. In any case, this bit of code boils down to me trying to slip a bugfix in here. Since I think fixing this properly will just pollute this diff even more, I'll back it out and try again in a separate patch. :) Comment at: lib/Sema/SemaDecl.cpp:9375-9381 +assert((Previous.empty() || +llvm::any_of( +Previous, +[](const NamedDecl *ND) { + return ND->getMostRecentDecl()->hasAttr(); +})) && + "Non-redecls shouldn't happen without overloadable present"); rsmith wrote: > Seems worth factoring out this "contains any overloadable functions" check, > since it's quite a few lines and you're doing it in two different places. With the removal of one unnecessary change (see a later response), this is no longer repeated. Happy to still pull it out into a function if you think that helps readability. Comment at: test/Sema/overloadable.c:112 void (*ptr2)(char *) = &foo; - void (*ambiguous)(int *) = &foo; // expected-error{{initializing 'void (*)(int *)' with an expression of incompatible type ''}} expected-note@105{{candidate function}} expected-note@106{{candidate function}} - void *vp_ambiguous = &foo; // expected-error{{initializing 'void *' with an expression of incompatible type ''}} expected-note@105{{candidate function}} expected-note@106{{candidate function}} + void (*ambiguous)(int *) = &foo; // expected-error{{initializing 'void (*)(int *)' with an expression of incompatible type ''}} expected-note@-4{{candidate function}} expected-note@-3{{candidate function}} + void *vp_ambiguous = &foo; // expected-error{{initializing 'void *' with an expression of incompatible type ''}} expected-note@-5{{candidate function}} expected-note@-4{{candidate function}} rsmith wrote: > It'd be nice to check in these changes from @NNN -> @-M separately. r305947. https://reviews.llvm.org/D32332 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D22128: Make CastExpr::getSubExprAsWritten look through implicit temporary under CK_ConstructorConversion
sberg updated this revision to Diff 103449. sberg added a comment. Herald added subscribers: kristof.beyls, mgorny, klimek. added test https://reviews.llvm.org/D22128 Files: lib/AST/Expr.cpp unittests/Tooling/CMakeLists.txt unittests/Tooling/CastExprTest.cpp Index: unittests/Tooling/CastExprTest.cpp === --- /dev/null +++ unittests/Tooling/CastExprTest.cpp @@ -0,0 +1,38 @@ +//===- unittest/Tooling/CastExprTest.cpp --===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// + +#include "TestVisitor.h" + +using namespace clang; + +namespace { + +struct CastExprVisitor : TestVisitor { + std::function OnExplicitCast; + + bool VisitExplicitCastExpr(ExplicitCastExpr *Expr) { +if (OnExplicitCast) + OnExplicitCast(Expr); +return true; + } +}; + +TEST(CastExprTest, GetSubExprAsWrittenThroughMaterializedTemporary) { +CastExprVisitor Visitor; +Visitor.OnExplicitCast = [](ExplicitCastExpr *Expr) { + auto Sub = Expr->getSubExprAsWritten(); + EXPECT_TRUE(isa(Sub)) +<< "Expected DeclRefExpr, but saw " << Sub->getStmtClassName(); +}; +Visitor.runOver("struct S1 {};\n" +"struct S2 { operator S1(); };\n" +"S1 f(S2 s) { return static_cast(s); }\n"); +} + +} Index: unittests/Tooling/CMakeLists.txt === --- unittests/Tooling/CMakeLists.txt +++ unittests/Tooling/CMakeLists.txt @@ -11,6 +11,7 @@ endif() add_clang_unittest(ToolingTests + CastExprTest.cpp CommentHandlerTest.cpp CompilationDatabaseTest.cpp FixItTest.cpp Index: lib/AST/Expr.cpp === --- lib/AST/Expr.cpp +++ lib/AST/Expr.cpp @@ -1641,25 +1641,32 @@ llvm_unreachable("Unhandled cast kind!"); } +namespace { + Expr *skipImplicitTemporary(Expr *expr) { +// Skip through reference binding to temporary. +if (MaterializeTemporaryExpr *Materialize + = dyn_cast(expr)) + expr = Materialize->GetTemporaryExpr(); + +// Skip any temporary bindings; they're implicit. +if (CXXBindTemporaryExpr *Binder = dyn_cast(expr)) + expr = Binder->getSubExpr(); + +return expr; + } +} + Expr *CastExpr::getSubExprAsWritten() { Expr *SubExpr = nullptr; CastExpr *E = this; do { -SubExpr = E->getSubExpr(); +SubExpr = skipImplicitTemporary(E->getSubExpr()); -// Skip through reference binding to temporary. -if (MaterializeTemporaryExpr *Materialize - = dyn_cast(SubExpr)) - SubExpr = Materialize->GetTemporaryExpr(); - -// Skip any temporary bindings; they're implicit. -if (CXXBindTemporaryExpr *Binder = dyn_cast(SubExpr)) - SubExpr = Binder->getSubExpr(); - // Conversions by constructor and conversion functions have a // subexpression describing the call; strip it off. if (E->getCastKind() == CK_ConstructorConversion) - SubExpr = cast(SubExpr)->getArg(0); + SubExpr = +skipImplicitTemporary(cast(SubExpr)->getArg(0)); else if (E->getCastKind() == CK_UserDefinedConversion) { assert((isa(SubExpr) || isa(SubExpr)) && ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34475: [RFC] [AArch64] Add support for __builtin_ms_va_list on aarch64
mstorsjo created this revision. Herald added subscribers: kristof.beyls, javed.absar, rengolin, aemerson. This behaves mostly the same as __builtin_ms_va_list on x86_64; a va_list on windows on aarch64 is a single pointer. In order to signal the kind of va_list to llvm for handling of va_start, a separate calling convention is used, signaled via __attribute__((ms_abi)) just as on x86_64. This allows wine on aarch64 to properly handle variadic functions, successfully running arm64 exes (from the windows 10 sdk) with a few different variations of fprintf and vsnprintf. This depends on https://reviews.llvm.org/D34474 for llvm. https://reviews.llvm.org/D34475 Files: include/clang/Basic/BuiltinsAArch64.def include/clang/Basic/DiagnosticSemaKinds.td include/clang/Basic/Specifiers.h lib/AST/ItaniumMangle.cpp lib/AST/MicrosoftMangle.cpp lib/AST/Type.cpp lib/AST/TypePrinter.cpp lib/Basic/Targets.cpp lib/CodeGen/CGBuiltin.cpp lib/CodeGen/CGCall.cpp lib/CodeGen/CGDebugInfo.cpp lib/CodeGen/TargetInfo.cpp lib/Sema/SemaChecking.cpp lib/Sema/SemaDeclAttr.cpp Index: lib/Sema/SemaDeclAttr.cpp === --- lib/Sema/SemaDeclAttr.cpp +++ lib/Sema/SemaDeclAttr.cpp @@ -4279,7 +4279,8 @@ case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break; case AttributeList::AT_RegCall: CC = CC_X86RegCall; break; case AttributeList::AT_MSABI: -CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : +CC = Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64 ? CC_AArch64Win64 : + Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : CC_X86_64Win64; break; case AttributeList::AT_SysVABI: Index: lib/Sema/SemaChecking.cpp === --- lib/Sema/SemaChecking.cpp +++ lib/Sema/SemaChecking.cpp @@ -1437,6 +1437,9 @@ bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { + if (BuiltinID == AArch64::BI__builtin_ms_va_start) +return SemaBuiltinVAStart(BuiltinID, TheCall); + if (BuiltinID == AArch64::BI__builtin_arm_ldrex || BuiltinID == AArch64::BI__builtin_arm_ldaex || BuiltinID == AArch64::BI__builtin_arm_strex || @@ -3619,12 +3622,15 @@ static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); bool IsX64 = TT.getArch() == llvm::Triple::x86_64; + bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; bool IsWindows = TT.isOSWindows(); - bool IsMSVAStart = BuiltinID == X86::BI__builtin_ms_va_start; + bool IsMSVAStart = BuiltinID == X86::BI__builtin_ms_va_start || + BuiltinID == AArch64::BI__builtin_ms_va_start; + clang::CallingConv CC = CC_C; + if (const FunctionDecl *FD = S.getCurFunctionDecl()) +CC = FD->getType()->getAs()->getCallConv(); + if (IsX64) { -clang::CallingConv CC = CC_C; -if (const FunctionDecl *FD = S.getCurFunctionDecl()) - CC = FD->getType()->getAs()->getCallConv(); if (IsMSVAStart) { // Don't allow this in System V ABI functions. if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_X86_64Win64)) @@ -3644,6 +3650,22 @@ return false; } + if (IsAArch64) { +if (IsMSVAStart) { + // Don't allow this in AAPCS functions. + if (CC == CC_C || (!IsWindows && CC != CC_AArch64Win64)) +return S.Diag(Fn->getLocStart(), + diag::err_ms_va_start_used_in_aapcs_function); +} else { + // On aarch64 Unix, don't allow this in Win64 ABI functions. + if (!IsWindows && CC == CC_AArch64Win64) +return S.Diag(Fn->getLocStart(), + diag::err_va_start_used_in_wrong_abi_function) + << !IsWindows; +} +return false; + } + if (IsMSVAStart) return S.Diag(Fn->getLocStart(), diag::err_x86_builtin_64_only); return false; Index: lib/CodeGen/TargetInfo.cpp === --- lib/CodeGen/TargetInfo.cpp +++ lib/CodeGen/TargetInfo.cpp @@ -4822,6 +4822,8 @@ return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) : EmitAAPCSVAArg(VAListAddr, Ty, CGF); } + Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, + QualType Ty) const override; bool shouldPassIndirectlyForSwift(CharUnits totalSize, ArrayRef scalars, @@ -5328,6 +5330,14 @@ TyInfo, SlotSize, /*AllowHigherAlign*/ true); } +Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, +QualType Ty) const { + return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, + CGF.getContext().getTypeInfo
[PATCH] D34304: Allow CompilerInvocations to generate .d files.
saugustine added a comment. > Actually, now that I figured out you mean ArgumentAdjusters, I am making > progress. Unfortunately, ArgumentAdjusters only work on vector, and while ToolInvocation::Invocation takes its arguments in that form, tooling::newInvocation (which returns a CompilerInvocation) takes a SmallVector, so we either need to change one side's interface, or write two ArgumentAdjusters, but with similar semantics. What is your preferred solution? https://reviews.llvm.org/D34304 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34454: SwiftCC: Perform physical layout when computing coercion types
aschwaighofer updated this revision to Diff 103458. aschwaighofer retitled this revision from "SwiftAggregateLowering: Use type alloc size to determine the size of types" to "SwiftCC: Perform physical layout when computing coercion types". aschwaighofer edited the summary of this revision. aschwaighofer removed a reviewer: cfe-commits. aschwaighofer added a subscriber: cfe-commits. aschwaighofer added a comment. Based on email conversation with John. He pointed out we purposely don't want to use the allocation size for the algorithm and that we can just use LLVM's layout when we compute the coercion types. https://reviews.llvm.org/D34454 Files: lib/CodeGen/SwiftCallingConv.cpp test/CodeGen/64bit-swiftcall.c Index: test/CodeGen/64bit-swiftcall.c === --- test/CodeGen/64bit-swiftcall.c +++ test/CodeGen/64bit-swiftcall.c @@ -1,4 +1,5 @@ // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s --check-prefix=X86-64 // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM64 @@ -1014,3 +1015,20 @@ TEST(struct_v1f3) // ARM64-LABEL: define swiftcc { <2 x float>, float } @return_struct_v1f3() // ARM64-LABEL: define swiftcc void @take_struct_v1f3(<2 x float>, float) + +typedef struct { + int3 vect; + unsigned long long val; +} __attribute__((packed)) padded_alloc_size_vector; +TEST(padded_alloc_size_vector) +// X86-64-LABEL: take_padded_alloc_size_vector(<3 x i32>, i64) +// X86-64-NOT: [4 x i8] +// x86-64: ret void + +typedef union { + float f1; + float3 fv2; +} union_hom_fp_partial2; +TEST(union_hom_fp_partial2) +// X86-64-LABEL: take_union_hom_fp_partial2(i64, float) +// ARM64-LABEL: take_union_hom_fp_partial2(i64, float) Index: lib/CodeGen/SwiftCallingConv.cpp === --- lib/CodeGen/SwiftCallingConv.cpp +++ lib/CodeGen/SwiftCallingConv.cpp @@ -57,6 +57,10 @@ return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type)); } +static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) { + return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type)); +} + void SwiftAggLowering::addTypedData(QualType type, CharUnits begin) { // Deal with various aggregate types as special cases: @@ -542,7 +546,9 @@ packed = true; elts.push_back(entry.Type); -lastEnd = entry.End; + +lastEnd = entry.Begin + getTypeAllocSize(CGM, entry.Type); +assert(entry.End <= lastEnd); } // We don't need to adjust 'packed' to deal with possible tail padding Index: test/CodeGen/64bit-swiftcall.c === --- test/CodeGen/64bit-swiftcall.c +++ test/CodeGen/64bit-swiftcall.c @@ -1,4 +1,5 @@ // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s --check-prefix=X86-64 // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM64 @@ -1014,3 +1015,20 @@ TEST(struct_v1f3) // ARM64-LABEL: define swiftcc { <2 x float>, float } @return_struct_v1f3() // ARM64-LABEL: define swiftcc void @take_struct_v1f3(<2 x float>, float) + +typedef struct { + int3 vect; + unsigned long long val; +} __attribute__((packed)) padded_alloc_size_vector; +TEST(padded_alloc_size_vector) +// X86-64-LABEL: take_padded_alloc_size_vector(<3 x i32>, i64) +// X86-64-NOT: [4 x i8] +// x86-64: ret void + +typedef union { + float f1; + float3 fv2; +} union_hom_fp_partial2; +TEST(union_hom_fp_partial2) +// X86-64-LABEL: take_union_hom_fp_partial2(i64, float) +// ARM64-LABEL: take_union_hom_fp_partial2(i64, float) Index: lib/CodeGen/SwiftCallingConv.cpp === --- lib/CodeGen/SwiftCallingConv.cpp +++ lib/CodeGen/SwiftCallingConv.cpp @@ -57,6 +57,10 @@ return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type)); } +static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) { + return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type)); +} + void SwiftAggLowering::addTypedData(QualType type, CharUnits begin) { // Deal with various aggregate types as special cases: @@ -542,7 +546,9 @@ packed = true; elts.push_back(entry.Type); -lastEnd = entry.End; + +lastEnd = entry.Begin + getTypeAllocSize(CGM, entry.Type); +assert(entry.End <= lastEnd); } // W
[PATCH] D34454: SwiftCC: Perform physical layout when computing coercion types
aschwaighofer updated this revision to Diff 103459. aschwaighofer added a comment. Same patch bug with added diff context. https://reviews.llvm.org/D34454 Files: lib/CodeGen/SwiftCallingConv.cpp test/CodeGen/64bit-swiftcall.c Index: test/CodeGen/64bit-swiftcall.c === --- test/CodeGen/64bit-swiftcall.c +++ test/CodeGen/64bit-swiftcall.c @@ -1,4 +1,5 @@ // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s --check-prefix=X86-64 // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM64 @@ -1014,3 +1015,20 @@ TEST(struct_v1f3) // ARM64-LABEL: define swiftcc { <2 x float>, float } @return_struct_v1f3() // ARM64-LABEL: define swiftcc void @take_struct_v1f3(<2 x float>, float) + +typedef struct { + int3 vect; + unsigned long long val; +} __attribute__((packed)) padded_alloc_size_vector; +TEST(padded_alloc_size_vector) +// X86-64-LABEL: take_padded_alloc_size_vector(<3 x i32>, i64) +// X86-64-NOT: [4 x i8] +// x86-64: ret void + +typedef union { + float f1; + float3 fv2; +} union_hom_fp_partial2; +TEST(union_hom_fp_partial2) +// X86-64-LABEL: take_union_hom_fp_partial2(i64, float) +// ARM64-LABEL: take_union_hom_fp_partial2(i64, float) Index: lib/CodeGen/SwiftCallingConv.cpp === --- lib/CodeGen/SwiftCallingConv.cpp +++ lib/CodeGen/SwiftCallingConv.cpp @@ -57,6 +57,10 @@ return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type)); } +static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) { + return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type)); +} + void SwiftAggLowering::addTypedData(QualType type, CharUnits begin) { // Deal with various aggregate types as special cases: @@ -542,7 +546,9 @@ packed = true; elts.push_back(entry.Type); -lastEnd = entry.End; + +lastEnd = entry.Begin + getTypeAllocSize(CGM, entry.Type); +assert(entry.End <= lastEnd); } // We don't need to adjust 'packed' to deal with possible tail padding Index: test/CodeGen/64bit-swiftcall.c === --- test/CodeGen/64bit-swiftcall.c +++ test/CodeGen/64bit-swiftcall.c @@ -1,4 +1,5 @@ // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s --check-prefix=X86-64 // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM64 @@ -1014,3 +1015,20 @@ TEST(struct_v1f3) // ARM64-LABEL: define swiftcc { <2 x float>, float } @return_struct_v1f3() // ARM64-LABEL: define swiftcc void @take_struct_v1f3(<2 x float>, float) + +typedef struct { + int3 vect; + unsigned long long val; +} __attribute__((packed)) padded_alloc_size_vector; +TEST(padded_alloc_size_vector) +// X86-64-LABEL: take_padded_alloc_size_vector(<3 x i32>, i64) +// X86-64-NOT: [4 x i8] +// x86-64: ret void + +typedef union { + float f1; + float3 fv2; +} union_hom_fp_partial2; +TEST(union_hom_fp_partial2) +// X86-64-LABEL: take_union_hom_fp_partial2(i64, float) +// ARM64-LABEL: take_union_hom_fp_partial2(i64, float) Index: lib/CodeGen/SwiftCallingConv.cpp === --- lib/CodeGen/SwiftCallingConv.cpp +++ lib/CodeGen/SwiftCallingConv.cpp @@ -57,6 +57,10 @@ return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type)); } +static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) { + return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type)); +} + void SwiftAggLowering::addTypedData(QualType type, CharUnits begin) { // Deal with various aggregate types as special cases: @@ -542,7 +546,9 @@ packed = true; elts.push_back(entry.Type); -lastEnd = entry.End; + +lastEnd = entry.Begin + getTypeAllocSize(CGM, entry.Type); +assert(entry.End <= lastEnd); } // We don't need to adjust 'packed' to deal with possible tail padding ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34198: Fix __has_trivial_destructor crash when the type is incomplete with unknown array bounds.
rsmith accepted this revision. rsmith added inline comments. Comment at: lib/Sema/SemaExprCXX.cpp:4128 +return true; +} + rjmccall wrote: > puneetha wrote: > > rjmccall wrote: > > > I don't understand the difference you're creating between traits here. > > > Three specific traits about destructibility allow incomplete array types > > > regardless of whether the base type is incomplete, but the rest do not? > > > > > > Anyway, I think what you want here is basically just: > > > > > > if (auto ArrayTy = S.Context.getAsIncompleteArrayType(ArgTy)) { > > > ArgTy = ArrayTy->getElementType(); > > > } > > Of my understanding, these traits are defined by MSVC. There is no mention > > of them in the GCC type-traits documentation. For these traits, GCC lets us > > pass an array of incomplete bounds for any base type, complete or > > incomplete. > > > > Please correct me if I am wrong. > I see. If we're matching GCC bug-for-bug, it doesn't really matter if the > behavior seems inconsistent. Generally: when the C++ standard has a trait named `std::foo` and Clang has a `__foo` builtin, the latter is a complete implementation of the former (and if other compilers have bugs in their implementations, we are not bug-for-bug compatible). That covers the `UTT_Is*` traits here. The other traits are typically extensions from other vendors, often used to implement pre-standard names for traits. Many of those are considered deprecated, and we try to be mostly bug-for-bug compatible with GCC or MSVC when implementing them. That covers the `UTT_Has*` traits here. Per commentary in PR33232, MSVC's STL has nearly entirely moved off the deprecated traits, so it's mostly GCC compatibility we care about here. https://reviews.llvm.org/D34198 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34198: Fix __has_trivial_destructor crash when the type is incomplete with unknown array bounds.
rsmith added a comment. It'd be good to also add tests for the other traits you're changing. https://reviews.llvm.org/D34198 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: [PATCH] D34439: Add GCC's noexcept-type alias for c++1z-compat-mangling
There's plenty of precedent for supporting a name we like for a flag, and also supporting an alias for GCC compatibility (especially for warning flags). On 21 June 2017 at 10:56, Raphael Isemann via Phabricator < revi...@reviews.llvm.org> wrote: > teemperor added a comment. > > @ahatanak I think we can leave the more expressive clang name for this > warning and just add the bit cryptic GCC name for compability. But I don't > have a strong opinion on this. > > > https://reviews.llvm.org/D34439 > > > > ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34454: SwiftCC: Perform physical layout when computing coercion types
rjmccall added a comment. Looks great, thanks! https://reviews.llvm.org/D34454 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34425: Unified ARM logic for computing target ABI.
echristo accepted this revision. echristo added a comment. This revision is now accepted and ready to land. This is OK once the dependent revision is approved. https://reviews.llvm.org/D34425 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libcxx] r305955 - Attempt to avoid static init ordering issues with globalMemCounter
Author: ericwf Date: Wed Jun 21 16:42:50 2017 New Revision: 305955 URL: http://llvm.org/viewvc/llvm-project?rev=305955&view=rev Log: Attempt to avoid static init ordering issues with globalMemCounter Modified: libcxx/trunk/test/support/count_new.hpp Modified: libcxx/trunk/test/support/count_new.hpp URL: http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/support/count_new.hpp?rev=305955&r1=305954&r2=305955&view=diff == --- libcxx/trunk/test/support/count_new.hpp (original) +++ libcxx/trunk/test/support/count_new.hpp Wed Jun 21 16:42:50 2017 @@ -231,12 +231,17 @@ public: const bool MemCounter::disable_checking = false; #endif -MemCounter globalMemCounter((MemCounter::MemCounterCtorArg_())); +inline MemCounter* getGlobalMemCounter() { + static MemCounter counter((MemCounter::MemCounterCtorArg_())); + return &counter; +} + +MemCounter &globalMemCounter = *getGlobalMemCounter(); #ifndef DISABLE_NEW_COUNT void* operator new(std::size_t s) TEST_THROW_SPEC(std::bad_alloc) { -globalMemCounter.newCalled(s); +getGlobalMemCounter()->newCalled(s); void* ret = std::malloc(s); if (ret == nullptr) detail::throw_bad_alloc_helper(); @@ -245,21 +250,21 @@ void* operator new(std::size_t s) TEST_T void operator delete(void* p) TEST_NOEXCEPT { -globalMemCounter.deleteCalled(p); +getGlobalMemCounter()->deleteCalled(p); std::free(p); } void* operator new[](std::size_t s) TEST_THROW_SPEC(std::bad_alloc) { -globalMemCounter.newArrayCalled(s); +getGlobalMemCounter()->newArrayCalled(s); return operator new(s); } void operator delete[](void* p) TEST_NOEXCEPT { -globalMemCounter.deleteArrayCalled(p); +getGlobalMemCounter()->deleteArrayCalled(p); operator delete(p); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r305956 - SwiftCC: Perform physical layout when computing coercion types
Author: arnolds Date: Wed Jun 21 16:43:40 2017 New Revision: 305956 URL: http://llvm.org/viewvc/llvm-project?rev=305956&view=rev Log: SwiftCC: Perform physical layout when computing coercion types We need to take type alignment padding into account whe computing physical layouts. The layout must be compatible with the input layout, offsets are defined in terms of offsets within a packed struct which are computed in terms of the alloc size of a type. Usingthe store size we would insert padding for the following type for example: struct { int3 v; long long l; } __attribute((packed)) On x86-64 int3 is padded to int4 alignment. The swiftcc type would be <{ <3 x float>, [4 x i8], i64 }> which is not compatible with <{ <3 x float>, i64 }>. The latter has i64 at offset 16 and the former at offset 20. rdar://32618125 Modified: cfe/trunk/lib/CodeGen/SwiftCallingConv.cpp cfe/trunk/test/CodeGen/64bit-swiftcall.c Modified: cfe/trunk/lib/CodeGen/SwiftCallingConv.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/SwiftCallingConv.cpp?rev=305956&r1=305955&r2=305956&view=diff == --- cfe/trunk/lib/CodeGen/SwiftCallingConv.cpp (original) +++ cfe/trunk/lib/CodeGen/SwiftCallingConv.cpp Wed Jun 21 16:43:40 2017 @@ -57,6 +57,10 @@ static CharUnits getTypeStoreSize(CodeGe return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type)); } +static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) { + return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type)); +} + void SwiftAggLowering::addTypedData(QualType type, CharUnits begin) { // Deal with various aggregate types as special cases: @@ -542,7 +546,9 @@ SwiftAggLowering::getCoerceAndExpandType packed = true; elts.push_back(entry.Type); -lastEnd = entry.End; + +lastEnd = entry.Begin + getTypeAllocSize(CGM, entry.Type); +assert(entry.End <= lastEnd); } // We don't need to adjust 'packed' to deal with possible tail padding Modified: cfe/trunk/test/CodeGen/64bit-swiftcall.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/64bit-swiftcall.c?rev=305956&r1=305955&r2=305956&view=diff == --- cfe/trunk/test/CodeGen/64bit-swiftcall.c (original) +++ cfe/trunk/test/CodeGen/64bit-swiftcall.c Wed Jun 21 16:43:40 2017 @@ -1,4 +1,5 @@ // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s +// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -target-cpu core2 -emit-llvm -o - %s | FileCheck %s --check-prefix=X86-64 // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple arm64-apple-ios9 -target-cpu cyclone -emit-llvm -o - %s | FileCheck %s --check-prefix=ARM64 @@ -1014,3 +1015,20 @@ typedef struct { TEST(struct_v1f3) // ARM64-LABEL: define swiftcc { <2 x float>, float } @return_struct_v1f3() // ARM64-LABEL: define swiftcc void @take_struct_v1f3(<2 x float>, float) + +typedef struct { + int3 vect; + unsigned long long val; +} __attribute__((packed)) padded_alloc_size_vector; +TEST(padded_alloc_size_vector) +// X86-64-LABEL: take_padded_alloc_size_vector(<3 x i32>, i64) +// X86-64-NOT: [4 x i8] +// x86-64: ret void + +typedef union { + float f1; + float3 fv2; +} union_hom_fp_partial2; +TEST(union_hom_fp_partial2) +// X86-64-LABEL: take_union_hom_fp_partial2(i64, float) +// ARM64-LABEL: take_union_hom_fp_partial2(i64, float) ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
Re: r303322 - [modules] Switch from inferring owning modules based on source location to
Hi Richard, Somehow this commit caused some methods in ObjC to do not become visible in an interface when compiling with modules on. I filed https://bugs.llvm.org/show_bug.cgi?id=33552, any idea what could have gone wrong here? `hasVisibleDeclarationImpl` doesn't seem to have changed the logic. Thanks, On Wed, May 17, 2017 at 7:29 PM, Richard Smith via cfe-commits wrote: > Author: rsmith > Date: Wed May 17 21:29:20 2017 > New Revision: 303322 > > URL: http://llvm.org/viewvc/llvm-project?rev=303322&view=rev > Log: > [modules] Switch from inferring owning modules based on source location to > inferring based on the current module at the point of creation. > > This should result in no functional change except when building a preprocessed > module (or more generally when using #pragma clang module begin/end to switch > module in the middle of a file), in which case it allows us to correctly track > the owning module for declarations. We can't map from FileID to module in the > preprocessed module case, since all modules would have the same FileID. > > There are still a couple of remaining places that try to infer a module from a > source location; I'll clean those up in follow-up changes. > > Modified: > cfe/trunk/include/clang/AST/ASTContext.h > cfe/trunk/include/clang/AST/DeclBase.h > cfe/trunk/include/clang/Basic/LangOptions.h > cfe/trunk/include/clang/Sema/Sema.h > cfe/trunk/include/clang/Serialization/ASTWriter.h > cfe/trunk/lib/CodeGen/CGDebugInfo.cpp > cfe/trunk/lib/Sema/SemaDecl.cpp > cfe/trunk/lib/Sema/SemaLookup.cpp > cfe/trunk/lib/Sema/SemaTemplate.cpp > cfe/trunk/lib/Serialization/ASTWriter.cpp > cfe/trunk/lib/Serialization/ASTWriterDecl.cpp > cfe/trunk/test/Modules/preprocess-module.cpp > cfe/trunk/test/SemaCXX/modules-ts.cppm > > Modified: cfe/trunk/include/clang/AST/ASTContext.h > URL: > http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=303322&r1=303321&r2=303322&view=diff > == > --- cfe/trunk/include/clang/AST/ASTContext.h (original) > +++ cfe/trunk/include/clang/AST/ASTContext.h Wed May 17 21:29:20 2017 > @@ -935,7 +935,7 @@ public: > >/// \brief Get the additional modules in which the definition \p Def has >/// been merged. > - ArrayRef getModulesWithMergedDefinition(NamedDecl *Def) { > + ArrayRef getModulesWithMergedDefinition(const NamedDecl *Def) { > auto MergedIt = MergedDefModules.find(Def); > if (MergedIt == MergedDefModules.end()) >return None; > > Modified: cfe/trunk/include/clang/AST/DeclBase.h > URL: > http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclBase.h?rev=303322&r1=303321&r2=303322&view=diff > == > --- cfe/trunk/include/clang/AST/DeclBase.h (original) > +++ cfe/trunk/include/clang/AST/DeclBase.h Wed May 17 21:29:20 2017 > @@ -332,15 +332,15 @@ private: >bool AccessDeclContextSanity() const; > > protected: > - >Decl(Kind DK, DeclContext *DC, SourceLocation L) > -: NextInContextAndBits(), DeclCtx(DC), > - Loc(L), DeclKind(DK), InvalidDecl(0), > - HasAttrs(false), Implicit(false), Used(false), Referenced(false), > - Access(AS_none), FromASTFile(0), Hidden(DC && cast(DC)->Hidden), > - IdentifierNamespace(getIdentifierNamespaceForKind(DK)), > - CacheValidAndLinkage(0) > - { > + : NextInContextAndBits(), DeclCtx(DC), Loc(L), DeclKind(DK), > +InvalidDecl(0), HasAttrs(false), Implicit(false), Used(false), > +Referenced(false), Access(AS_none), FromASTFile(0), > +Hidden(DC && cast(DC)->Hidden && > + (!cast(DC)->isFromASTFile() || > +hasLocalOwningModuleStorage())), > +IdentifierNamespace(getIdentifierNamespaceForKind(DK)), > +CacheValidAndLinkage(0) { > if (StatisticsEnabled) add(DK); >} > > @@ -698,6 +698,9 @@ public: >Module *getLocalOwningModule() const { > if (isFromASTFile() || !Hidden) >return nullptr; > + > +assert(hasLocalOwningModuleStorage() && > + "hidden local decl but no local module storage"); > return reinterpret_cast(this)[-1]; >} >void setLocalOwningModule(Module *M) { > > Modified: cfe/trunk/include/clang/Basic/LangOptions.h > URL: > http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/LangOptions.h?rev=303322&r1=303321&r2=303322&view=diff > == > --- cfe/trunk/include/clang/Basic/LangOptions.h (original) > +++ cfe/trunk/include/clang/Basic/LangOptions.h Wed May 17 21:29:20 2017 > @@ -168,7 +168,7 @@ public: > >/// Do we need to track the owning module for a local declaration? >bool trackLocalOwningModule() const { > -return ModulesLocalVisibility; > +return isCompilingModule() || ModulesLocalVisibility || ModulesTS; >
Re: r303322 - [modules] Switch from inferring owning modules based on source location to
On 21 June 2017 at 14:51, Bruno Cardoso Lopes wrote: > Hi Richard, > > Somehow this commit caused some methods in ObjC to do not become > visible in an interface when compiling with modules on. I filed > https://bugs.llvm.org/show_bug.cgi?id=33552, any idea what could have > gone wrong here? `hasVisibleDeclarationImpl` doesn't seem to have > changed the logic. > DeclObjC.cpp is making some incorrect assumptions about what the isHidden() flag on Decls means. Looks like we're going to need to move all of the ObjC lookup machinery out of DeclObjC into Sema to allow it to perform correct visibility checks. (For what it's worth, this would already have been broken for Objective-C++ and local submodule visibility mode prior to this change, as those modes both have situations where the "Hidden" flag is not the complete story with regard to whether a declaration is visible in a particular lookup context.) > Thanks, > > On Wed, May 17, 2017 at 7:29 PM, Richard Smith via cfe-commits > wrote: > > Author: rsmith > > Date: Wed May 17 21:29:20 2017 > > New Revision: 303322 > > > > URL: http://llvm.org/viewvc/llvm-project?rev=303322&view=rev > > Log: > > [modules] Switch from inferring owning modules based on source location > to > > inferring based on the current module at the point of creation. > > > > This should result in no functional change except when building a > preprocessed > > module (or more generally when using #pragma clang module begin/end to > switch > > module in the middle of a file), in which case it allows us to correctly > track > > the owning module for declarations. We can't map from FileID to module > in the > > preprocessed module case, since all modules would have the same FileID. > > > > There are still a couple of remaining places that try to infer a module > from a > > source location; I'll clean those up in follow-up changes. > > > > Modified: > > cfe/trunk/include/clang/AST/ASTContext.h > > cfe/trunk/include/clang/AST/DeclBase.h > > cfe/trunk/include/clang/Basic/LangOptions.h > > cfe/trunk/include/clang/Sema/Sema.h > > cfe/trunk/include/clang/Serialization/ASTWriter.h > > cfe/trunk/lib/CodeGen/CGDebugInfo.cpp > > cfe/trunk/lib/Sema/SemaDecl.cpp > > cfe/trunk/lib/Sema/SemaLookup.cpp > > cfe/trunk/lib/Sema/SemaTemplate.cpp > > cfe/trunk/lib/Serialization/ASTWriter.cpp > > cfe/trunk/lib/Serialization/ASTWriterDecl.cpp > > cfe/trunk/test/Modules/preprocess-module.cpp > > cfe/trunk/test/SemaCXX/modules-ts.cppm > > > > Modified: cfe/trunk/include/clang/AST/ASTContext.h > > URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/ > clang/AST/ASTContext.h?rev=303322&r1=303321&r2=303322&view=diff > > > == > > --- cfe/trunk/include/clang/AST/ASTContext.h (original) > > +++ cfe/trunk/include/clang/AST/ASTContext.h Wed May 17 21:29:20 2017 > > @@ -935,7 +935,7 @@ public: > > > >/// \brief Get the additional modules in which the definition \p Def > has > >/// been merged. > > - ArrayRef getModulesWithMergedDefinition(NamedDecl *Def) { > > + ArrayRef getModulesWithMergedDefinition(const NamedDecl > *Def) { > > auto MergedIt = MergedDefModules.find(Def); > > if (MergedIt == MergedDefModules.end()) > >return None; > > > > Modified: cfe/trunk/include/clang/AST/DeclBase.h > > URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/ > clang/AST/DeclBase.h?rev=303322&r1=303321&r2=303322&view=diff > > > == > > --- cfe/trunk/include/clang/AST/DeclBase.h (original) > > +++ cfe/trunk/include/clang/AST/DeclBase.h Wed May 17 21:29:20 2017 > > @@ -332,15 +332,15 @@ private: > >bool AccessDeclContextSanity() const; > > > > protected: > > - > >Decl(Kind DK, DeclContext *DC, SourceLocation L) > > -: NextInContextAndBits(), DeclCtx(DC), > > - Loc(L), DeclKind(DK), InvalidDecl(0), > > - HasAttrs(false), Implicit(false), Used(false), Referenced(false), > > - Access(AS_none), FromASTFile(0), Hidden(DC && > cast(DC)->Hidden), > > - IdentifierNamespace(getIdentifierNamespaceForKind(DK)), > > - CacheValidAndLinkage(0) > > - { > > + : NextInContextAndBits(), DeclCtx(DC), Loc(L), DeclKind(DK), > > +InvalidDecl(0), HasAttrs(false), Implicit(false), Used(false), > > +Referenced(false), Access(AS_none), FromASTFile(0), > > +Hidden(DC && cast(DC)->Hidden && > > + (!cast(DC)->isFromASTFile() || > > +hasLocalOwningModuleStorage())), > > +IdentifierNamespace(getIdentifierNamespaceForKind(DK)), > > +CacheValidAndLinkage(0) { > > if (StatisticsEnabled) add(DK); > >} > > > > @@ -698,6 +698,9 @@ public: > >Module *getLocalOwningModule() const { > > if (isFromASTFile() || !Hidden) > >return nullptr; > > + > > +assert(hasLocalOwningModuleStorage() && > > +
Re: r303322 - [modules] Switch from inferring owning modules based on source location to
On Wed, Jun 21, 2017 at 4:44 PM, Richard Smith wrote: > On 21 June 2017 at 14:51, Bruno Cardoso Lopes > wrote: >> >> Hi Richard, >> >> Somehow this commit caused some methods in ObjC to do not become >> visible in an interface when compiling with modules on. I filed >> https://bugs.llvm.org/show_bug.cgi?id=33552, any idea what could have >> gone wrong here? `hasVisibleDeclarationImpl` doesn't seem to have >> changed the logic. > > > DeclObjC.cpp is making some incorrect assumptions about what the isHidden() > flag on Decls means. Looks like we're going to need to move all of the ObjC > lookup machinery out of DeclObjC into Sema to allow it to perform correct > visibility checks. (For what it's worth, this would already have been broken > for Objective-C++ and local submodule visibility mode prior to this change, > as those modes both have situations where the "Hidden" flag is not the > complete story with regard to whether a declaration is visible in a > particular lookup context.) Oh, that's bad. Is there any workaround we can do on top of this change for now in order to have the previous behavior for non-LSV and ObjC? This is keeping Swift from building against upstream right now. > >> >> Thanks, >> >> On Wed, May 17, 2017 at 7:29 PM, Richard Smith via cfe-commits >> wrote: >> > Author: rsmith >> > Date: Wed May 17 21:29:20 2017 >> > New Revision: 303322 >> > >> > URL: http://llvm.org/viewvc/llvm-project?rev=303322&view=rev >> > Log: >> > [modules] Switch from inferring owning modules based on source location >> > to >> > inferring based on the current module at the point of creation. >> > >> > This should result in no functional change except when building a >> > preprocessed >> > module (or more generally when using #pragma clang module begin/end to >> > switch >> > module in the middle of a file), in which case it allows us to correctly >> > track >> > the owning module for declarations. We can't map from FileID to module >> > in the >> > preprocessed module case, since all modules would have the same FileID. >> > >> > There are still a couple of remaining places that try to infer a module >> > from a >> > source location; I'll clean those up in follow-up changes. >> > >> > Modified: >> > cfe/trunk/include/clang/AST/ASTContext.h >> > cfe/trunk/include/clang/AST/DeclBase.h >> > cfe/trunk/include/clang/Basic/LangOptions.h >> > cfe/trunk/include/clang/Sema/Sema.h >> > cfe/trunk/include/clang/Serialization/ASTWriter.h >> > cfe/trunk/lib/CodeGen/CGDebugInfo.cpp >> > cfe/trunk/lib/Sema/SemaDecl.cpp >> > cfe/trunk/lib/Sema/SemaLookup.cpp >> > cfe/trunk/lib/Sema/SemaTemplate.cpp >> > cfe/trunk/lib/Serialization/ASTWriter.cpp >> > cfe/trunk/lib/Serialization/ASTWriterDecl.cpp >> > cfe/trunk/test/Modules/preprocess-module.cpp >> > cfe/trunk/test/SemaCXX/modules-ts.cppm >> > >> > Modified: cfe/trunk/include/clang/AST/ASTContext.h >> > URL: >> > http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=303322&r1=303321&r2=303322&view=diff >> > >> > == >> > --- cfe/trunk/include/clang/AST/ASTContext.h (original) >> > +++ cfe/trunk/include/clang/AST/ASTContext.h Wed May 17 21:29:20 2017 >> > @@ -935,7 +935,7 @@ public: >> > >> >/// \brief Get the additional modules in which the definition \p Def >> > has >> >/// been merged. >> > - ArrayRef getModulesWithMergedDefinition(NamedDecl *Def) { >> > + ArrayRef getModulesWithMergedDefinition(const NamedDecl >> > *Def) { >> > auto MergedIt = MergedDefModules.find(Def); >> > if (MergedIt == MergedDefModules.end()) >> >return None; >> > >> > Modified: cfe/trunk/include/clang/AST/DeclBase.h >> > URL: >> > http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclBase.h?rev=303322&r1=303321&r2=303322&view=diff >> > >> > == >> > --- cfe/trunk/include/clang/AST/DeclBase.h (original) >> > +++ cfe/trunk/include/clang/AST/DeclBase.h Wed May 17 21:29:20 2017 >> > @@ -332,15 +332,15 @@ private: >> >bool AccessDeclContextSanity() const; >> > >> > protected: >> > - >> >Decl(Kind DK, DeclContext *DC, SourceLocation L) >> > -: NextInContextAndBits(), DeclCtx(DC), >> > - Loc(L), DeclKind(DK), InvalidDecl(0), >> > - HasAttrs(false), Implicit(false), Used(false), Referenced(false), >> > - Access(AS_none), FromASTFile(0), Hidden(DC && >> > cast(DC)->Hidden), >> > - IdentifierNamespace(getIdentifierNamespaceForKind(DK)), >> > - CacheValidAndLinkage(0) >> > - { >> > + : NextInContextAndBits(), DeclCtx(DC), Loc(L), DeclKind(DK), >> > +InvalidDecl(0), HasAttrs(false), Implicit(false), Used(false), >> > +Referenced(false), Access(AS_none), FromASTFile(0), >> > +Hidden(DC && cast(DC)->Hidden && >> > + (!cast(DC)->isFromASTFile() || >> > +
Re: r303322 - [modules] Switch from inferring owning modules based on source location to
On 21 June 2017 at 16:55, Bruno Cardoso Lopes wrote: > On Wed, Jun 21, 2017 at 4:44 PM, Richard Smith > wrote: > > On 21 June 2017 at 14:51, Bruno Cardoso Lopes > > wrote: > >> > >> Hi Richard, > >> > >> Somehow this commit caused some methods in ObjC to do not become > >> visible in an interface when compiling with modules on. I filed > >> https://bugs.llvm.org/show_bug.cgi?id=33552, any idea what could have > >> gone wrong here? `hasVisibleDeclarationImpl` doesn't seem to have > >> changed the logic. > > > > > > DeclObjC.cpp is making some incorrect assumptions about what the > isHidden() > > flag on Decls means. Looks like we're going to need to move all of the > ObjC > > lookup machinery out of DeclObjC into Sema to allow it to perform correct > > visibility checks. (For what it's worth, this would already have been > broken > > for Objective-C++ and local submodule visibility mode prior to this > change, > > as those modes both have situations where the "Hidden" flag is not the > > complete story with regard to whether a declaration is visible in a > > particular lookup context.) > > Oh, that's bad. > > Is there any workaround we can do on top of this change for now in > order to have the previous behavior for non-LSV and ObjC? This is > keeping Swift from building against upstream right now. Yes, I'm working on what should (hopefully) be a fairly quick short-term fix. > >> Thanks, > >> > >> On Wed, May 17, 2017 at 7:29 PM, Richard Smith via cfe-commits > >> wrote: > >> > Author: rsmith > >> > Date: Wed May 17 21:29:20 2017 > >> > New Revision: 303322 > >> > > >> > URL: http://llvm.org/viewvc/llvm-project?rev=303322&view=rev > >> > Log: > >> > [modules] Switch from inferring owning modules based on source > location > >> > to > >> > inferring based on the current module at the point of creation. > >> > > >> > This should result in no functional change except when building a > >> > preprocessed > >> > module (or more generally when using #pragma clang module begin/end to > >> > switch > >> > module in the middle of a file), in which case it allows us to > correctly > >> > track > >> > the owning module for declarations. We can't map from FileID to module > >> > in the > >> > preprocessed module case, since all modules would have the same > FileID. > >> > > >> > There are still a couple of remaining places that try to infer a > module > >> > from a > >> > source location; I'll clean those up in follow-up changes. > >> > > >> > Modified: > >> > cfe/trunk/include/clang/AST/ASTContext.h > >> > cfe/trunk/include/clang/AST/DeclBase.h > >> > cfe/trunk/include/clang/Basic/LangOptions.h > >> > cfe/trunk/include/clang/Sema/Sema.h > >> > cfe/trunk/include/clang/Serialization/ASTWriter.h > >> > cfe/trunk/lib/CodeGen/CGDebugInfo.cpp > >> > cfe/trunk/lib/Sema/SemaDecl.cpp > >> > cfe/trunk/lib/Sema/SemaLookup.cpp > >> > cfe/trunk/lib/Sema/SemaTemplate.cpp > >> > cfe/trunk/lib/Serialization/ASTWriter.cpp > >> > cfe/trunk/lib/Serialization/ASTWriterDecl.cpp > >> > cfe/trunk/test/Modules/preprocess-module.cpp > >> > cfe/trunk/test/SemaCXX/modules-ts.cppm > >> > > >> > Modified: cfe/trunk/include/clang/AST/ASTContext.h > >> > URL: > >> > http://llvm.org/viewvc/llvm-project/cfe/trunk/include/ > clang/AST/ASTContext.h?rev=303322&r1=303321&r2=303322&view=diff > >> > > >> > > == > >> > --- cfe/trunk/include/clang/AST/ASTContext.h (original) > >> > +++ cfe/trunk/include/clang/AST/ASTContext.h Wed May 17 21:29:20 2017 > >> > @@ -935,7 +935,7 @@ public: > >> > > >> >/// \brief Get the additional modules in which the definition \p > Def > >> > has > >> >/// been merged. > >> > - ArrayRef getModulesWithMergedDefinition(NamedDecl *Def) { > >> > + ArrayRef getModulesWithMergedDefinition(const NamedDecl > >> > *Def) { > >> > auto MergedIt = MergedDefModules.find(Def); > >> > if (MergedIt == MergedDefModules.end()) > >> >return None; > >> > > >> > Modified: cfe/trunk/include/clang/AST/DeclBase.h > >> > URL: > >> > http://llvm.org/viewvc/llvm-project/cfe/trunk/include/ > clang/AST/DeclBase.h?rev=303322&r1=303321&r2=303322&view=diff > >> > > >> > > == > >> > --- cfe/trunk/include/clang/AST/DeclBase.h (original) > >> > +++ cfe/trunk/include/clang/AST/DeclBase.h Wed May 17 21:29:20 2017 > >> > @@ -332,15 +332,15 @@ private: > >> >bool AccessDeclContextSanity() const; > >> > > >> > protected: > >> > - > >> >Decl(Kind DK, DeclContext *DC, SourceLocation L) > >> > -: NextInContextAndBits(), DeclCtx(DC), > >> > - Loc(L), DeclKind(DK), InvalidDecl(0), > >> > - HasAttrs(false), Implicit(false), Used(false), > Referenced(false), > >> > - Access(AS_none), FromASTFile(0), Hidden(DC && > >> > cast(DC)->Hidden), > >> > - IdentifierNamespace(getIdentifierNamespaceForKind(DK)), >
[PATCH] D34489: [scan-build-py] Patch to fix "-analyzer-config" option
haowei created this revision. Herald added a subscriber: whisperity. I noticed that when I use "-analyze-config" option in scan-build-py, it behaves differently from original perl based scan-build. For example, command: $ scan-build -analyzer-config ipa=basic-inlining make Will work without any issues on perl version of scan-build. But on scan-build-py it will throw an error message "error reading 'ipa=basic-inlining'". After debugging, it turns out that the scan-build-py does not put "-analyzer-config" flag in front of the analyzer config flags (in this case is the "ipa=basic-inlining") in the final clang command line. This patch fixes this issue. https://reviews.llvm.org/D34489 Files: tools/scan-build-py/libscanbuild/analyze.py Index: tools/scan-build-py/libscanbuild/analyze.py === --- tools/scan-build-py/libscanbuild/analyze.py +++ tools/scan-build-py/libscanbuild/analyze.py @@ -249,7 +249,7 @@ if args.output_format: result.append('-analyzer-output={0}'.format(args.output_format)) if args.analyzer_config: -result.append(args.analyzer_config) +result.extend(['-analyzer-config', args.analyzer_config]) if args.verbose >= 4: result.append('-analyzer-display-progress') if args.plugins: Index: tools/scan-build-py/libscanbuild/analyze.py === --- tools/scan-build-py/libscanbuild/analyze.py +++ tools/scan-build-py/libscanbuild/analyze.py @@ -249,7 +249,7 @@ if args.output_format: result.append('-analyzer-output={0}'.format(args.output_format)) if args.analyzer_config: -result.append(args.analyzer_config) +result.extend(['-analyzer-config', args.analyzer_config]) if args.verbose >= 4: result.append('-analyzer-display-progress') if args.plugins: ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D34264: Introduce -Wunguarded-availability-new, which is like -Wunguarded-availability, except that it's enabled by default for new deployment targets
dexonsmith added inline comments. Comment at: lib/Sema/SemaDeclAttr.cpp:7031 +Introduced) && +!S.Diags.isIgnored(diag::warn_unguarded_availability_new, Loc); +diag = NewWarning ? diag::warn_partial_availability_new arphaman wrote: > erik.pilkington wrote: > > Sorry to keep this going so long, but why are we even checking isIgnored? > > The only difference it could make in whether we emit a diagnostic is if > > both: -Wunguarded-availability and -Wno-unguarded-availability-new are > > passed in, which seems like it would never happen, right? Even if somebody > > did pass that in, it seems reasonable to warn on old stuff but not new > > stuff. Maybe I'm missing something here? > Right, it's to handle the `-Wunguarded-availability > -Wno-unguarded-availability-new` case. Your argument makes sense though, we > could allow `-Wunguarded-availability -Wno-unguarded-availability-new` where > we warn on old APIs. Although that still seems kinda weird to me. Maybe > @dexonsmith has an opinion about this? I don't think the exact behaviour of `-Wunguarded-availability -Wno-unguarded-availability-new` is terribly important. I'm fine either way. But, having a predictable command-line interface is nice, and I'd expect that combination to show diagnostics only for old APIs. Repository: rL LLVM https://reviews.llvm.org/D34264 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libcxxabi] r305977 - Add some catch(...) blocks to the tests so that if they fail, we get a good error message. No functional change.
Author: marshall Date: Wed Jun 21 19:49:03 2017 New Revision: 305977 URL: http://llvm.org/viewvc/llvm-project?rev=305977&view=rev Log: Add some catch(...) blocks to the tests so that if they fail, we get a good error message. No functional change. Modified: libcxxabi/trunk/test/incomplete_type.sh.cpp Modified: libcxxabi/trunk/test/incomplete_type.sh.cpp URL: http://llvm.org/viewvc/llvm-project/libcxxabi/trunk/test/incomplete_type.sh.cpp?rev=305977&r1=305976&r2=305977&view=diff == --- libcxxabi/trunk/test/incomplete_type.sh.cpp (original) +++ libcxxabi/trunk/test/incomplete_type.sh.cpp Wed Jun 21 19:49:03 2017 @@ -91,6 +91,8 @@ int main() { } catch (int NeverDefined::*p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch NeverDefined::*" ); } + AssertIncompleteTypeInfoEquals(ReturnTypeInfoIncompleteMP(), typeid(int IncompleteAtThrow::*)); try { ThrowIncompleteMP(); @@ -104,6 +106,7 @@ int main() { } catch (int IncompleteAtThrow::*p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch IncompleteAtThrow::*" ); } AssertIncompleteTypeInfoEquals(ReturnTypeInfoIncompletePP(), typeid(IncompleteAtThrow**)); try { @@ -114,6 +117,7 @@ int main() { } catch (IncompleteAtThrow** p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch IncompleteAtThrow**" ); } try { ThrowIncompletePMP(); @@ -125,6 +129,7 @@ int main() { } catch (int IncompleteAtThrow::**p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch IncompleteAtThrow::**" ); } AssertIncompleteTypeInfoEquals(ReturnTypeInfoCompleteMP(), typeid(int CompleteAtThrow::*)); try { @@ -139,6 +144,7 @@ int main() { } catch (int CompleteAtThrow::*p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch CompleteAtThrow::" ); } AssertIncompleteTypeInfoEquals(ReturnTypeInfoCompletePP(), typeid(CompleteAtThrow**)); try { @@ -153,6 +159,7 @@ int main() { } catch (CompleteAtThrow**p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch CompleteAtThrow**" ); } try { ThrowCompletePMP(); @@ -168,6 +175,7 @@ int main() { } catch (int CompleteAtThrow::**p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch CompleteAtThrow::**" ); } #if __cplusplus >= 201103L // Catch nullptr as complete type @@ -176,6 +184,7 @@ int main() { } catch (int IncompleteAtThrow::*p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch nullptr as IncompleteAtThrow::*" ); } // Catch nullptr as an incomplete type try { @@ -183,12 +192,16 @@ int main() { } catch (int CompleteAtThrow::*p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch nullptr as CompleteAtThrow::*" ); } + // Catch nullptr as a type that is never complete. try { ThrowNullptr(); } catch (int NeverDefined::*p) { assert(!p); } + catch(...) { assert(!"FAIL: Didn't catch nullptr as NeverDefined::*" ); } + #endif } #endif ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[PATCH] D29654: [OpenMP] Integrate OpenMP target region cubin into host binary
hfinkel accepted this revision. hfinkel added a comment. This revision is now accepted and ready to land. LGTM Repository: rL LLVM https://reviews.llvm.org/D29654 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits