[clang] 3197357 - Revert "[clang] Match -isysroot behaviour with system compiler on Darwin"

2023-08-23 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2023-08-23T14:50:02-07:00
New Revision: 3197357b7e39a58bc7eb0600eb337ac2a1c8c225

URL: 
https://github.com/llvm/llvm-project/commit/3197357b7e39a58bc7eb0600eb337ac2a1c8c225
DIFF: 
https://github.com/llvm/llvm-project/commit/3197357b7e39a58bc7eb0600eb337ac2a1c8c225.diff

LOG: Revert "[clang] Match -isysroot behaviour with system compiler on Darwin"

This reverts commit f24aa691aa4f25291db8f7c61c6e9007288859e7.

This change caused these two test failures on Darwin CI:
Clang.Tooling.clang-check-mac-libcxx-abspath.cpp
Clang.Tooling.clang-check-mac-libcxx-relpath.cpp

https://green.lab.llvm.org/green/job/clang-stage1-cmake-RA-incremental/37169/

More info in https://reviews.llvm.org/D157283

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/darwin-header-search-libcxx.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 5d8f006252fd9d..e45424a5f712a0 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2465,7 +2465,8 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
   //Also check whether this is used for setting library search paths.
   ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
 
-  if (DriverArgs.hasArg(options::OPT_nostdlibinc, options::OPT_nostdincxx))
+  if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
+options::OPT_nostdincxx))
 return;
 
   llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
@@ -2473,8 +2474,8 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
   switch (GetCXXStdlibType(DriverArgs)) {
   case ToolChain::CST_Libcxx: {
 // On Darwin, libc++ can be installed in one of the following two places:
-// 1. In a SDK (or a custom sysroot) in /usr/include/c++/v1
-// 2. Alongside the compiler in /include/c++/v1
+// 1. Alongside the compiler in /include/c++/v1
+// 2. In a SDK (or a custom sysroot) in /usr/include/c++/v1
 //
 // The precendence of paths is as listed above, i.e. we take the first path
 // that exists. Also note that we never include libc++ twice -- we take the
@@ -2482,17 +2483,6 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 // include_next could break).
 
 // Check for (1)
-llvm::SmallString<128> SysrootUsr = Sysroot;
-llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");
-if (getVFS().exists(SysrootUsr)) {
-  addSystemInclude(DriverArgs, CC1Args, SysrootUsr);
-  return;
-} else if (DriverArgs.hasArg(options::OPT_v)) {
-  llvm::errs() << "ignoring nonexistent directory \"" << SysrootUsr
-   << "\"\n";
-}
-
-// Otherwise, check for (2)
 // Get from '/bin' to '/include/c++/v1'.
 // Note that InstallBin can be relative, so we use '..' instead of
 // parent_path.
@@ -2507,6 +2497,17 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
+// Otherwise, check for (2)
+llvm::SmallString<128> SysrootUsr = Sysroot;
+llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");
+if (getVFS().exists(SysrootUsr)) {
+  addSystemInclude(DriverArgs, CC1Args, SysrootUsr);
+  return;
+} else if (DriverArgs.hasArg(options::OPT_v)) {
+  llvm::errs() << "ignoring nonexistent directory \"" << SysrootUsr
+   << "\"\n";
+}
+
 // Otherwise, don't add any path.
 break;
   }

diff  --git a/clang/test/Driver/darwin-header-search-libcxx.cpp 
b/clang/test/Driver/darwin-header-search-libcxx.cpp
index 4929511cd00af6..cc8ec9ceb89b3a 100644
--- a/clang/test/Driver/darwin-header-search-libcxx.cpp
+++ b/clang/test/Driver/darwin-header-search-libcxx.cpp
@@ -53,7 +53,7 @@
 // CHECK-LIBCXX-SYSROOT-1-NOT: "-internal-isystem" 
"[[TOOLCHAIN]]/usr/bin/../include/c++/v1"
 
 // Check with both headers in the sysroot and headers alongside the 
installation
-// (the  headers should be preferred over the headers in the 
toolchain).
+// (the headers in the toolchain should be preferred over the  
headers).
 // Ensure that both -isysroot and --sysroot work, and that isysroot has 
precedence
 // over --sysroot.
 //
@@ -89,10 +89,10 @@
 // RUN:   --check-prefix=CHECK-LIBCXX-SYSROOT_AND_TOOLCHAIN-1 %s
 //
 // CHECK-LIBCXX-SYSROOT_AND_TOOLCHAIN-1: "-cc1"
-// CHECK-LIBCXX-SYSROOT_AND_TOOLCHAIN-1: "-internal-isystem" 
"[[SYSROOT]]/usr/include/c++/v1"
-// CHECK-LIBCXX-SYSROOT_AND_TOOLCHAIN-1-NOT: "-internal-isystem" 
"[[TOOLCHAIN]]/usr/bin/../include/c++/v1"
+// CHECK-LIBCXX-SYSROOT_AND_TOOLCHAIN-1: "-internal-isystem" 
"[[TOOLCHAIN]]/usr/bin/../include/c++/v1"
+// CHECK-LIBCXX-SYSROOT_AND_TOOLCHAIN-1-NOT: "-internal-isystem" 
"[[SYSROOT]]/usr/include/c++/v1"
 
-// Make sure that using -nostdinc++ or -nostdlib will drop both the 

[clang] c8e2dd8 - [clang][darwin] An OS version preprocessor define is added for any darwin OS

2023-03-12 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2023-03-12T10:58:33-07:00
New Revision: c8e2dd8c6f490b68e41fe663b44535a8a21dfeab

URL: 
https://github.com/llvm/llvm-project/commit/c8e2dd8c6f490b68e41fe663b44535a8a21dfeab
DIFF: 
https://github.com/llvm/llvm-project/commit/c8e2dd8c6f490b68e41fe663b44535a8a21dfeab.diff

LOG: [clang][darwin] An OS version preprocessor define is added for any darwin 
OS

This change generalizes the OS version macro for all darwin OSes. The 
OS-specific OS version macros are still defined to preserve compatibility.

Added: 


Modified: 
clang/lib/Basic/Targets/OSTargets.cpp
clang/test/Frontend/darwin-version.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/OSTargets.cpp 
b/clang/lib/Basic/Targets/OSTargets.cpp
index 33a5b500e2d1c..763235fb10a52 100644
--- a/clang/lib/Basic/Targets/OSTargets.cpp
+++ b/clang/lib/Basic/Targets/OSTargets.cpp
@@ -108,9 +108,16 @@ void getDarwinDefines(MacroBuilder , const 
LangOptions ,
 Builder.defineMacro("__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__", Str);
   }
 
-  // Tell users about the kernel if there is one.
-  if (Triple.isOSDarwin())
+  if (Triple.isOSDarwin()) {
+// Any darwin OS defines a general darwin OS version macro in addition
+// to the other OS specific macros.
+assert(OsVersion.getMinor().value_or(0) < 100 &&
+   OsVersion.getSubminor().value_or(0) < 100 && "Invalid version!");
+Builder.defineMacro("__ENVIRONMENT_OS_VERSION_MIN_REQUIRED__", Str);
+
+// Tell users about the kernel if there is one.
 Builder.defineMacro("__MACH__");
+  }
 
   PlatformMinVersion = OsVersion;
 }

diff  --git a/clang/test/Frontend/darwin-version.c 
b/clang/test/Frontend/darwin-version.c
index 67f087feafe25..28826014e39f1 100644
--- a/clang/test/Frontend/darwin-version.c
+++ b/clang/test/Frontend/darwin-version.c
@@ -59,6 +59,11 @@
 
 // RUN: %clang_cc1 -triple arm64-apple-ios99.99.99 -dM -E %s | FileCheck 
--check-prefix=IOS99 %s
 // IOS99: __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ 99
+// IOS99-NEXT: __ENVIRONMENT_OS_VERSION_MIN_REQUIRED__ 99
 
 // RUN: %clang_cc1 -triple arm64-apple-watchos99.9 -dM -E %s | FileCheck 
--check-prefix=WATCHOS99 %s
-// WATCHOS99: __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ 990900
+// WATCHOS99: __ENVIRONMENT_OS_VERSION_MIN_REQUIRED__ 990900
+// WATCHOS99-NEXT: __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ 990900
+
+// RUN: %clang_cc1 -triple arm64-apple-macos12.4 -dM -E %s | FileCheck 
--check-prefix=MACOS124 %s
+// MACOS124: __ENVIRONMENT_OS_VERSION_MIN_REQUIRED__ 120400



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 21631b5 - [clang] fix intendation in newly added release note

2023-02-23 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2023-02-23T15:53:07-08:00
New Revision: 21631b567e88b5a1146a74b0a25f7a20afef8afb

URL: 
https://github.com/llvm/llvm-project/commit/21631b567e88b5a1146a74b0a25f7a20afef8afb
DIFF: 
https://github.com/llvm/llvm-project/commit/21631b567e88b5a1146a74b0a25f7a20afef8afb.diff

LOG: [clang] fix intendation in newly added release note

This fixes the llvm docs build bot.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c7204d8615a9..d7413def4d06 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -128,10 +128,10 @@ Attribute Changes in Clang
   the attributes on ``__declspec`` was ignored, while now it will be forwarded 
to the
   point where the alias is used.
 - Introduced a new ``USR`` (unified symbol resolution) clause inside of the
-existing ``__attribute__((external_source_symbol))`` attribute. Clang's indexer
-uses the optional USR value when indexing Clang's AST. This value is expected
-to be generated by an external compiler when generating C++ bindings during
-the compilation of the foreign language sources (e.g. Swift).
+  existing ``__attribute__((external_source_symbol))`` attribute. Clang's 
indexer
+  uses the optional USR value when indexing Clang's AST. This value is expected
+  to be generated by an external compiler when generating C++ bindings during
+  the compilation of the foreign language sources (e.g. Swift).
 
 Improvements to Clang's diagnostics
 ---



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c8b37e4 - [clang] extend external_source_symbol attribute with USR clause

2023-02-23 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2023-02-23T14:59:26-08:00
New Revision: c8b37e48f6f00bb2aa3882ca3cc26082f85ca999

URL: 
https://github.com/llvm/llvm-project/commit/c8b37e48f6f00bb2aa3882ca3cc26082f85ca999
DIFF: 
https://github.com/llvm/llvm-project/commit/c8b37e48f6f00bb2aa3882ca3cc26082f85ca999.diff

LOG: [clang] extend external_source_symbol attribute with USR clause

Allow the user to specify a concrete USR in the external_source_symbol 
attribute.
That will let Clang's indexer to use Swift USRs for Swift declarations that are
represented with C++ declarations.

This new clause is used by Swift when generating a C++ header representation
of a Swift module:
https://github.com/apple/swift/pull/63002

Differential Revision: https://reviews.llvm.org/D141324

Added: 
clang/test/Index/Core/external-source-symbol-attr-cxx.cpp
clang/test/Sema/attr-external-source-symbol-cxx.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticCommonKinds.td
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/include/clang/Parse/Parser.h
clang/lib/Index/USRGeneration.cpp
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/Parser.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/AST/ast-dump-attr.cpp
clang/test/Index/Core/external-source-symbol-attr.m
clang/test/Parser/attr-external-source-symbol.m
clang/test/Sema/attr-external-source-symbol.c
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a636ebb00f79..c7204d8615a90 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -127,6 +127,11 @@ Attribute Changes in Clang
 - ``__declspec`` attributes can now be used together with the using keyword. 
Before
   the attributes on ``__declspec`` was ignored, while now it will be forwarded 
to the
   point where the alias is used.
+- Introduced a new ``USR`` (unified symbol resolution) clause inside of the
+existing ``__attribute__((external_source_symbol))`` attribute. Clang's indexer
+uses the optional USR value when indexing Clang's AST. This value is expected
+to be generated by an external compiler when generating C++ bindings during
+the compilation of the foreign language sources (e.g. Swift).
 
 Improvements to Clang's diagnostics
 ---

diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index fc2c7f7e37f45..8858bb6bec850 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -287,23 +287,22 @@ class VariadicEnumArgument values,
 }
 
 // This handles one spelling of an attribute.
-class Spelling {
+class Spelling {
   string Name = name;
   string Variety = variety;
+  int Version = version;
 }
 
 class GNU : Spelling;
 class Declspec : Spelling;
 class Microsoft : Spelling;
 class CXX11
-: Spelling {
+: Spelling {
   string Namespace = namespace;
-  int Version = version;
 }
 class C2x
-: Spelling {
+: Spelling {
   string Namespace = namespace;
-  int Version = version;
 }
 
 class Keyword : Spelling;
@@ -321,7 +320,8 @@ class GCC : Spelling {
 // The Clang spelling implies GNU, CXX11<"clang", name>, and optionally,
 // C2x<"clang", name>. This spelling should be used for any Clang-specific
 // attributes.
-class Clang : Spelling {
+class Clang
+: Spelling {
   bit AllowInC = allowInC;
 }
 
@@ -958,10 +958,12 @@ static llvm::StringRef 
canonicalizePlatformName(llvm::StringRef Platform) {
 }
 
 def ExternalSourceSymbol : InheritableAttr {
-  let Spellings = [Clang<"external_source_symbol">];
+  let Spellings = [Clang<"external_source_symbol", /*allowInC=*/1,
+   /*version=*/20230206>];
   let Args = [StringArgument<"language", 1>,
   StringArgument<"definedIn", 1>,
-  BoolArgument<"generatedDeclaration", 1>];
+  BoolArgument<"generatedDeclaration", 1>,
+  StringArgument<"USR", 1>];
   let HasCustomParsing = 1;
   let Subjects = SubjectList<[Named]>;
   let Documentation = [ExternalSourceSymbolDocs];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index eebbf6863dd43..cbf28688a7408 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1750,6 +1750,19 @@ defined_in=\ *string-literal*
   source containers are modules, so ``defined_in`` should specify the Swift
   module name.
 
+USR=\ *string-literal*
+  String that specifies a unified symbol resolution (USR) value for this
+  declaration. USR string uniquely identifies this particular declaration, and
+  is typically used when constructing an index of a codebase.
+  The USR value in this attribute is expected to be generated by an external
+  compiler that compiled 

[clang] 60a33de - [clang][darwin] Use consistent version define stringifying logic for different Darwin OSes

2022-11-29 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-11-29T14:22:34-08:00
New Revision: 60a33ded751c86fff9ac1c4bdd2b341fbe4b0649

URL: 
https://github.com/llvm/llvm-project/commit/60a33ded751c86fff9ac1c4bdd2b341fbe4b0649
DIFF: 
https://github.com/llvm/llvm-project/commit/60a33ded751c86fff9ac1c4bdd2b341fbe4b0649.diff

LOG: [clang][darwin] Use consistent version define stringifying logic for 
different Darwin OSes

Added: 


Modified: 
clang/lib/Basic/Targets/OSTargets.cpp
clang/test/Frontend/darwin-version.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/OSTargets.cpp 
b/clang/lib/Basic/Targets/OSTargets.cpp
index d11b9f5dbba5a..33a5b500e2d1c 100644
--- a/clang/lib/Basic/Targets/OSTargets.cpp
+++ b/clang/lib/Basic/Targets/OSTargets.cpp
@@ -67,48 +67,23 @@ void getDarwinDefines(MacroBuilder , const 
LangOptions ,
 return;
   }
 
-  // Set the appropriate OS version define.
-  if (Triple.isiOS()) {
-assert(OsVersion < VersionTuple(100) && "Invalid version!");
-char Str[7];
-if (OsVersion.getMajor() < 10) {
-  Str[0] = '0' + OsVersion.getMajor();
-  Str[1] = '0' + (OsVersion.getMinor().value_or(0) / 10);
-  Str[2] = '0' + (OsVersion.getMinor().value_or(0) % 10);
-  Str[3] = '0' + (OsVersion.getSubminor().value_or(0) / 10);
-  Str[4] = '0' + (OsVersion.getSubminor().value_or(0) % 10);
-  Str[5] = '\0';
-} else {
-  // Handle versions >= 10.
-  Str[0] = '0' + (OsVersion.getMajor() / 10);
-  Str[1] = '0' + (OsVersion.getMajor() % 10);
-  Str[2] = '0' + (OsVersion.getMinor().value_or(0) / 10);
-  Str[3] = '0' + (OsVersion.getMinor().value_or(0) % 10);
-  Str[4] = '0' + (OsVersion.getSubminor().value_or(0) / 10);
-  Str[5] = '0' + (OsVersion.getSubminor().value_or(0) % 10);
-  Str[6] = '\0';
-}
-if (Triple.isTvOS())
-  Builder.defineMacro("__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__", Str);
-else
-  Builder.defineMacro("__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__",
-  Str);
-
-  } else if (Triple.isWatchOS()) {
-assert(OsVersion < VersionTuple(10) && "Invalid version!");
-char Str[6];
+  assert(OsVersion < VersionTuple(100) && "Invalid version!");
+  char Str[7];
+  if (Triple.isMacOSX() && OsVersion < VersionTuple(10, 10)) {
+Str[0] = '0' + (OsVersion.getMajor() / 10);
+Str[1] = '0' + (OsVersion.getMajor() % 10);
+Str[2] = '0' + std::min(OsVersion.getMinor().value_or(0), 9U);
+Str[3] = '0' + std::min(OsVersion.getSubminor().value_or(0), 9U);
+Str[4] = '\0';
+  } else if (!Triple.isMacOSX() && OsVersion.getMajor() < 10) {
 Str[0] = '0' + OsVersion.getMajor();
 Str[1] = '0' + (OsVersion.getMinor().value_or(0) / 10);
 Str[2] = '0' + (OsVersion.getMinor().value_or(0) % 10);
 Str[3] = '0' + (OsVersion.getSubminor().value_or(0) / 10);
 Str[4] = '0' + (OsVersion.getSubminor().value_or(0) % 10);
 Str[5] = '\0';
-Builder.defineMacro("__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__", Str);
-  } else if (Triple.isDriverKit()) {
-assert(OsVersion.getMajor() < 100 &&
-   OsVersion.getMinor().value_or(0) < 100 &&
-   OsVersion.getSubminor().value_or(0) < 100 && "Invalid version!");
-char Str[7];
+  } else {
+// Handle versions >= 10.
 Str[0] = '0' + (OsVersion.getMajor() / 10);
 Str[1] = '0' + (OsVersion.getMajor() % 10);
 Str[2] = '0' + (OsVersion.getMinor().value_or(0) / 10);
@@ -116,30 +91,20 @@ void getDarwinDefines(MacroBuilder , const 
LangOptions ,
 Str[4] = '0' + (OsVersion.getSubminor().value_or(0) / 10);
 Str[5] = '0' + (OsVersion.getSubminor().value_or(0) % 10);
 Str[6] = '\0';
+  }
+
+  // Set the appropriate OS version define.
+  if (Triple.isTvOS()) {
+Builder.defineMacro("__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__", Str);
+  } else if (Triple.isiOS()) {
+Builder.defineMacro("__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__", Str);
+  } else if (Triple.isWatchOS()) {
+Builder.defineMacro("__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__", Str);
+  } else if (Triple.isDriverKit()) {
+assert(OsVersion.getMinor().value_or(0) < 100 &&
+   OsVersion.getSubminor().value_or(0) < 100 && "Invalid version!");
 Builder.defineMacro("__ENVIRONMENT_DRIVERKIT_VERSION_MIN_REQUIRED__", Str);
   } else if (Triple.isMacOSX()) {
-// Note that the Driver allows versions which aren't representable in the
-// define (because we only get a single digit for the minor and micro
-// revision numbers). So, we limit them to the maximum representable
-// version.
-assert(OsVersion < VersionTuple(100) && "Invalid version!");
-char Str[7];
-if (OsVersion < VersionTuple(10, 10)) {
-  Str[0] = '0' + (OsVersion.getMajor() / 10);
-  Str[1] = '0' + (OsVersion.getMajor() % 10);
-  Str[2] = '0' + std::min(OsVersion.getMinor().value_or(0), 9U);
-  Str[3] = '0' + 

[clang] 2a67014 - [clang][driver][darwin] Enforce consistent major version limit for any Darwin OS

2022-11-29 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-11-29T13:18:56-08:00
New Revision: 2a6701444af816f9048c788513abf4d2e9fa785d

URL: 
https://github.com/llvm/llvm-project/commit/2a6701444af816f9048c788513abf4d2e9fa785d
DIFF: 
https://github.com/llvm/llvm-project/commit/2a6701444af816f9048c788513abf4d2e9fa785d.diff

LOG: [clang][driver][darwin] Enforce consistent major version limit for any 
Darwin OS

Limit can also be bumped up to 999 to allow OS versions over 100

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/darwin-version.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index c3a7627460ae..050b90a344a4 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2187,17 +2187,20 @@ void Darwin::AddDeploymentTarget(DerivedArgList ) 
const {
 
   unsigned Major, Minor, Micro;
   bool HadExtra;
+  // The major version should not be over this number.
+  const unsigned MajorVersionLimit = 1000;
   // Set the tool chain target information.
   if (Platform == MacOS) {
 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
Micro, HadExtra) ||
-HadExtra || Major < 10 || Major >= 100 || Minor >= 100 || Micro >= 100)
+HadExtra || Major < 10 || Major >= MajorVersionLimit || Minor >= 100 ||
+Micro >= 100)
   getDriver().Diag(diag::err_drv_invalid_version_number)
   << OSTarget->getAsString(Args, Opts);
   } else if (Platform == IPhoneOS) {
 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
Micro, HadExtra) ||
-HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
+HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
   getDriver().Diag(diag::err_drv_invalid_version_number)
   << OSTarget->getAsString(Args, Opts);
 ;
@@ -2229,19 +2232,20 @@ void Darwin::AddDeploymentTarget(DerivedArgList ) 
const {
   } else if (Platform == TvOS) {
 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
Micro, HadExtra) ||
-HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
+HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
   getDriver().Diag(diag::err_drv_invalid_version_number)
   << OSTarget->getAsString(Args, Opts);
   } else if (Platform == WatchOS) {
 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
Micro, HadExtra) ||
-HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
+HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
   getDriver().Diag(diag::err_drv_invalid_version_number)
   << OSTarget->getAsString(Args, Opts);
   } else if (Platform == DriverKit) {
 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
Micro, HadExtra) ||
-HadExtra || Major < 19 || Major >= 100 || Minor >= 100 || Micro >= 100)
+HadExtra || Major < 19 || Major >= MajorVersionLimit || Minor >= 100 ||
+Micro >= 100)
   getDriver().Diag(diag::err_drv_invalid_version_number)
   << OSTarget->getAsString(Args, Opts);
   } else

diff  --git a/clang/test/Driver/darwin-version.c 
b/clang/test/Driver/darwin-version.c
index db6a81cd6542..71f3f2c4cc17 100644
--- a/clang/test/Driver/darwin-version.c
+++ b/clang/test/Driver/darwin-version.c
@@ -332,3 +332,18 @@
 // RUN:   FileCheck --check-prefix=CHECK-MACOS11 %s
 
 // CHECK-MACOS11: "x86_64-apple-macosx11.0.0"
+
+// RUN: %clang -target arm64-apple-macos999 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-MACOS999 %s
+
+// CHECK-MACOS999: "arm64-apple-macosx999.0.0"
+
+// RUN: %clang -target arm64-apple-watchos99 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-WATCHOS99 %s
+
+// CHECK-WATCHOS99: "arm64-apple-watchos99.0.0"
+
+// RUN: not %clang -target arm64-apple-ios99 -c %s 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-IOS99 %s
+
+// CHECK-IOS99: error: invalid version number in '-target 
arm64-apple-ios99'



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f4be5ed - [clang][pp] only __is_target_environment(unknown) should match unknown target triple environment

2022-11-02 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-11-02T13:49:04-07:00
New Revision: f4be5ed6a3fef0b2b0c60b29e1c0638926638d28

URL: 
https://github.com/llvm/llvm-project/commit/f4be5ed6a3fef0b2b0c60b29e1c0638926638d28
DIFF: 
https://github.com/llvm/llvm-project/commit/f4be5ed6a3fef0b2b0c60b29e1c0638926638d28.diff

LOG: [clang][pp] only __is_target_environment(unknown) should match unknown 
target triple environment

Added: 
clang/test/Preprocessor/is_target_unknown_environment.c

Modified: 
clang/lib/Lex/PPMacroExpansion.cpp

Removed: 




diff  --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index e79d76cbf3857..ffc758d47c7a2 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -1447,6 +1447,11 @@ static bool isTargetEnvironment(const TargetInfo ,
 const IdentifierInfo *II) {
   std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str();
   llvm::Triple Env(EnvName);
+  // The unknown environment is matched only if
+  // '__is_target_environment(unknown)' is used.
+  if (Env.getEnvironment() == llvm::Triple::UnknownEnvironment &&
+  EnvName != "---unknown")
+return false;
   return TI.getTriple().getEnvironment() == Env.getEnvironment();
 }
 

diff  --git a/clang/test/Preprocessor/is_target_unknown_environment.c 
b/clang/test/Preprocessor/is_target_unknown_environment.c
new file mode 100644
index 0..9462ef442fecd
--- /dev/null
+++ b/clang/test/Preprocessor/is_target_unknown_environment.c
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -triple x86_64-apple-macos12 -verify %s
+
+// expected-no-diagnostics
+
+#if !__is_target_environment(unknown)
+#error "mismatching environment"
+#endif
+
+#if __is_target_environment(simulator) || __is_target_environment(SIMULATOR)
+#error "mismatching environment"
+#endif
+
+#if __is_target_environment(invalidEnv)
+#error "invalid environment must not be matched"
+#endif



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2498964 - [clang][test] NFC, check in darwin-ld-platform-version-macos-requires-darwin.c should be more permissive

2022-10-12 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-10-12T15:57:27-07:00
New Revision: 24989646a5216cc6f8c6d336a17e7cb2f5c60454

URL: 
https://github.com/llvm/llvm-project/commit/24989646a5216cc6f8c6d336a17e7cb2f5c60454
DIFF: 
https://github.com/llvm/llvm-project/commit/24989646a5216cc6f8c6d336a17e7cb2f5c60454.diff

LOG: [clang][test] NFC, check in 
darwin-ld-platform-version-macos-requires-darwin.c should be more permissive

some Darwin CI uses older SDK that reports different SDK version here
https://green.lab.llvm.org/green/job/clang-stage1-RA/

Added: 


Modified: 
clang/test/Driver/darwin-ld-platform-version-macos-requires-darwin.c

Removed: 




diff  --git 
a/clang/test/Driver/darwin-ld-platform-version-macos-requires-darwin.c 
b/clang/test/Driver/darwin-ld-platform-version-macos-requires-darwin.c
index 24c0c0c20b70..6026ab5d41d3 100644
--- a/clang/test/Driver/darwin-ld-platform-version-macos-requires-darwin.c
+++ b/clang/test/Driver/darwin-ld-platform-version-macos-requires-darwin.c
@@ -5,6 +5,6 @@
 
 // RUN: %clang -fuse-ld= -arch arm64 -mlinker-version=520 -isysroot 
%t/MacOSX12.sdk/does-not-exist -### %t/f.o 2>&1 | FileCheck %s
 
-// CHECK: "-platform_version" "macos" "[[NUMBER:[0-9]+]].0.0" "[[NUMBER]].0"
+// CHECK: "-platform_version" "macos" "{{[0-9]+}}.0.0" "{{[0-9]+}}.{{[0-9]+}}"
 
 // REQUIRES: system-darwin



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7d85f6b - [clang][driver][darwin] Ensure that the SDK version passed to -platform_version has a minor version number 0

2022-10-04 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-10-04T10:23:38-07:00
New Revision: 7d85f6b1af26c8f749f0c217d7aae694cc3931eb

URL: 
https://github.com/llvm/llvm-project/commit/7d85f6b1af26c8f749f0c217d7aae694cc3931eb
DIFF: 
https://github.com/llvm/llvm-project/commit/7d85f6b1af26c8f749f0c217d7aae694cc3931eb.diff

LOG: [clang][driver][darwin] Ensure that the SDK version passed to 
-platform_version has a minor version number 0

The linker requires at least a "major.minor" for the SDK version, so it will 
fail when we don't have
a minor version in the case we don't actually have an SDK info.

Added: 
clang/test/Driver/darwin-ld-platform-version-macos-requires-darwin.c

Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 50572ff04ff85..758961d3bf79a 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -3103,6 +3103,8 @@ void Darwin::addPlatformVersionArgs(const 
llvm::opt::ArgList ,
 
 if (SDKInfo) {
   VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
+  if (!SDKVersion.getMinor())
+SDKVersion = VersionTuple(SDKVersion.getMajor(), 0);
   CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
 } else {
   // Use an SDK version that's matching the deployment target if the 
SDK

diff  --git 
a/clang/test/Driver/darwin-ld-platform-version-macos-requires-darwin.c 
b/clang/test/Driver/darwin-ld-platform-version-macos-requires-darwin.c
new file mode 100644
index 0..24c0c0c20b70a
--- /dev/null
+++ b/clang/test/Driver/darwin-ld-platform-version-macos-requires-darwin.c
@@ -0,0 +1,10 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: touch %t/f.o
+// RUN: mkdir -p %t/MacOSX12.0.sdk
+
+// RUN: %clang -fuse-ld= -arch arm64 -mlinker-version=520 -isysroot 
%t/MacOSX12.sdk/does-not-exist -### %t/f.o 2>&1 | FileCheck %s
+
+// CHECK: "-platform_version" "macos" "[[NUMBER:[0-9]+]].0.0" "[[NUMBER]].0"
+
+// REQUIRES: system-darwin



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 79e09af - [clang] Fix the begin location of concepts specialization expression

2022-05-25 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-05-25T12:39:21-07:00
New Revision: 79e09af1d6e11b05c6484868f15a9a2db298699c

URL: 
https://github.com/llvm/llvm-project/commit/79e09af1d6e11b05c6484868f15a9a2db298699c
DIFF: 
https://github.com/llvm/llvm-project/commit/79e09af1d6e11b05c6484868f15a9a2db298699c.diff

LOG: [clang] Fix the begin location of concepts specialization expression

The concept specialization expression should start at the location of
the  nested qualifiers when it has nested qualifiers.
This ensures that libclang reports correct source ranges that include
all subexpressions when visiting the expression.

Differential Revision: https://reviews.llvm.org/D126332

Added: 


Modified: 
clang/include/clang/AST/ExprConcepts.h
clang/test/Index/index-concepts.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ExprConcepts.h 
b/clang/include/clang/AST/ExprConcepts.h
index 6849b65b71c0c..fd9cd31f3b90b 100644
--- a/clang/include/clang/AST/ExprConcepts.h
+++ b/clang/include/clang/AST/ExprConcepts.h
@@ -122,6 +122,8 @@ class ConceptSpecializationExpr final : public Expr, public 
ConceptReference,
   }
 
   SourceLocation getBeginLoc() const LLVM_READONLY {
+if (auto QualifierLoc = getNestedNameSpecifierLoc())
+  return QualifierLoc.getBeginLoc();
 return ConceptName.getBeginLoc();
   }
 

diff  --git a/clang/test/Index/index-concepts.cpp 
b/clang/test/Index/index-concepts.cpp
index ba4b87111ff48..b8d41e841e619 100644
--- a/clang/test/Index/index-concepts.cpp
+++ b/clang/test/Index/index-concepts.cpp
@@ -64,8 +64,8 @@ concept ConTwoTemplateParams = ns::ConInNamespace && 
ConWithLogicalAnd;
 // CHECK: index-concepts.cpp:[[@LINE-1]]:9: 
ConceptDecl=ConTwoTemplateParams:[[@LINE-1]]:9 (Definition) 
Extent=[[[@LINE-2]]:1 - [[@LINE-1]]:79]
 // CHECK: index-concepts.cpp:[[@LINE-3]]:17: 
TemplateTypeParameter=T1:[[@LINE-3]]:17 (Definition) Extent=[[[@LINE-3]]:11 - 
[[@LINE-3]]:19] [access=public]
 // CHECK: index-concepts.cpp:[[@LINE-4]]:27: 
TemplateTypeParameter=T2:[[@LINE-4]]:27 (Definition) Extent=[[[@LINE-4]]:21 - 
[[@LINE-4]]:29] [access=public]
-// CHECK: index-concepts.cpp:[[@LINE-4]]:36: BinaryOperator= 
Extent=[[[@LINE-4]]:36 - [[@LINE-4]]:79]
-// CHECK: index-concepts.cpp:[[@LINE-5]]:36: ConceptSpecializationExpr= 
Extent=[[[@LINE-5]]:36 - [[@LINE-5]]:54]
+// CHECK: index-concepts.cpp:[[@LINE-4]]:32: BinaryOperator= 
Extent=[[[@LINE-4]]:32 - [[@LINE-4]]:79]
+// CHECK: index-concepts.cpp:[[@LINE-5]]:32: ConceptSpecializationExpr= 
Extent=[[[@LINE-5]]:32 - [[@LINE-5]]:54]
 // CHECK: index-concepts.cpp:[[@LINE-6]]:32: NamespaceRef=ns:55:11 
Extent=[[[@LINE-6]]:32 - [[@LINE-6]]:34]
 // CHECK: index-concepts.cpp:[[@LINE-7]]:36: TemplateRef=ConInNamespace:58:9 
Extent=[[[@LINE-7]]:36 - [[@LINE-7]]:50]
 // CHECK: index-concepts.cpp:[[@LINE-8]]:58: ConceptSpecializationExpr= 
Extent=[[[@LINE-8]]:58 - [[@LINE-8]]:79]
@@ -107,7 +107,7 @@ requires ns::ConInNamespace && ConTwoTemplateParams {}
 // CHECK: index-concepts.cpp:[[@LINE-4]]:16: 
TemplateTypeParameter=T:[[@LINE-4]]:16 (Definition) Extent=[[[@LINE-4]]:10 - 
[[@LINE-4]]:17] [access=public]
 // CHECK: index-concepts.cpp:[[@LINE-4]]:36: ParmDecl=x:[[@LINE-4]]:36 
(Definition) Extent=[[[@LINE-4]]:27 - [[@LINE-4]]:37]
 // CHECK: index-concepts.cpp:[[@LINE-5]]:33: TypeRef=T:[[@LINE-6]]:16 
Extent=[[[@LINE-5]]:33 - [[@LINE-5]]:34]
-// CHECK: index-concepts.cpp:[[@LINE-5]]:14: ConceptSpecializationExpr= 
Extent=[[[@LINE-5]]:14 - [[@LINE-5]]:31]
+// CHECK: index-concepts.cpp:[[@LINE-5]]:10: ConceptSpecializationExpr= 
Extent=[[[@LINE-5]]:10 - [[@LINE-5]]:31]
 // CHECK: index-concepts.cpp:[[@LINE-6]]:10: NamespaceRef=ns:55:11 
Extent=[[[@LINE-6]]:10 - [[@LINE-6]]:12]
 // CHECK: index-concepts.cpp:[[@LINE-7]]:14: TemplateRef=ConInNamespace:58:9 
Extent=[[[@LINE-7]]:14 - [[@LINE-7]]:28]
 // CHECK: index-concepts.cpp:[[@LINE-8]]:29: TypeRef=T:[[@LINE-10]]:16 
Extent=[[[@LINE-8]]:29 - [[@LINE-8]]:30]



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1b34f1e - [clang][test] mark tests added in ee8524087c78 as unsupported on AIX

2022-05-24 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-05-24T13:39:37-07:00
New Revision: 1b34f1e996565bc5e4f2be14b89f881f8fe0f3b9

URL: 
https://github.com/llvm/llvm-project/commit/1b34f1e996565bc5e4f2be14b89f881f8fe0f3b9
DIFF: 
https://github.com/llvm/llvm-project/commit/1b34f1e996565bc5e4f2be14b89f881f8fe0f3b9.diff

LOG: [clang][test] mark tests added in ee8524087c78 as unsupported on AIX

These tests are failing on the PPC64 AIX CI bot, but it's unclear why,
as they pass on other CI jobs.
I marked them as unsupported on AIX for now while investigating the failure.

Added: 


Modified: 
clang/test/Index/index-concept-kind.cpp
clang/test/Index/index-concepts.cpp

Removed: 




diff  --git a/clang/test/Index/index-concept-kind.cpp 
b/clang/test/Index/index-concept-kind.cpp
index 7aaf814f5f989..f33fc6bc5cc0d 100644
--- a/clang/test/Index/index-concept-kind.cpp
+++ b/clang/test/Index/index-concept-kind.cpp
@@ -1,5 +1,5 @@
 // RUN: c-index-test -index-file %s -std=gnu++20 | FileCheck %s
-
+// UNSUPPORTED: aix
 template 
 concept LargeType = sizeof(T) > 8;
 // CHECK: [indexDeclaration]: kind: concept | name: LargeType | USR: 
c:@CT@LargeType | lang: C | cursor: ConceptDecl=LargeType:[[@LINE-1]]:9 
(Definition) | loc: [[@LINE-1]]:9 | semantic-container: [TU] | 
lexical-container: [TU] | isRedecl: 0 | isDef: 1 | isContainer: 0 | isImplicit: 0

diff  --git a/clang/test/Index/index-concepts.cpp 
b/clang/test/Index/index-concepts.cpp
index 9887e9fdc6541..ba4b87111ff48 100644
--- a/clang/test/Index/index-concepts.cpp
+++ b/clang/test/Index/index-concepts.cpp
@@ -1,5 +1,5 @@
 // RUN: c-index-test -test-load-source all %s -std=gnu++20 
-fno-delayed-template-parsing | FileCheck %s
-
+// UNSUPPORTED: aix
 template
 struct type_trait {
 const static bool value = false;



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ee85240 - [libclang] add supporting for indexing/visiting C++ concepts

2022-05-24 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-05-24T10:02:53-07:00
New Revision: ee8524087c78a673fcf5486ded69ee597a85e0f1

URL: 
https://github.com/llvm/llvm-project/commit/ee8524087c78a673fcf5486ded69ee597a85e0f1
DIFF: 
https://github.com/llvm/llvm-project/commit/ee8524087c78a673fcf5486ded69ee597a85e0f1.diff

LOG: [libclang] add supporting for indexing/visiting C++ concepts

This commit builds upon recently added indexing support for C++ concepts
from https://reviews.llvm.org/D124441 by extending libclang to
support indexing and visiting concepts, constraints and requires
expressions as well.

Differential Revision: https://reviews.llvm.org/D126031

Added: 
clang/test/Index/index-concept-kind.cpp
clang/test/Index/index-concepts.cpp

Modified: 
clang/include/clang-c/Index.h
clang/lib/Sema/SemaCodeComplete.cpp
clang/tools/c-index-test/c-index-test.c
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/CXCursor.cpp
clang/tools/libclang/CXIndexDataConsumer.cpp
clang/tools/libclang/CXIndexDataConsumer.h
clang/tools/libclang/CursorVisitor.h

Removed: 




diff  --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index c4da7df6595d1..70de5195d0580 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -2189,7 +2189,17 @@ enum CXCursorKind {
*/
   CXCursor_CXXAddrspaceCastExpr = 152,
 
-  CXCursor_LastExpr = CXCursor_CXXAddrspaceCastExpr,
+  /**
+   * Expression that references a C++20 concept.
+   */
+  CXCursor_ConceptSpecializationExpr = 153,
+
+  /**
+   * Expression that references a C++20 concept.
+   */
+  CXCursor_RequiresExpr = 154,
+
+  CXCursor_LastExpr = CXCursor_RequiresExpr,
 
   /* Statements */
   CXCursor_FirstStmt = 200,
@@ -2700,8 +2710,13 @@ enum CXCursorKind {
* a friend declaration.
*/
   CXCursor_FriendDecl = 603,
+  /**
+   * a concept declaration.
+   */
+  CXCursor_ConceptDecl = 604,
+
   CXCursor_FirstExtraDecl = CXCursor_ModuleImportDecl,
-  CXCursor_LastExtraDecl = CXCursor_FriendDecl,
+  CXCursor_LastExtraDecl = CXCursor_ConceptDecl,
 
   /**
* A code completion overload candidate.
@@ -6319,7 +6334,8 @@ typedef enum {
   CXIdxEntity_CXXDestructor = 23,
   CXIdxEntity_CXXConversionFunction = 24,
   CXIdxEntity_CXXTypeAlias = 25,
-  CXIdxEntity_CXXInterface = 26
+  CXIdxEntity_CXXInterface = 26,
+  CXIdxEntity_CXXConcept = 27
 
 } CXIdxEntityKind;
 

diff  --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index 30720c197d7e7..d35e9c6e42bf2 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -4044,6 +4044,9 @@ CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
   case Decl::ObjCTypeParam:
 return CXCursor_TemplateTypeParameter;
 
+  case Decl::Concept:
+return CXCursor_ConceptDecl;
+
   default:
 if (const auto *TD = dyn_cast(D)) {
   switch (TD->getTagKind()) {

diff  --git a/clang/test/Index/index-concept-kind.cpp 
b/clang/test/Index/index-concept-kind.cpp
new file mode 100644
index 0..7aaf814f5f989
--- /dev/null
+++ b/clang/test/Index/index-concept-kind.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test -index-file %s -std=gnu++20 | FileCheck %s
+
+template 
+concept LargeType = sizeof(T) > 8;
+// CHECK: [indexDeclaration]: kind: concept | name: LargeType | USR: 
c:@CT@LargeType | lang: C | cursor: ConceptDecl=LargeType:[[@LINE-1]]:9 
(Definition) | loc: [[@LINE-1]]:9 | semantic-container: [TU] | 
lexical-container: [TU] | isRedecl: 0 | isDef: 1 | isContainer: 0 | isImplicit: 0
+
+template 
+// CHECK: [indexEntityReference]: kind: concept | name: LargeType | USR: 
c:@CT@LargeType | lang: C | cursor: TemplateRef=LargeType:4:9 | loc: 
[[@LINE-1]]:11 | :: kind: function-template | name: f | USR: 
c:@FT@>1#Tf#v# | lang: C++ | container: [<>] | refkind: direct | role: ref
+void f();

diff  --git a/clang/test/Index/index-concepts.cpp 
b/clang/test/Index/index-concepts.cpp
new file mode 100644
index 0..9887e9fdc6541
--- /dev/null
+++ b/clang/test/Index/index-concepts.cpp
@@ -0,0 +1,186 @@
+// RUN: c-index-test -test-load-source all %s -std=gnu++20 
-fno-delayed-template-parsing | FileCheck %s
+
+template
+struct type_trait {
+const static bool value = false;
+};
+
+template<>
+struct type_trait {
+const static bool value = true;
+};
+
+template 
+requires (type_trait::value)
+// CHECK: index-concepts.cpp:[[@LINE-1]]:10: ParenExpr= Extent=[[[@LINE-1]]:10 
- [[@LINE-1]]:32]
+// CHECK: index-concepts.cpp:[[@LINE-2]]:11: DeclRefExpr= 
Extent=[[[@LINE-2]]:11 - [[@LINE-2]]:31]
+// CHECK: index-concepts.cpp:[[@LINE-3]]:11: TemplateRef=type_trait:4:8 
Extent=[[[@LINE-3]]:11 - [[@LINE-3]]:21]
+// CHECK: index-concepts.cpp:[[@LINE-4]]:22: TypeRef=T:13:17 
Extent=[[[@LINE-4]]:22 - [[@LINE-4]]:23]
+void indexRequiresClause() {
+}
+
+template
+requires (type_trait::value)
+// CHECK: 

[clang] 688622f - [clang][test] Add -fuse-ld= to test cases added in d238acd1131ec2670acf5cf47b89069ca6c2e86c to resolve test failure with CLANG_DEFAULT_LINKER=lld

2022-02-14 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-02-14T13:21:39-08:00
New Revision: 688622ff607ca1b15e76f9b4f6216f78dd22fab2

URL: 
https://github.com/llvm/llvm-project/commit/688622ff607ca1b15e76f9b4f6216f78dd22fab2
DIFF: 
https://github.com/llvm/llvm-project/commit/688622ff607ca1b15e76f9b4f6216f78dd22fab2.diff

LOG: [clang][test] Add -fuse-ld= to test cases added in 
d238acd1131ec2670acf5cf47b89069ca6c2e86c to resolve test failure with 
CLANG_DEFAULT_LINKER=lld

Added: 


Modified: 
clang/test/Driver/darwin-ld-platform-version-target-version.c
clang/test/Driver/darwin-zippered-target-version.c

Removed: 




diff  --git a/clang/test/Driver/darwin-ld-platform-version-target-version.c 
b/clang/test/Driver/darwin-ld-platform-version-target-version.c
index ec9825d21bde0..cc88e015f82c5 100644
--- a/clang/test/Driver/darwin-ld-platform-version-target-version.c
+++ b/clang/test/Driver/darwin-ld-platform-version-target-version.c
@@ -9,9 +9,9 @@
 // RUN:   | FileCheck --check-prefix=ARM64_NEW %s
 // RUN: %clang -target arm64-apple-macos10.15 -darwin-target-variant 
arm64-apple-ios13.1-macabi  -isysroot %S/Inputs/MacOSX10.15.versioned.sdk 
-mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=ARM64_NEW-INV %s
-// RUN: %clang -target arm64-apple-ios13.1-macabi -darwin-target-variant 
arm64-apple-macos10.15 -isysroot %S/Inputs/MacOSX10.15.versioned.sdk 
-mlinker-version=400 -### %t.o 2>&1 \
+// RUN: %clang -target arm64-apple-ios13.1-macabi -darwin-target-variant 
arm64-apple-macos10.15 -isysroot %S/Inputs/MacOSX10.15.versioned.sdk -fuse-ld= 
-mlinker-version=400 -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=ARM64_OLD %s
-// RUN: %clang -target arm64-apple-macos10.15 -darwin-target-variant 
arm64-apple-ios13.1-macabi -isysroot %S/Inputs/MacOSX10.15.versioned.sdk 
-mlinker-version=400 -### %t.o 2>&1 \
+// RUN: %clang -target arm64-apple-macos10.15 -darwin-target-variant 
arm64-apple-ios13.1-macabi -isysroot %S/Inputs/MacOSX10.15.versioned.sdk 
-fuse-ld= -mlinker-version=400 -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=ARM64_OLD-INV %s
 
 // CHECK: "-platform_version" "mac catalyst" "13.1.0" "13.1"

diff  --git a/clang/test/Driver/darwin-zippered-target-version.c 
b/clang/test/Driver/darwin-zippered-target-version.c
index 91449fa2331ee..0f739a44f4d4a 100644
--- a/clang/test/Driver/darwin-zippered-target-version.c
+++ b/clang/test/Driver/darwin-zippered-target-version.c
@@ -1,10 +1,10 @@
 // RUN: %clang -target unknown-apple-macos10.15 -arch x86_64 -arch x86_64h 
-arch i386 \
 // RUN:   -darwin-target-variant x86_64-apple-ios13.1-macabi 
-darwin-target-variant x86_64h-apple-ios13.1-macabi \
-// RUN:   %s -mlinker-version=400 -### 2>&1 | FileCheck %s
+// RUN:   %s -fuse-ld= -mlinker-version=400 -### 2>&1 | FileCheck %s
 
 // RUN: %clang -target unknown-apple-ios13.1-macabi -arch x86_64 -arch x86_64h 
\
 // RUN:   -darwin-target-variant x86_64-apple-macos10.15 \
-// RUN:   %s -mlinker-version=400 -### 2>&1 | FileCheck 
--check-prefix=INVERTED %s
+// RUN:   %s -fuse-ld= -mlinker-version=400 -### 2>&1 | FileCheck 
--check-prefix=INVERTED %s
 
 // CHECK: "-arch" "x86_64" "-macosx_version_min" "10.15.0" 
"-maccatalyst_version_min" "13.1"
 // CHECK: "-arch" "x86_64h" "-macosx_version_min" "10.15.0" 
"-maccatalyst_version_min" "13.1"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d238acd - [clang][driver] add clang driver support for emitting macho files with two build version load commands

2022-02-14 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-02-14T12:27:14-08:00
New Revision: d238acd1131ec2670acf5cf47b89069ca6c2e86c

URL: 
https://github.com/llvm/llvm-project/commit/d238acd1131ec2670acf5cf47b89069ca6c2e86c
DIFF: 
https://github.com/llvm/llvm-project/commit/d238acd1131ec2670acf5cf47b89069ca6c2e86c.diff

LOG: [clang][driver] add clang driver support for emitting macho files with two 
build version load commands

This patch extends clang driver to pass the right flags to the clang frontend, 
and ld64,
so that they can emit macho files with two build version load commands. It adds 
a new
0darwin-target-variant option which complements -target and also can be used to 
specify different
target variants when multi-arch compilations are invoked with multiple -arch 
commands.

Differential Revision: https://reviews.llvm.org/D118862

Added: 
clang/test/Driver/darwin-ld-platform-version-target-version.c
clang/test/Driver/darwin-objc-runtime-maccatalyst-target-variant.m
clang/test/Driver/darwin-target-variant-sdk-version.c
clang/test/Driver/darwin-target-variant.c
clang/test/Driver/darwin-zippered-target-version.c

Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 427cb788c3a4c..b688c121b1c07 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -637,4 +637,8 @@ def err_drv_cuda_offload_only_emit_bc : Error<
 def warn_drv_jmc_requires_debuginfo : Warning<
   "/JMC requires debug info. Use '/Zi', '/Z7' or other debug options; option 
ignored">,
   InGroup;
+
+def err_drv_target_variant_invalid : Error<
+  "unsupported '%0' value '%1'; use 'ios-macabi' instead">;
+
 }

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index cd0d56cecaca1..b81973155cae6 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3994,6 +3994,9 @@ def : Separate<["--"], "no-system-header-prefix">, 
Alias, Group;
 def target : Joined<["--"], "target=">, Flags<[NoXarchOption, CoreOption]>,
   HelpText<"Generate code for the given target">;
+def darwin_target_variant : Separate<["-"], "darwin-target-variant">,
+  Flags<[NoXarchOption, CoreOption]>,
+  HelpText<"Generate code for an additional runtime variant of the deployment 
target">;
 def print_supported_cpus : Flag<["-", "--"], "print-supported-cpus">,
   Group, Flags<[CC1Option, CoreOption]>,
   HelpText<"Print supported cpu models for the given target (if target is not 
specified,"

diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index df860ccc6be4f..3c408010b5b19 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1496,6 +1496,10 @@ struct DarwinPlatform {
   /// Returns true if the simulator environment can be inferred from the arch.
   bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
 
+  const Optional () const {
+return TargetVariantTriple;
+  }
+
   /// Adds the -m-version-min argument to the compiler invocation.
   void addOSVersionMinArgument(DerivedArgList , const OptTable ) {
 if (Argument)
@@ -1558,6 +1562,16 @@ struct DarwinPlatform {
   }
 }
   }
+  // In a zippered build, we could be building for a macOS target that's
+  // lower than the version that's implied by the OS version. In that case
+  // we need to use the minimum version as the native target version.
+  if (TargetVariantTriple) {
+auto TargetVariantVersion = TargetVariantTriple->getOSVersion();
+if (TargetVariantVersion.getMajor()) {
+  if (TargetVariantVersion < NativeTargetVersion)
+NativeTargetVersion = TargetVariantVersion;
+}
+  }
   break;
 }
 default:
@@ -1567,12 +1581,14 @@ struct DarwinPlatform {
 
   static DarwinPlatform
   createFromTarget(const llvm::Triple , StringRef OSVersion, Arg *A,
+   Optional TargetVariantTriple,
const Optional ) {
 DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
   A);
 VersionTuple OsVersion = TT.getOSVersion();
 if (OsVersion.getMajor() == 0)
   Result.HasOSVersion = false;
+Result.TargetVariantTriple = TargetVariantTriple;
 Result.setEnvironment(TT.getEnvironment(), OsVersion, SDKInfo);
 return Result;
   }
@@ -1656,6 +1672,7 @@ struct DarwinPlatform {
   bool HasOSVersion = true, InferSimulatorFromArch = true;
   Arg *Argument;
   StringRef EnvVarName;
+  Optional TargetVariantTriple;
 };
 
 /// Returns the 

[clang] 00cd6c0 - [Preprocessor] Reduce the memory overhead of `#define` directives (Recommit)

2022-02-14 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-02-14T09:27:44-08:00
New Revision: 00cd6c04202acf71f74c670b2dd4343929d1f45f

URL: 
https://github.com/llvm/llvm-project/commit/00cd6c04202acf71f74c670b2dd4343929d1f45f
DIFF: 
https://github.com/llvm/llvm-project/commit/00cd6c04202acf71f74c670b2dd4343929d1f45f.diff

LOG: [Preprocessor] Reduce the memory overhead of `#define` directives 
(Recommit)

Recently we observed high memory pressure caused by clang during some parallel 
builds.
We discovered that we have several projects that have a large number of #define 
directives
in their TUs (on the order of millions), which caused huge memory consumption 
in clang due
to a lot of allocations for MacroInfo. We would like to reduce the memory 
overhead of
clang for a single #define to reduce the memory overhead for these files, to 
allow us to
reduce the memory pressure on the system during highly parallel builds. This 
change achieves
that by removing the SmallVector in MacroInfo and instead storing the tokens in 
an array
allocated using the bump pointer allocator, after all tokens are lexed.

The added unit test with 100 #define directives illustrates the problem. 
Prior to this
change, on arm64 macOS, clang's PP bump pointer allocator allocated 272007616 
bytes, and
used roughly 272 bytes per #define. After this change, clang's PP bump pointer 
allocator
allocates 120002016 bytes, and uses only roughly 120 bytes per #define.

For an example test file that we have internally with 7.8 million #define 
directives, this
change produces the following improvement on arm64 macOS: Persistent allocation 
footprint for
this test case file as it's being compiled to LLVM IR went down 22% from 5.28 
GB to 4.07 GB
and the total allocations went down 14% from 8.26 GB to 7.05 GB. Furthermore, 
this change
reduced the total number of allocations made by the system for this clang 
invocation from
1454853 to 133663, an order of magnitude improvement.

The recommit fixes the LLDB build failure.

Differential Revision: https://reviews.llvm.org/D117348

Added: 
clang/unittests/Lex/PPMemoryAllocationsTest.cpp

Modified: 
clang/include/clang/Lex/MacroInfo.h
clang/lib/Lex/MacroInfo.cpp
clang/lib/Lex/PPDirectives.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/unittests/Lex/CMakeLists.txt
lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/MacroInfo.h 
b/clang/include/clang/Lex/MacroInfo.h
index 0347a7a37186b..1947bc8fc509e 100644
--- a/clang/include/clang/Lex/MacroInfo.h
+++ b/clang/include/clang/Lex/MacroInfo.h
@@ -54,11 +54,14 @@ class MacroInfo {
   /// macro, this includes the \c __VA_ARGS__ identifier on the list.
   IdentifierInfo **ParameterList = nullptr;
 
+  /// This is the list of tokens that the macro is defined to.
+  const Token *ReplacementTokens = nullptr;
+
   /// \see ParameterList
   unsigned NumParameters = 0;
 
-  /// This is the list of tokens that the macro is defined to.
-  SmallVector ReplacementTokens;
+  /// \see ReplacementTokens
+  unsigned NumReplacementTokens = 0;
 
   /// Length in characters of the macro definition.
   mutable unsigned DefinitionLength;
@@ -230,26 +233,47 @@ class MacroInfo {
   bool isWarnIfUnused() const { return IsWarnIfUnused; }
 
   /// Return the number of tokens that this macro expands to.
-  unsigned getNumTokens() const { return ReplacementTokens.size(); }
+  unsigned getNumTokens() const { return NumReplacementTokens; }
 
   const Token (unsigned Tok) const {
-assert(Tok < ReplacementTokens.size() && "Invalid token #");
+assert(Tok < NumReplacementTokens && "Invalid token #");
 return ReplacementTokens[Tok];
   }
 
-  using tokens_iterator = SmallVectorImpl::const_iterator;
+  using const_tokens_iterator = const Token *;
 
-  tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); }
-  tokens_iterator tokens_end() const { return ReplacementTokens.end(); }
-  bool tokens_empty() const { return ReplacementTokens.empty(); }
-  ArrayRef tokens() const { return ReplacementTokens; }
+  const_tokens_iterator tokens_begin() const { return ReplacementTokens; }
+  const_tokens_iterator tokens_end() const {
+return ReplacementTokens + NumReplacementTokens;
+  }
+  bool tokens_empty() const { return NumReplacementTokens == 0; }
+  ArrayRef tokens() const {
+return llvm::makeArrayRef(ReplacementTokens, NumReplacementTokens);
+  }
 
-  /// Add the specified token to the replacement text for the macro.
-  void AddTokenToBody(const Token ) {
+  llvm::MutableArrayRef
+  allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator ) {
+assert(ReplacementTokens == nullptr && NumReplacementTokens == 0 &&
+   "Token list already allocated!");
+NumReplacementTokens = NumTokens;
+Token *NewReplacementTokens = 

[clang] 3f05192 - Revert "[Preprocessor] Reduce the memory overhead of `#define` directives"

2022-02-11 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-02-11T15:53:16-08:00
New Revision: 3f05192c4c40bc79b1db431a7a36baaa9491eebb

URL: 
https://github.com/llvm/llvm-project/commit/3f05192c4c40bc79b1db431a7a36baaa9491eebb
DIFF: 
https://github.com/llvm/llvm-project/commit/3f05192c4c40bc79b1db431a7a36baaa9491eebb.diff

LOG: Revert "[Preprocessor] Reduce the memory overhead of `#define` directives"

This reverts commit 0d9b91524ea4db3760791bba15773c386a26d8ec.

This change broke LLDB's build. I will need to recommit after fixing LLDB.

Added: 


Modified: 
clang/include/clang/Lex/MacroInfo.h
clang/lib/Lex/MacroInfo.cpp
clang/lib/Lex/PPDirectives.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/unittests/Lex/CMakeLists.txt

Removed: 
clang/unittests/Lex/PPMemoryAllocationsTest.cpp



diff  --git a/clang/include/clang/Lex/MacroInfo.h 
b/clang/include/clang/Lex/MacroInfo.h
index 1947bc8fc509e..0347a7a37186b 100644
--- a/clang/include/clang/Lex/MacroInfo.h
+++ b/clang/include/clang/Lex/MacroInfo.h
@@ -54,14 +54,11 @@ class MacroInfo {
   /// macro, this includes the \c __VA_ARGS__ identifier on the list.
   IdentifierInfo **ParameterList = nullptr;
 
-  /// This is the list of tokens that the macro is defined to.
-  const Token *ReplacementTokens = nullptr;
-
   /// \see ParameterList
   unsigned NumParameters = 0;
 
-  /// \see ReplacementTokens
-  unsigned NumReplacementTokens = 0;
+  /// This is the list of tokens that the macro is defined to.
+  SmallVector ReplacementTokens;
 
   /// Length in characters of the macro definition.
   mutable unsigned DefinitionLength;
@@ -233,47 +230,26 @@ class MacroInfo {
   bool isWarnIfUnused() const { return IsWarnIfUnused; }
 
   /// Return the number of tokens that this macro expands to.
-  unsigned getNumTokens() const { return NumReplacementTokens; }
+  unsigned getNumTokens() const { return ReplacementTokens.size(); }
 
   const Token (unsigned Tok) const {
-assert(Tok < NumReplacementTokens && "Invalid token #");
+assert(Tok < ReplacementTokens.size() && "Invalid token #");
 return ReplacementTokens[Tok];
   }
 
-  using const_tokens_iterator = const Token *;
+  using tokens_iterator = SmallVectorImpl::const_iterator;
 
-  const_tokens_iterator tokens_begin() const { return ReplacementTokens; }
-  const_tokens_iterator tokens_end() const {
-return ReplacementTokens + NumReplacementTokens;
-  }
-  bool tokens_empty() const { return NumReplacementTokens == 0; }
-  ArrayRef tokens() const {
-return llvm::makeArrayRef(ReplacementTokens, NumReplacementTokens);
-  }
+  tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); }
+  tokens_iterator tokens_end() const { return ReplacementTokens.end(); }
+  bool tokens_empty() const { return ReplacementTokens.empty(); }
+  ArrayRef tokens() const { return ReplacementTokens; }
 
-  llvm::MutableArrayRef
-  allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator ) {
-assert(ReplacementTokens == nullptr && NumReplacementTokens == 0 &&
-   "Token list already allocated!");
-NumReplacementTokens = NumTokens;
-Token *NewReplacementTokens = PPAllocator.Allocate(NumTokens);
-ReplacementTokens = NewReplacementTokens;
-return llvm::makeMutableArrayRef(NewReplacementTokens, NumTokens);
-  }
-
-  void setTokens(ArrayRef Tokens, llvm::BumpPtrAllocator ) {
+  /// Add the specified token to the replacement text for the macro.
+  void AddTokenToBody(const Token ) {
 assert(
 !IsDefinitionLengthCached &&
 "Changing replacement tokens after definition length got calculated");
-assert(ReplacementTokens == nullptr && NumReplacementTokens == 0 &&
-   "Token list already set!");
-if (Tokens.empty())
-  return;
-
-NumReplacementTokens = Tokens.size();
-Token *NewReplacementTokens = PPAllocator.Allocate(Tokens.size());
-std::copy(Tokens.begin(), Tokens.end(), NewReplacementTokens);
-ReplacementTokens = NewReplacementTokens;
+ReplacementTokens.push_back(Tok);
   }
 
   /// Return true if this macro is enabled.

diff  --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp
index f5702130d1819..1ccd140364aeb 100644
--- a/clang/lib/Lex/MacroInfo.cpp
+++ b/clang/lib/Lex/MacroInfo.cpp
@@ -28,25 +28,6 @@
 
 using namespace clang;
 
-namespace {
-
-// MacroInfo is expected to take 40 bytes on platforms with an 8 byte pointer
-// and 4 byte SourceLocation.
-template  class MacroInfoSizeChecker {
-public:
-  constexpr static bool AsExpected = true;
-};
-template <> class MacroInfoSizeChecker<8> {
-public:
-  constexpr static bool AsExpected =
-  sizeof(MacroInfo) == (32 + sizeof(SourceLocation) * 2);
-};
-
-static_assert(MacroInfoSizeChecker::AsExpected,
-  "Unexpected size of MacroInfo");
-
-} // end namespace
-
 MacroInfo::MacroInfo(SourceLocation DefLoc)
 : Location(DefLoc), 

[clang] 0d9b915 - [Preprocessor] Reduce the memory overhead of `#define` directives

2022-02-11 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-02-11T15:01:10-08:00
New Revision: 0d9b91524ea4db3760791bba15773c386a26d8ec

URL: 
https://github.com/llvm/llvm-project/commit/0d9b91524ea4db3760791bba15773c386a26d8ec
DIFF: 
https://github.com/llvm/llvm-project/commit/0d9b91524ea4db3760791bba15773c386a26d8ec.diff

LOG: [Preprocessor] Reduce the memory overhead of `#define` directives

Recently we observed high memory pressure caused by clang during some parallel 
builds.
We discovered that we have several projects that have a large number of #define 
directives
in their TUs (on the order of millions), which caused huge memory consumption 
in clang due
to a lot of allocations for MacroInfo. We would like to reduce the memory 
overhead of
clang for a single #define to reduce the memory overhead for these files, to 
allow us to
reduce the memory pressure on the system during highly parallel builds. This 
change achieves
that by removing the SmallVector in MacroInfo and instead storing the tokens in 
an array
allocated using the bump pointer allocator, after all tokens are lexed.

The added unit test with 100 #define directives illustrates the problem. 
Prior to this
change, on arm64 macOS, clang's PP bump pointer allocator allocated 272007616 
bytes, and
used roughly 272 bytes per #define. After this change, clang's PP bump pointer 
allocator
allocates 120002016 bytes, and uses only roughly 120 bytes per #define.

For an example test file that we have internally with 7.8 million #define 
directives, this
change produces the following improvement on arm64 macOS: Persistent allocation 
footprint for
this test case file as it's being compiled to LLVM IR went down 22% from 5.28 
GB to 4.07 GB
and the total allocations went down 14% from 8.26 GB to 7.05 GB. Furthermore, 
this change
reduced the total number of allocations made by the system for this clang 
invocation from
1454853 to 133663, an order of magnitude improvement.

Differential Revision: https://reviews.llvm.org/D117348

Added: 
clang/unittests/Lex/PPMemoryAllocationsTest.cpp

Modified: 
clang/include/clang/Lex/MacroInfo.h
clang/lib/Lex/MacroInfo.cpp
clang/lib/Lex/PPDirectives.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/unittests/Lex/CMakeLists.txt

Removed: 




diff  --git a/clang/include/clang/Lex/MacroInfo.h 
b/clang/include/clang/Lex/MacroInfo.h
index 0347a7a37186b..1947bc8fc509e 100644
--- a/clang/include/clang/Lex/MacroInfo.h
+++ b/clang/include/clang/Lex/MacroInfo.h
@@ -54,11 +54,14 @@ class MacroInfo {
   /// macro, this includes the \c __VA_ARGS__ identifier on the list.
   IdentifierInfo **ParameterList = nullptr;
 
+  /// This is the list of tokens that the macro is defined to.
+  const Token *ReplacementTokens = nullptr;
+
   /// \see ParameterList
   unsigned NumParameters = 0;
 
-  /// This is the list of tokens that the macro is defined to.
-  SmallVector ReplacementTokens;
+  /// \see ReplacementTokens
+  unsigned NumReplacementTokens = 0;
 
   /// Length in characters of the macro definition.
   mutable unsigned DefinitionLength;
@@ -230,26 +233,47 @@ class MacroInfo {
   bool isWarnIfUnused() const { return IsWarnIfUnused; }
 
   /// Return the number of tokens that this macro expands to.
-  unsigned getNumTokens() const { return ReplacementTokens.size(); }
+  unsigned getNumTokens() const { return NumReplacementTokens; }
 
   const Token (unsigned Tok) const {
-assert(Tok < ReplacementTokens.size() && "Invalid token #");
+assert(Tok < NumReplacementTokens && "Invalid token #");
 return ReplacementTokens[Tok];
   }
 
-  using tokens_iterator = SmallVectorImpl::const_iterator;
+  using const_tokens_iterator = const Token *;
 
-  tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); }
-  tokens_iterator tokens_end() const { return ReplacementTokens.end(); }
-  bool tokens_empty() const { return ReplacementTokens.empty(); }
-  ArrayRef tokens() const { return ReplacementTokens; }
+  const_tokens_iterator tokens_begin() const { return ReplacementTokens; }
+  const_tokens_iterator tokens_end() const {
+return ReplacementTokens + NumReplacementTokens;
+  }
+  bool tokens_empty() const { return NumReplacementTokens == 0; }
+  ArrayRef tokens() const {
+return llvm::makeArrayRef(ReplacementTokens, NumReplacementTokens);
+  }
 
-  /// Add the specified token to the replacement text for the macro.
-  void AddTokenToBody(const Token ) {
+  llvm::MutableArrayRef
+  allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator ) {
+assert(ReplacementTokens == nullptr && NumReplacementTokens == 0 &&
+   "Token list already allocated!");
+NumReplacementTokens = NumTokens;
+Token *NewReplacementTokens = PPAllocator.Allocate(NumTokens);
+ReplacementTokens = NewReplacementTokens;
+return llvm::makeMutableArrayRef(NewReplacementTokens, NumTokens);
+  }

[clang] b58bf76 - [clang][driver] update the darwin driver to point to correct macho_embedded path

2022-02-07 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-02-07T16:50:58-08:00
New Revision: b58bf76f97f4bffe91bcf673dcc1231c0cfc0921

URL: 
https://github.com/llvm/llvm-project/commit/b58bf76f97f4bffe91bcf673dcc1231c0cfc0921
DIFF: 
https://github.com/llvm/llvm-project/commit/b58bf76f97f4bffe91bcf673dcc1231c0cfc0921.diff

LOG: [clang][driver] update the darwin driver to point to correct 
macho_embedded path

Compiler-rt started emitting the macho_embedded libraries in
`/lib/darwin/macho_embedded` after
https://reviews.llvm.org/D105765 / 1e03c37b97b6176a60404d84665c40321f4e33a4,
so update the clang's driver to reflect that.

Differential Revision: https://reviews.llvm.org/D115403

Added: 

clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.hard_pic.a

clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.hard_static.a

clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.soft_pic.a

clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.soft_static.a

Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp

Removed: 

clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.hard_pic.a

clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.hard_static.a

clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.soft_pic.a

clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.soft_static.a



diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index f7da3f187814f..e71511747e44d 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1152,8 +1152,9 @@ void MachO::AddLinkRuntimeLib(const ArgList , 
ArgStringList ,
   DarwinLibName += getOSLibraryNameSuffix();
   DarwinLibName += IsShared ? "_dynamic.dylib" : ".a";
   SmallString<128> Dir(getDriver().ResourceDir);
-  llvm::sys::path::append(
-  Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin");
+  llvm::sys::path::append(Dir, "lib", "darwin");
+  if (Opts & RLO_IsEmbedded)
+llvm::sys::path::append(Dir, "macho_embedded");
 
   SmallString<128> P(Dir);
   llvm::sys::path::append(P, DarwinLibName);

diff  --git 
a/clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.hard_pic.a
 
b/clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.hard_pic.a
similarity index 100%
rename from 
clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.hard_pic.a
rename to 
clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.hard_pic.a

diff  --git 
a/clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.hard_static.a
 
b/clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.hard_static.a
similarity index 100%
rename from 
clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.hard_static.a
rename to 
clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.hard_static.a

diff  --git 
a/clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.soft_pic.a
 
b/clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.soft_pic.a
similarity index 100%
rename from 
clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.soft_pic.a
rename to 
clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.soft_pic.a

diff  --git 
a/clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.soft_static.a
 
b/clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.soft_static.a
similarity index 100%
rename from 
clang/test/Driver/Inputs/resource_dir/lib/macho_embedded/libclang_rt.soft_static.a
rename to 
clang/test/Driver/Inputs/resource_dir/lib/darwin/macho_embedded/libclang_rt.soft_static.a



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 979d0ee - [clang] fix out of bounds access in an empty string when lexing a _Pragma with missing string token

2022-02-02 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-02-02T11:16:11-08:00
New Revision: 979d0ee8ab30a175220af3b39a6df7d56de9d2c8

URL: 
https://github.com/llvm/llvm-project/commit/979d0ee8ab30a175220af3b39a6df7d56de9d2c8
DIFF: 
https://github.com/llvm/llvm-project/commit/979d0ee8ab30a175220af3b39a6df7d56de9d2c8.diff

LOG: [clang] fix out of bounds access in an empty string when lexing a _Pragma 
with missing string token

The lexer can attempt to lex a _Pragma and crash with an out of bounds string 
access when it's
lexing a _Pragma whose string token is an invalid buffer, e.g. when a module 
header file from which the macro
expansion for that token was deleted from the file system.

Differential Revision: https://reviews.llvm.org/D116052

Added: 
clang/test/Preprocessor/pragma-missing-string-token.c

Modified: 
clang/lib/Frontend/PrintPreprocessedOutput.cpp
clang/lib/Lex/Pragma.cpp

Removed: 




diff  --git a/clang/lib/Frontend/PrintPreprocessedOutput.cpp 
b/clang/lib/Frontend/PrintPreprocessedOutput.cpp
index 1d0022bda474c..e2fc862849ad1 100644
--- a/clang/lib/Frontend/PrintPreprocessedOutput.cpp
+++ b/clang/lib/Frontend/PrintPreprocessedOutput.cpp
@@ -189,7 +189,8 @@ class PrintPPOutputPPCallbacks : public PPCallbacks {
   bool MoveToLine(const Token , bool RequireStartOfLine) {
 PresumedLoc PLoc = SM.getPresumedLoc(Tok.getLocation());
 unsigned TargetLine = PLoc.isValid() ? PLoc.getLine() : CurLine;
-bool IsFirstInFile = Tok.isAtStartOfLine() && PLoc.getLine() == 1;
+bool IsFirstInFile =
+Tok.isAtStartOfLine() && PLoc.isValid() && PLoc.getLine() == 1;
 return MoveToLine(TargetLine, RequireStartOfLine) || IsFirstInFile;
   }
 

diff  --git a/clang/lib/Lex/Pragma.cpp b/clang/lib/Lex/Pragma.cpp
index eb7e7cbc47140..eb370e8a0ecd6 100644
--- a/clang/lib/Lex/Pragma.cpp
+++ b/clang/lib/Lex/Pragma.cpp
@@ -263,7 +263,12 @@ void Preprocessor::Handle_Pragma(Token ) {
   }
 
   SourceLocation RParenLoc = Tok.getLocation();
-  std::string StrVal = getSpelling(StrTok);
+  bool Invalid = false;
+  std::string StrVal = getSpelling(StrTok, );
+  if (Invalid) {
+Diag(PragmaLoc, diag::err__Pragma_malformed);
+return;
+  }
 
   // The _Pragma is lexically sound.  Destringize according to C11 6.10.9.1:
   // "The string literal is destringized by deleting any encoding prefix,

diff  --git a/clang/test/Preprocessor/pragma-missing-string-token.c 
b/clang/test/Preprocessor/pragma-missing-string-token.c
new file mode 100644
index 0..5f40b2f4fdb97
--- /dev/null
+++ b/clang/test/Preprocessor/pragma-missing-string-token.c
@@ -0,0 +1,27 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -emit-module -x c -fmodules -I %t/Inputs -fmodule-name=aa 
%t/Inputs/module.modulemap -o %t/aa.pcm
+// RUN: rm %t/Inputs/b.h
+// RUN: not %clang_cc1 -E -fmodules -I %t/Inputs -fmodule-file=%t/aa.pcm %s -o 
- -fallow-pcm-with-compiler-errors 2>&1 | FileCheck %s
+
+//--- Inputs/module.modulemap
+module aa {
+header "a.h"
+header "b.h"
+}
+
+//--- Inputs/a.h
+#define TEST(x) x
+
+//--- Inputs/b.h
+#define SUB "mypragma"
+
+//--- test.c
+#include "a.h"
+
+_Pragma(SUB);
+int a = TEST(SUB);
+
+// CHECK: int a
+// CHECK: 1 error generated



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 116c1be - [clang][macho] add clang frontend support for emitting macho files with two build version load commands

2022-02-02 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2022-02-02T08:30:39-08:00
New Revision: 116c1bea65ac268bc46a2373220c81d02fc0a256

URL: 
https://github.com/llvm/llvm-project/commit/116c1bea65ac268bc46a2373220c81d02fc0a256
DIFF: 
https://github.com/llvm/llvm-project/commit/116c1bea65ac268bc46a2373220c81d02fc0a256.diff

LOG: [clang][macho] add clang frontend support for emitting macho files with 
two build version load commands

This patch extends clang frontend to add metadata that can be used to emit 
macho files with two build version load commands.
It utilizes "darwin.target_variant.triple" and "darwin.target_variant.SDK 
Version" metadata names for that.

MachO uses two build version load commands to represent an object file / binary 
that is targeting both the macOS target,
and the Mac Catalyst target. At runtime, a dynamic library that supports both 
targets can be loaded from either a native
macOS or a Mac Catalyst app on a macOS system. We want to add support to this 
to upstream to LLVM to be able to build
compiler-rt for both targets, to finish the complete support for the Mac 
Catalyst platform, which is right now targetable
by upstream clang, but the compiler-rt bits aren't supported because of the 
lack of this multiple build version support.

Differential Revision: https://reviews.llvm.org/D115415

Added: 
clang/test/CodeGen/darwin-target-variant.c

Modified: 
clang/include/clang/Basic/TargetInfo.h
clang/include/clang/Basic/TargetOptions.h
clang/include/clang/Driver/Options.td
clang/lib/Basic/Targets.cpp
clang/lib/CodeGen/ModuleBuilder.cpp
clang/lib/Frontend/CompilerInvocation.cpp
llvm/include/llvm/IR/Module.h
llvm/lib/IR/Module.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index a49342a34f3e..324c123e5be7 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -235,6 +235,8 @@ class TargetInfo : public virtual TransferrableTargetInfo,
 
   unsigned MaxOpenCLWorkGroupSize;
 
+  Optional DarwinTargetVariantTriple;
+
   // TargetInfo Constructor.  Default initializes all fields.
   TargetInfo(const llvm::Triple );
 
@@ -1608,6 +1610,21 @@ class TargetInfo : public virtual 
TransferrableTargetInfo,
   /// Whether target allows debuginfo types for decl only variables/functions.
   virtual bool allowDebugInfoForExternalRef() const { return false; }
 
+  /// Returns the darwin target variant triple, the variant of the deployment
+  /// target for which the code is being compiled.
+  const llvm::Triple *getDarwinTargetVariantTriple() const {
+return DarwinTargetVariantTriple ? DarwinTargetVariantTriple.getPointer()
+ : nullptr;
+  }
+
+  /// Returns the version of the darwin target variant SDK which was used 
during
+  /// the compilation if one was specified, or an empty version otherwise.
+  const Optional getDarwinTargetVariantSDKVersion() const {
+return !getTargetOpts().DarwinTargetVariantSDKVersion.empty()
+   ? getTargetOpts().DarwinTargetVariantSDKVersion
+   : Optional();
+  }
+
 protected:
   /// Copy type and layout related info.
   void copyAuxTarget(const TargetInfo *Aux);

diff  --git a/clang/include/clang/Basic/TargetOptions.h 
b/clang/include/clang/Basic/TargetOptions.h
index 81c15adb8248..696abf4ca473 100644
--- a/clang/include/clang/Basic/TargetOptions.h
+++ b/clang/include/clang/Basic/TargetOptions.h
@@ -91,6 +91,13 @@ class TargetOptions {
   /// * CUDA compilation uses it to control parts of CUDA compilation
   ///   in clang that depend on specific version of the CUDA SDK.
   llvm::VersionTuple SDKVersion;
+
+  /// The name of the darwin target- ariant triple to compile for.
+  std::string DarwinTargetVariantTriple;
+
+  /// The version of the darwin target variant SDK which was used during the
+  /// compilation.
+  llvm::VersionTuple DarwinTargetVariantSDKVersion;
 };
 
 }  // end namespace clang

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 53e68ed2cef9..5aa1e851c258 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4777,6 +4777,13 @@ def target_abi : Separate<["-"], "target-abi">,
   MarshallingInfoString>;
 def target_sdk_version_EQ : Joined<["-"], "target-sdk-version=">,
   HelpText<"The version of target SDK used for compilation">;
+def darwin_target_variant_triple : Separate<["-"], 
"darwin-target-variant-triple">,
+  HelpText<"Specify the darwin target variant triple">,
+  MarshallingInfoString>,
+  Normalizer<"normalizeTriple">;
+def darwin_target_variant_sdk_version_EQ : Joined<["-"],
+  "darwin-target-variant-sdk-version=">,
+  HelpText<"The version of darwin target variant SDK used for compilation">;
 
 }
 

diff  --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index 

[clang] 809c6a5 - [Clang] Extract availability mapping from VersionMap for watchOS/tvOS

2022-01-05 Thread Alex Lorenz via cfe-commits

Author: Egor Zhdan
Date: 2022-01-05T17:00:03-08:00
New Revision: 809c6a5a1d2f4366ab0e602c9d963b73f380b74e

URL: 
https://github.com/llvm/llvm-project/commit/809c6a5a1d2f4366ab0e602c9d963b73f380b74e
DIFF: 
https://github.com/llvm/llvm-project/commit/809c6a5a1d2f4366ab0e602c9d963b73f380b74e.diff

LOG: [Clang] Extract availability mapping from VersionMap for watchOS/tvOS

This change makes it possible to extract iOS-to-another-platform version 
mappings from `VersionMap` in the `SDKSettings.json` file in Darwin SDKs, for 
example, `iOS_watchOS` and `iOS_tvOS`.

This code was originally authored by Alex Lorenz.

rdar://81491680

Differential Revision: https://reviews.llvm.org/D116615

Added: 


Modified: 
clang/lib/Basic/DarwinSDKInfo.cpp
clang/unittests/Basic/DarwinSDKInfoTest.cpp

Removed: 




diff  --git a/clang/lib/Basic/DarwinSDKInfo.cpp 
b/clang/lib/Basic/DarwinSDKInfo.cpp
index fe35f77782c92..64bcb45a4cd85 100644
--- a/clang/lib/Basic/DarwinSDKInfo.cpp
+++ b/clang/lib/Basic/DarwinSDKInfo.cpp
@@ -84,6 +84,25 @@ DarwinSDKInfo::parseDarwinSDKSettingsJSON(const 
llvm::json::Object *Obj) {
   llvm::DenseMap>
   VersionMappings;
   if (const auto *VM = Obj->getObject("VersionMap")) {
+// FIXME: Generalize this out beyond iOS-deriving targets.
+// Look for ios_ version mapping for targets that derive from 
ios.
+for (const auto  : *VM) {
+  auto Pair = StringRef(KV.getFirst()).split("_");
+  if (Pair.first.compare_insensitive("ios") == 0) {
+llvm::Triple TT(llvm::Twine("--") + Pair.second.lower());
+if (TT.getOS() != llvm::Triple::UnknownOS) {
+  auto Mapping = RelatedTargetVersionMapping::parseJSON(
+  *KV.getSecond().getAsObject(), *MaximumDeploymentVersion);
+  if (Mapping)
+VersionMappings[OSEnvPair(llvm::Triple::IOS,
+  llvm::Triple::UnknownEnvironment,
+  TT.getOS(),
+  llvm::Triple::UnknownEnvironment)
+.Value] = std::move(Mapping);
+}
+  }
+}
+
 if (const auto *Mapping = VM->getObject("macOS_iOSMac")) {
   auto VersionMap = RelatedTargetVersionMapping::parseJSON(
   *Mapping, *MaximumDeploymentVersion);

diff  --git a/clang/unittests/Basic/DarwinSDKInfoTest.cpp 
b/clang/unittests/Basic/DarwinSDKInfoTest.cpp
index f845e1536da8a..aa1feeb293c0e 100644
--- a/clang/unittests/Basic/DarwinSDKInfoTest.cpp
+++ b/clang/unittests/Basic/DarwinSDKInfoTest.cpp
@@ -13,7 +13,68 @@
 using namespace llvm;
 using namespace clang;
 
-TEST(DarwinSDKInfoTest, ParseAndTestMapping) {
+// Check the version mapping logic in DarwinSDKInfo.
+TEST(DarwinSDKInfo, VersionMapping) {
+  llvm::json::Object Obj({{"3.0", "1.0"}, {"3.1", "1.2"}});
+  Optional Mapping =
+  DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj,
+VersionTuple());
+  EXPECT_TRUE(Mapping.hasValue());
+  EXPECT_EQ(Mapping->getMinimumValue(), VersionTuple(1));
+
+  // Exact mapping.
+  EXPECT_EQ(Mapping->map(VersionTuple(3), VersionTuple(0, 1), None),
+VersionTuple(1));
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 0), VersionTuple(0, 1), None),
+VersionTuple(1));
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 0, 0), VersionTuple(0, 1), None),
+VersionTuple(1));
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 1), VersionTuple(0, 1), None),
+VersionTuple(1, 2));
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 1, 0), VersionTuple(0, 1), None),
+VersionTuple(1, 2));
+
+  // Missing mapping - fallback to major.
+  EXPECT_EQ(Mapping->map(VersionTuple(3, 0, 1), VersionTuple(0, 1), None),
+VersionTuple(1));
+
+  // Minimum
+  EXPECT_EQ(Mapping->map(VersionTuple(2), VersionTuple(0, 1), None),
+VersionTuple(0, 1));
+
+  // Maximum
+  EXPECT_EQ(
+  Mapping->map(VersionTuple(4), VersionTuple(0, 1), VersionTuple(100)),
+  VersionTuple(100));
+}
+
+// Check the version mapping logic in DarwinSDKInfo.
+TEST(DarwinSDKInfo, VersionMappingMissingKey) {
+  llvm::json::Object Obj({{"3.0", "1.0"}, {"5.0", "1.2"}});
+  Optional Mapping =
+  DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj,
+VersionTuple());
+  EXPECT_TRUE(Mapping.hasValue());
+  EXPECT_EQ(
+  Mapping->map(VersionTuple(4), VersionTuple(0, 1), VersionTuple(100)),
+  None);
+}
+
+TEST(DarwinSDKInfo, VersionMappingParseEmpty) {
+  llvm::json::Object Obj({});
+  EXPECT_FALSE(
+  DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, 
VersionTuple())
+  .hasValue());
+}
+
+TEST(DarwinSDKInfo, VersionMappingParseError) {
+  llvm::json::Object Obj({{"test", "1.2"}});
+  EXPECT_FALSE(
+  DarwinSDKInfo::RelatedTargetVersionMapping::parseJSON(Obj, 

[clang] 290cddc - Allow __attribute__((swift_attr)) in attribute push pragmas

2021-11-19 Thread Alex Lorenz via cfe-commits

Author: Becca Royal-Gordon
Date: 2021-11-19T13:00:26-08:00
New Revision: 290cddcd139d668251821f11426f37481faf6d7f

URL: 
https://github.com/llvm/llvm-project/commit/290cddcd139d668251821f11426f37481faf6d7f
DIFF: 
https://github.com/llvm/llvm-project/commit/290cddcd139d668251821f11426f37481faf6d7f.diff

LOG: Allow __attribute__((swift_attr)) in attribute push pragmas

This change allows SwiftAttr to be used with #pragma clang attribute push
to add Swift attributes to large regions of header files.
We plan to use this to annotate headers with concurrency information.

Patch by: Becca Royal-Gordon

Differential Revision: https://reviews.llvm.org/D112773

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/test/AST/attr-swift_attr.m
clang/test/Misc/pragma-attribute-supported-attributes-list.test

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index d8f0fcd56550c..39588d94cf09b 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2310,6 +2310,7 @@ def SwiftAttr : InheritableAttr {
   let Spellings = [GNU<"swift_attr">];
   let Args = [StringArgument<"Attribute">];
   let Documentation = [SwiftAttrDocs];
+  let PragmaAttributeSupport = 1;
 }
 
 def SwiftBridge : InheritableAttr {

diff  --git a/clang/test/AST/attr-swift_attr.m 
b/clang/test/AST/attr-swift_attr.m
index 3cd51b81e349f..70e325723b213 100644
--- a/clang/test/AST/attr-swift_attr.m
+++ b/clang/test/AST/attr-swift_attr.m
@@ -4,5 +4,13 @@
 @interface View
 @end
 
-// CHECK: InterfaceDecl {{.*}} View
+// CHECK-LABEL: InterfaceDecl {{.*}} View
 // CHECK-NEXT: SwiftAttrAttr {{.*}} "@actor"
+
+#pragma clang attribute push(__attribute__((swift_attr("@sendable"))), 
apply_to=objc_interface)
+@interface Contact
+@end
+#pragma clang attribute pop
+
+// CHECK-LABEL: InterfaceDecl {{.*}} Contact
+// CHECK-NEXT: SwiftAttrAttr {{.*}} "@sendable"

diff  --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test 
b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
index 199934b2791da..b565f7d00314b 100644
--- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -163,6 +163,7 @@
 // CHECK-NEXT: SwiftAsyncContext (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: SwiftAsyncError (SubjectMatchRule_function, 
SubjectMatchRule_objc_method)
 // CHECK-NEXT: SwiftAsyncName (SubjectMatchRule_objc_method, 
SubjectMatchRule_function)
+// CHECK-NEXT: SwiftAttr ()
 // CHECK-NEXT: SwiftBridgedTypedef (SubjectMatchRule_type_alias)
 // CHECK-NEXT: SwiftContext (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: SwiftError (SubjectMatchRule_function, 
SubjectMatchRule_objc_method)



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a00944e - [clang] 'unused-but-set-variable' warning should not apply to __block objective-c pointers

2021-11-05 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-11-05T07:48:07-07:00
New Revision: a00944ebeab1b0adbce606cde4d2410fcbb3f440

URL: 
https://github.com/llvm/llvm-project/commit/a00944ebeab1b0adbce606cde4d2410fcbb3f440
DIFF: 
https://github.com/llvm/llvm-project/commit/a00944ebeab1b0adbce606cde4d2410fcbb3f440.diff

LOG: [clang] 'unused-but-set-variable' warning should not apply to __block 
objective-c pointers

The __block Objective-C pointers can be set but not used due to a commonly used 
lifetime extension pattern in Objective-C.

Differential Revision: https://reviews.llvm.org/D112850

Added: 
clang/test/SemaObjC/block-capture-unused-variable.m

Modified: 
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index f4c0893cfcec2..d61570ee6a104 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -1944,6 +1944,12 @@ void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
 }
   }
 
+  // Don't warn about __block Objective-C pointer variables, as they might
+  // be assigned in the block but not used elsewhere for the purpose of 
lifetime
+  // extension.
+  if (VD->hasAttr() && Ty->isObjCObjectPointerType())
+return;
+
   auto iter = RefsMinusAssignments.find(VD);
   if (iter == RefsMinusAssignments.end())
 return;

diff  --git a/clang/test/SemaObjC/block-capture-unused-variable.m 
b/clang/test/SemaObjC/block-capture-unused-variable.m
new file mode 100644
index 0..1d40d9fb106b0
--- /dev/null
+++ b/clang/test/SemaObjC/block-capture-unused-variable.m
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macos11 -fsyntax-only -fobjc-arc 
-fblocks -verify -Wunused-but-set-variable -Wno-objc-root-class %s
+
+typedef struct dispatch_queue_s *dispatch_queue_t;
+
+typedef void (^dispatch_block_t)(void);
+
+void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
+
+extern __attribute__((visibility("default"))) struct dispatch_queue_s 
_dispatch_main_q;
+
+id getFoo();
+
+@protocol P
+
+@end
+
+@interface I
+
+@end
+
+void test() {
+  // no diagnostics
+  __block id x = getFoo();
+  __block id y = x;
+  __block I *z = (I *)x;
+  // diagnose non-block variables
+  id x2 = getFoo(); // expected-warning {{variable 'x2' set but not used}}
+  dispatch_async(&_dispatch_main_q, ^{
+x = ((void *)0);
+y = x;
+z = ((void *)0);
+  });
+  x2 = getFoo();
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a43d1aa - [clang] Make 'align-mismatch' warning work without an associated function declaration

2021-10-29 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-10-29T13:39:16-07:00
New Revision: a43d1aa8525649a64b1f0ed5a5c25718c28920c1

URL: 
https://github.com/llvm/llvm-project/commit/a43d1aa8525649a64b1f0ed5a5c25718c28920c1
DIFF: 
https://github.com/llvm/llvm-project/commit/a43d1aa8525649a64b1f0ed5a5c25718c28920c1.diff

LOG: [clang] Make 'align-mismatch' warning work without an associated function 
declaration

This change fixes a crash where a NULL fd was used to emit a diagnostic.
Instead of crashing, just avoid printing the declaration name when there's no
associated function declaration.

Differential Revision: https://reviews.llvm.org/D109402

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/typedef_alignment_mismatch_warning.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 7f7410a20084b..d37c8e9266e9b 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6792,7 +6792,7 @@ def warn_taking_address_of_packed_member : Warning<
   "taking address of packed member %0 of class or structure %q1 may result in 
an unaligned pointer value">,
   InGroup>;
 def warn_param_mismatched_alignment : Warning<
-  "passing %0-byte aligned argument to %1-byte aligned parameter %2 of %3 may 
result in an unaligned pointer access">,
+  "passing %0-byte aligned argument to %1-byte aligned parameter %2%select{| 
of %4}3 may result in an unaligned pointer access">,
   InGroup>;
 
 def err_objc_object_assignment : Error<

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 147f50aeed97f..bf458f914c111 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4887,7 +4887,7 @@ void Sema::CheckArgAlignment(SourceLocation Loc, 
NamedDecl *FDecl,
   if (ArgAlign < ParamAlign)
 Diag(Loc, diag::warn_param_mismatched_alignment)
 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
-<< ParamName << FDecl;
+<< ParamName << (FDecl != nullptr) << FDecl;
 }
 
 /// Handles the checks for format strings, non-POD arguments to vararg

diff  --git a/clang/test/CodeGen/typedef_alignment_mismatch_warning.cpp 
b/clang/test/CodeGen/typedef_alignment_mismatch_warning.cpp
index 9bc1d19843f34..1e6888de60e6b 100644
--- a/clang/test/CodeGen/typedef_alignment_mismatch_warning.cpp
+++ b/clang/test/CodeGen/typedef_alignment_mismatch_warning.cpp
@@ -282,3 +282,7 @@ void test10() {
   auto *UA4ptr = new UsingAligned4(11);
   new (UA4ptr) UsingAligned4(12);
 }
+
+void testFunctionPointerArray(void (*fptr[10])(Aligned8Int *), Aligned2Int* 
src) {
+  fptr[0](src); // expected-warning {{passing 2-byte aligned argument to 
8-byte aligned parameter 1 may result in an unaligned pointer access}}
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 3d0d7d8 - [clang][driver][darwin] support -target with Mac Catalyst triple without OS version

2021-10-28 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-10-28T18:46:10-07:00
New Revision: 3d0d7d8c5b669332f55c0af654b10f510bde1932

URL: 
https://github.com/llvm/llvm-project/commit/3d0d7d8c5b669332f55c0af654b10f510bde1932
DIFF: 
https://github.com/llvm/llvm-project/commit/3d0d7d8c5b669332f55c0af654b10f510bde1932.diff

LOG: [clang][driver][darwin] support -target with Mac Catalyst triple without 
OS version

Some users might omit the version and assume the compiler will target the 
initial
Mac Catalyst version.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/darwin-maccatalyst.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 5062c33bb0966..bf1425fe65efa 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1820,7 +1820,12 @@ std::string getOSVersion(llvm::Triple::OSType OS, const 
llvm::Triple ,
   << Triple.getOSName();
 break;
   case llvm::Triple::IOS:
-Triple.getiOSVersion(Major, Minor, Micro);
+if (Triple.isMacCatalystEnvironment() && !Triple.getOSMajorVersion()) {
+  Major = 13;
+  Minor = 1;
+  Micro = 0;
+} else
+  Triple.getiOSVersion(Major, Minor, Micro);
 break;
   case llvm::Triple::TvOS:
 Triple.getOSVersion(Major, Minor, Micro);

diff  --git a/clang/test/Driver/darwin-maccatalyst.c 
b/clang/test/Driver/darwin-maccatalyst.c
index 0e388ea3abe67..ac8a2cb9b9f57 100644
--- a/clang/test/Driver/darwin-maccatalyst.c
+++ b/clang/test/Driver/darwin-maccatalyst.c
@@ -1,9 +1,12 @@
 // RUN: %clang -target x86_64-apple-ios13.1-macabi -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION1 %s
+// RUN: %clang -target x86_64-apple-ios-macabi -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-VERSION1 %s
 // RUN: %clang -target x86_64-apple-ios13.0-macabi -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-ERROR %s
 // RUN: %clang -target x86_64-apple-ios12.0-macabi -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-ERROR %s
 
+// CHECK-VERSION1-NOT: error:
 // CHECK-VERSION1: "x86_64-apple-ios13.1.0-macabi"
 // CHECK-ERROR: error: invalid version number in '-target x86_64-apple-ios



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f575f37 - [clang][darwin] Add support for the -mtargetos= option to the driver

2021-08-02 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-08-02T12:45:40-07:00
New Revision: f575f371822f6a07483b21701165492224a846bb

URL: 
https://github.com/llvm/llvm-project/commit/f575f371822f6a07483b21701165492224a846bb
DIFF: 
https://github.com/llvm/llvm-project/commit/f575f371822f6a07483b21701165492224a846bb.diff

LOG: [clang][darwin] Add support for the -mtargetos= option to the driver

The new -mtargetos= option is a replacement for the existing, OS-specific 
options
like -miphoneos-version-min=. This allows us to introduce support for new 
darwin OSes
easier as they won't require the use of a new option. The older options will be
deprecated and the use of the new option will be encouraged instead.

Differential Revision: https://reviews.llvm.org/D106316

Added: 
clang/test/Driver/mtargetos-darwin.c

Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Darwin.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 3b4daa59f66b5..d27b83ecbe774 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -235,6 +235,7 @@ def warn_invalid_ios_deployment_target : Warning<
   DefaultError;
 def err_invalid_macos_32bit_deployment_target : Error<
   "32-bit targets are not supported when building for Mac Catalyst">;
+def err_drv_invalid_os_in_arg : Error<"invalid OS value '%0' in '%1'">;
 def err_drv_conflicting_deployment_targets : Error<
   "conflicting deployment targets, both '%0' and '%1' are present in 
environment">;
 def err_arc_unsupported_on_runtime : Error<

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 34442060e2771..8c562a6c06128 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3144,6 +3144,8 @@ def meabi : Separate<["-"], "meabi">, Group, 
Flags<[CC1Option]>,
   MarshallingInfoEnum, "Default">,
   NormalizedValuesScope<"llvm::EABI">,
   NormalizedValues<["Default", "EABI4", "EABI5", "GNU"]>;
+def mtargetos_EQ : Joined<["-"], "mtargetos=">, Group,
+  HelpText<"Set the deployment target to be the specified OS and OS version">;
 
 def mno_constant_cfstrings : Flag<["-"], "mno-constant-cfstrings">, 
Group;
 def mno_global_merge : Flag<["-"], "mno-global-merge">, Group, 
Flags<[CC1Option]>,

diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 261f522f6c493..f610bc2a781a5 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1379,6 +1379,8 @@ struct DarwinPlatform {
   enum SourceKind {
 /// The OS was specified using the -target argument.
 TargetArg,
+/// The OS was specified using the -mtargetos= argument.
+MTargetOSArg,
 /// The OS was specified using the -m-version-min argument.
 OSVersionArg,
 /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
@@ -1430,7 +1432,8 @@ struct DarwinPlatform {
   void addOSVersionMinArgument(DerivedArgList , const OptTable ) {
 if (Argument)
   return;
-assert(Kind != TargetArg && Kind != OSVersionArg && "Invalid kind");
+assert(Kind != TargetArg && Kind != MTargetOSArg && Kind != OSVersionArg &&
+   "Invalid kind");
 options::ID Opt;
 switch (Platform) {
 case DarwinPlatformKind::MacOS:
@@ -1455,6 +1458,7 @@ struct DarwinPlatform {
   std::string getAsString(DerivedArgList , const OptTable ) {
 switch (Kind) {
 case TargetArg:
+case MTargetOSArg:
 case OSVersionArg:
 case InferredFromSDK:
 case InferredFromArch:
@@ -1466,40 +1470,54 @@ struct DarwinPlatform {
 llvm_unreachable("Unsupported Darwin Source Kind");
   }
 
-  static DarwinPlatform
-  createFromTarget(const llvm::Triple , StringRef OSVersion, Arg *A,
-   const Optional ) {
-DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
-  A);
-unsigned Major, Minor, Micro;
-TT.getOSVersion(Major, Minor, Micro);
-if (Major == 0)
-  Result.HasOSVersion = false;
-
-switch (TT.getEnvironment()) {
+  void setEnvironment(llvm::Triple::EnvironmentType EnvType,
+  const VersionTuple ,
+  const Optional ) {
+switch (EnvType) {
 case llvm::Triple::Simulator:
-  Result.Environment = DarwinEnvironmentKind::Simulator;
+  Environment = DarwinEnvironmentKind::Simulator;
   break;
 case llvm::Triple::MacABI: {
+  Environment = DarwinEnvironmentKind::MacCatalyst;
   // The minimum native macOS target for MacCatalyst is macOS 10.15.
-  auto NativeTargetVersion = VersionTuple(10, 15);
-  if (Result.HasOSVersion && SDKInfo) {
+  NativeTargetVersion = 

[clang] 40d2d0c - [clang][test] Add -fuse-ld= to test case added in 2542c1a5a130 to resolve test failure with CLANG_DEFAULT_LINKER=lld

2021-07-22 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-07-22T11:12:38-07:00
New Revision: 40d2d0c41298f1d8a178216e2534b29e3128cf37

URL: 
https://github.com/llvm/llvm-project/commit/40d2d0c41298f1d8a178216e2534b29e3128cf37
DIFF: 
https://github.com/llvm/llvm-project/commit/40d2d0c41298f1d8a178216e2534b29e3128cf37.diff

LOG: [clang][test] Add -fuse-ld= to test case added in 2542c1a5a130 to resolve 
test failure with CLANG_DEFAULT_LINKER=lld

Added: 


Modified: 
clang/test/Driver/darwin-ld.c

Removed: 




diff  --git a/clang/test/Driver/darwin-ld.c b/clang/test/Driver/darwin-ld.c
index bd874d24e6c7..7441cc186df9 100644
--- a/clang/test/Driver/darwin-ld.c
+++ b/clang/test/Driver/darwin-ld.c
@@ -140,7 +140,7 @@
 // LINK_VERSION_MIN: {{ld(.exe)?"}}
 // LINK_VERSION_MIN: "-macosx_version_min" "10.7.0"
 
-// RUN: %clang -target x86_64-apple-ios13.1-macabi -mlinker-version=400 -### 
%t.o 2>> %t.log
+// RUN: %clang -target x86_64-apple-ios13.1-macabi -fuse-ld= 
-mlinker-version=400 -### %t.o 2>> %t.log
 // RUN: FileCheck -check-prefix=LINK_VERSION_MIN_MACABI %s < %t.log
 // LINK_VERSION_MIN_MACABI: {{ld(.exe)?"}}
 // LINK_VERSION_MIN_MACABI: "-maccatalyst_version_min" "13.1.0"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2542c1a - [clang][driver][darwin] Add driver support for Mac Catalyst

2021-07-22 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-07-22T10:20:19-07:00
New Revision: 2542c1a5a1306398d73c3c0c5d71cacf7c690093

URL: 
https://github.com/llvm/llvm-project/commit/2542c1a5a1306398d73c3c0c5d71cacf7c690093
DIFF: 
https://github.com/llvm/llvm-project/commit/2542c1a5a1306398d73c3c0c5d71cacf7c690093.diff

LOG: [clang][driver][darwin] Add driver support for Mac Catalyst

This commit adds driver support for the Mac Catalyst target,
as supported by the Apple clang compile

Differential Revision: https://reviews.llvm.org/D105960

Added: 
clang/test/Driver/Inputs/MacOSX10.15.versioned.sdk/SDKSettings.json
clang/test/Driver/darwin-ld-platform-version-maccatalyst.c
clang/test/Driver/darwin-mac-catalyst-32bit-not-supported.c
clang/test/Driver/darwin-maccatalyst.c
clang/test/Driver/darwin-objc-runtime-maccatalyst.m
clang/test/Driver/darwin-sdk-version-maccatalyst.c

Modified: 
clang/include/clang/Basic/DarwinSDKInfo.h
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Basic/DarwinSDKInfo.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h
clang/test/Driver/darwin-ld.c
clang/test/Driver/darwin-objc-defaults.m
clang/test/Driver/darwin-sanitizer-ld.c

Removed: 




diff  --git a/clang/include/clang/Basic/DarwinSDKInfo.h 
b/clang/include/clang/Basic/DarwinSDKInfo.h
index f6892269bb609..918dc7c8becc6 100644
--- a/clang/include/clang/Basic/DarwinSDKInfo.h
+++ b/clang/include/clang/Basic/DarwinSDKInfo.h
@@ -50,6 +50,13 @@ class DarwinSDKInfo {
llvm::Triple::IOS, llvm::Triple::MacABI);
 }
 
+/// Returns the os-environment mapping pair that's used to represent the
+/// Mac Catalyst -> macOS version mapping.
+static inline constexpr OSEnvPair macCatalystToMacOSPair() {
+  return OSEnvPair(llvm::Triple::IOS, llvm::Triple::MacABI,
+   llvm::Triple::MacOSX, llvm::Triple::UnknownEnvironment);
+}
+
   private:
 StorageType Value;
 

diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index c7da9713b1e4e..fc3704303a956 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -231,6 +231,8 @@ def warn_invalid_ios_deployment_target : Warning<
   "invalid iOS deployment version '%0', iOS 10 is the maximum deployment "
   "target for 32-bit targets">, InGroup,
   DefaultError;
+def err_invalid_macos_32bit_deployment_target : Error<
+  "32-bit targets are not supported when building for Mac Catalyst">;
 def err_drv_conflicting_deployment_targets : Error<
   "conflicting deployment targets, both '%0' and '%1' are present in 
environment">;
 def err_arc_unsupported_on_runtime : Error<

diff  --git a/clang/lib/Basic/DarwinSDKInfo.cpp 
b/clang/lib/Basic/DarwinSDKInfo.cpp
index fe3e8edbcd5cb..fe35f77782c92 100644
--- a/clang/lib/Basic/DarwinSDKInfo.cpp
+++ b/clang/lib/Basic/DarwinSDKInfo.cpp
@@ -92,6 +92,14 @@ DarwinSDKInfo::parseDarwinSDKSettingsJSON(const 
llvm::json::Object *Obj) {
   VersionMappings[OSEnvPair::macOStoMacCatalystPair().Value] =
   std::move(VersionMap);
 }
+if (const auto *Mapping = VM->getObject("iOSMac_macOS")) {
+  auto VersionMap = RelatedTargetVersionMapping::parseJSON(
+  *Mapping, *MaximumDeploymentVersion);
+  if (!VersionMap)
+return None;
+  VersionMappings[OSEnvPair::macCatalystToMacOSPair().Value] =
+  std::move(VersionMap);
+}
   }
 
   return DarwinSDKInfo(std::move(*Version),

diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index fc1f10111941b..4de5e81d2c0c0 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -34,6 +34,10 @@ using namespace clang::driver::toolchains;
 using namespace clang;
 using namespace llvm::opt;
 
+static const VersionTuple minimumMacCatalystDeploymentTarget() {
+  return VersionTuple(13, 1);
+}
+
 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
   // archs which Darwin doesn't use.
@@ -820,9 +824,9 @@ bool MachO::HasNativeLLVMSupport() const { return true; }
 
 ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
   // Default to use libc++ on OS X 10.9+ and iOS 7+.
-  if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
-   (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
-   isTargetWatchOSBased())
+  if ((isTargetMacOSBased() && !isMacosxVersionLT(10, 9)) ||
+  (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
+  isTargetWatchOSBased())
 return ToolChain::CST_Libcxx;
 
   return ToolChain::CST_Libstdcxx;
@@ -846,7 +850,7 @@ bool Darwin::hasBlocksRuntime() const {
   else if (isTargetIOSBased())
 return 

[clang] 9643d11 - [clang][sema] NFC, include DarwinSDKInfo header instead of using the forward reference

2021-07-21 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-07-21T12:46:52-07:00
New Revision: 9643d11e1d7f918c0e5184c9488935720d591c90

URL: 
https://github.com/llvm/llvm-project/commit/9643d11e1d7f918c0e5184c9488935720d591c90
DIFF: 
https://github.com/llvm/llvm-project/commit/9643d11e1d7f918c0e5184c9488935720d591c90.diff

LOG: [clang][sema] NFC, include DarwinSDKInfo header instead of using the 
forward reference

This fixes a build issue with an older libc++ on some bots: 
clang-cmake-x86_64-avx2-linux and clang-ppc64be-linux

Added: 


Modified: 
clang/include/clang/Sema/Sema.h

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index c200b9b24681..013722cfbe1e 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -37,6 +37,7 @@
 #include "clang/AST/TypeOrdering.h"
 #include "clang/Basic/BitmaskEnum.h"
 #include "clang/Basic/Builtins.h"
+#include "clang/Basic/DarwinSDKInfo.h"
 #include "clang/Basic/ExpressionTraits.h"
 #include "clang/Basic/Module.h"
 #include "clang/Basic/OpenCLOptions.h"
@@ -115,7 +116,6 @@ namespace clang {
   class CodeCompletionTUInfo;
   class CodeCompletionResult;
   class CoroutineBodyStmt;
-  class DarwinSDKInfo;
   class Decl;
   class DeclAccessPair;
   class DeclContext;



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] eb26ba9 - [clang][darwin] add support for remapping macOS availability to Mac Catalyst availability

2021-07-21 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-07-21T11:32:25-07:00
New Revision: eb26ba9da8aeab8ecc1209034912f9f12a945128

URL: 
https://github.com/llvm/llvm-project/commit/eb26ba9da8aeab8ecc1209034912f9f12a945128
DIFF: 
https://github.com/llvm/llvm-project/commit/eb26ba9da8aeab8ecc1209034912f9f12a945128.diff

LOG: [clang][darwin] add support for remapping macOS availability to Mac 
Catalyst availability

This commit adds supports for clang to remap macOS availability attributes that 
have introduced,
deprecated or obsoleted versions to appropriate Mac Catalyst availability 
attributes. This
mapping is done using the version mapping provided in the macOS SDK, in the 
SDKSettings.json file.
The mappings in the SDKSettings json file will also be used in the clang driver 
for the driver
Mac Catalyst patch, and they could also be used in the future for other 
platforms as well.

Differential Revision: https://reviews.llvm.org/D105257

Added: 
clang/test/Sema/Inputs/MacOSX11.0.sdk/SDKSettings.json
clang/test/Sema/attr-availability-iosmac-infer-from-macos-no-sdk-settings.c
clang/test/Sema/attr-availability-iosmac-infer-from-macos.c

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/Basic/DarwinSDKInfo.cpp
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/Driver/Inputs/MacOSX10.14.sdk/SDKSettings.json
clang/test/Driver/Inputs/WatchOS6.0.sdk/SDKSettings.json
clang/test/Driver/Inputs/iPhoneOS13.0.sdk/SDKSettings.json
clang/test/Sema/attr-availability-maccatalyst.c

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 792313fed2a9f..108f1796415c8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3549,6 +3549,10 @@ def warn_at_available_unchecked_use : Warning<
   "use if (%select{@available|__builtin_available}0) instead">,
   InGroup>;
 
+def warn_missing_sdksettings_for_availability_checking : Warning<
+  "%0 availability is ignored without a valid 'SDKSettings.json' in the SDK">,
+  InGroup>;
+
 // Thread Safety Attributes
 def warn_thread_attribute_ignored : Warning<
   "ignoring %0 attribute because its argument is invalid">,

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 4ade04992a5f4..c200b9b246811 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -115,6 +115,7 @@ namespace clang {
   class CodeCompletionTUInfo;
   class CodeCompletionResult;
   class CoroutineBodyStmt;
+  class DarwinSDKInfo;
   class Decl;
   class DeclAccessPair;
   class DeclContext;
@@ -1525,6 +1526,8 @@ class Sema final {
   /// assignment.
   llvm::DenseMap RefsMinusAssignments;
 
+  Optional> CachedDarwinSDKInfo;
+
 public:
   Sema(Preprocessor , ASTContext , ASTConsumer ,
TranslationUnitKind TUKind = TU_Complete,
@@ -1553,6 +1556,8 @@ class Sema final {
   ASTConsumer () const { return Consumer; }
   ASTMutationListener *getASTMutationListener() const;
   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
+  DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
+ StringRef Platform);
 
   ///Registers an external source. If an external source already exists,
   /// creates a multiplex external source and appends to it.

diff  --git a/clang/lib/Basic/DarwinSDKInfo.cpp 
b/clang/lib/Basic/DarwinSDKInfo.cpp
index 6959b84e5c62a..fe3e8edbcd5cb 100644
--- a/clang/lib/Basic/DarwinSDKInfo.cpp
+++ b/clang/lib/Basic/DarwinSDKInfo.cpp
@@ -115,13 +115,8 @@ clang::parseDarwinSDKInfo(llvm::vfs::FileSystem , 
StringRef SDKRootPath) {
 return Result.takeError();
 
   if (const auto *Obj = Result->getAsObject()) {
-// FIXME: Switch to use parseDarwinSDKSettingsJSON.
-auto VersionString = Obj->getString("Version");
-if (VersionString) {
-  VersionTuple Version;
-  if (!Version.tryParse(*VersionString))
-return DarwinSDKInfo(Version, Version);
-}
+if (auto SDKInfo = DarwinSDKInfo::parseDarwinSDKSettingsJSON(Obj))
+  return std::move(SDKInfo);
   }
   return llvm::make_error("invalid SDKSettings.json",
  llvm::inconvertibleErrorCode());

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 704b631f94003..fbbb347f57da3 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -22,12 +22,14 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/PrettyDeclStackTrace.h"
 #include "clang/AST/StmtCXX.h"
+#include "clang/Basic/DarwinSDKInfo.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/PartialDiagnostic.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/Stack.h"
 #include 

[clang] 5f55761 - [clang] Fix the capitalization of the DarwinSDKInfoTest unittest filename to avoid case-sensitive FS build errors

2021-07-20 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-07-20T14:53:08-07:00
New Revision: 5f557616c6b13adbe244b3583459a926628c3466

URL: 
https://github.com/llvm/llvm-project/commit/5f557616c6b13adbe244b3583459a926628c3466
DIFF: 
https://github.com/llvm/llvm-project/commit/5f557616c6b13adbe244b3583459a926628c3466.diff

LOG: [clang] Fix the capitalization of the DarwinSDKInfoTest unittest filename 
to avoid case-sensitive FS build errors

Added: 
clang/unittests/Basic/DarwinSDKInfoTest.cpp

Modified: 


Removed: 
clang/unittests/Basic/DarwinSDKinfoTest.cpp



diff  --git a/clang/unittests/Basic/DarwinSDKinfoTest.cpp 
b/clang/unittests/Basic/DarwinSDKInfoTest.cpp
similarity index 100%
rename from clang/unittests/Basic/DarwinSDKinfoTest.cpp
rename to clang/unittests/Basic/DarwinSDKInfoTest.cpp



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 808bbc2 - [clang][darwin] Add support for macOS -> Mac Catalyst

2021-07-20 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-07-20T14:25:33-07:00
New Revision: 808bbc2c47028ff5c2cc0bf7a1d5140adec9202a

URL: 
https://github.com/llvm/llvm-project/commit/808bbc2c47028ff5c2cc0bf7a1d5140adec9202a
DIFF: 
https://github.com/llvm/llvm-project/commit/808bbc2c47028ff5c2cc0bf7a1d5140adec9202a.diff

LOG: [clang][darwin] Add support for macOS -> Mac Catalyst
version remapping to the Darwin SDK Info

Differential Revision: https://reviews.llvm.org/D105958

Added: 
clang/unittests/Basic/DarwinSDKinfoTest.cpp

Modified: 
clang/include/clang/Basic/DarwinSDKInfo.h
clang/lib/Basic/DarwinSDKInfo.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/unittests/Basic/CMakeLists.txt
llvm/include/llvm/Support/VersionTuple.h

Removed: 




diff  --git a/clang/include/clang/Basic/DarwinSDKInfo.h 
b/clang/include/clang/Basic/DarwinSDKInfo.h
index f4428f29315b3..f6892269bb609 100644
--- a/clang/include/clang/Basic/DarwinSDKInfo.h
+++ b/clang/include/clang/Basic/DarwinSDKInfo.h
@@ -10,21 +10,132 @@
 #define LLVM_CLANG_BASIC_DARWIN_SDK_INFO_H
 
 #include "clang/Basic/LLVM.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/Triple.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/VersionTuple.h"
 #include "llvm/Support/VirtualFileSystem.h"
 
+namespace llvm {
+namespace json {
+class Object;
+} // end namespace json
+} // end namespace llvm
+
 namespace clang {
 
 /// The information about the darwin SDK that was used during this compilation.
 class DarwinSDKInfo {
 public:
-  DarwinSDKInfo(llvm::VersionTuple Version) : Version(Version) {}
+  /// A value that describes two os-environment pairs that can be used as a key
+  /// to the version map in the SDK.
+  struct OSEnvPair {
+  public:
+using StorageType = uint64_t;
+
+constexpr OSEnvPair(llvm::Triple::OSType FromOS,
+llvm::Triple::EnvironmentType FromEnv,
+llvm::Triple::OSType ToOS,
+llvm::Triple::EnvironmentType ToEnv)
+: Value(((StorageType(FromOS) * StorageType(llvm::Triple::LastOSType) +
+  StorageType(FromEnv))
+ << 32ull) |
+(StorageType(ToOS) * StorageType(llvm::Triple::LastOSType) +
+ StorageType(ToEnv))) {}
+
+/// Returns the os-environment mapping pair that's used to represent the
+/// macOS -> Mac Catalyst version mapping.
+static inline constexpr OSEnvPair macOStoMacCatalystPair() {
+  return OSEnvPair(llvm::Triple::MacOSX, llvm::Triple::UnknownEnvironment,
+   llvm::Triple::IOS, llvm::Triple::MacABI);
+}
+
+  private:
+StorageType Value;
+
+friend class DarwinSDKInfo;
+  };
+
+  /// Represents a version mapping that maps from a version of one target to a
+  /// version of a related target.
+  ///
+  /// e.g. "macOS_iOSMac":{"10.15":"13.1"} is an example of a macOS -> Mac
+  /// Catalyst version map.
+  class RelatedTargetVersionMapping {
+  public:
+RelatedTargetVersionMapping(
+VersionTuple MinimumKeyVersion, VersionTuple MaximumKeyVersion,
+VersionTuple MinimumValue, VersionTuple MaximumValue,
+llvm::DenseMap Mapping)
+: MinimumKeyVersion(MinimumKeyVersion),
+  MaximumKeyVersion(MaximumKeyVersion), MinimumValue(MinimumValue),
+  MaximumValue(MaximumValue), Mapping(Mapping) {
+  assert(!this->Mapping.empty() && "unexpected empty mapping");
+}
+
+/// Returns the value with the lowest version in the mapping.
+const VersionTuple () const { return MinimumValue; }
+
+/// Returns the mapped key, or the appropriate Minimum / MaximumValue if
+/// they key is outside of the mapping bounds. If they key isn't mapped, 
but
+/// within the minimum and maximum bounds, None is returned.
+Optional map(const VersionTuple ,
+   const VersionTuple ,
+   Optional MaximumValue) const;
+
+static Optional
+parseJSON(const llvm::json::Object ,
+  VersionTuple MaximumDeploymentTarget);
+
+  private:
+VersionTuple MinimumKeyVersion;
+VersionTuple MaximumKeyVersion;
+VersionTuple MinimumValue;
+VersionTuple MaximumValue;
+llvm::DenseMap Mapping;
+  };
+
+  DarwinSDKInfo(VersionTuple Version, VersionTuple MaximumDeploymentTarget,
+llvm::DenseMap>
+VersionMappings =
+llvm::DenseMap>())
+  : Version(Version), MaximumDeploymentTarget(MaximumDeploymentTarget),
+VersionMappings(std::move(VersionMappings)) {}
 
   const llvm::VersionTuple () const { return Version; }
 
+  // Returns the optional, target-specific version mapping that maps from one
+  // target to another target.
+  //
+  // This mapping is constructed from an appropriate mapping in the 
SDKSettings,
+  // for instance, when building for Mac Catalyst, the mapping would 

[clang] 05a6d74 - [clang] NFC, move DarwinSDKInfo to lib/Basic

2021-07-20 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-07-20T13:22:48-07:00
New Revision: 05a6d74c4845221907e25971937242b72489ef55

URL: 
https://github.com/llvm/llvm-project/commit/05a6d74c4845221907e25971937242b72489ef55
DIFF: 
https://github.com/llvm/llvm-project/commit/05a6d74c4845221907e25971937242b72489ef55.diff

LOG: [clang] NFC, move DarwinSDKInfo to lib/Basic

This is a preparation commit for https://reviews.llvm.org/D105958

Added: 
clang/include/clang/Basic/DarwinSDKInfo.h
clang/lib/Basic/DarwinSDKInfo.cpp

Modified: 
clang/lib/Basic/CMakeLists.txt
clang/lib/Driver/CMakeLists.txt
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h

Removed: 
clang/include/clang/Driver/DarwinSDKInfo.h
clang/lib/Driver/DarwinSDKInfo.cpp



diff  --git a/clang/include/clang/Driver/DarwinSDKInfo.h 
b/clang/include/clang/Basic/DarwinSDKInfo.h
similarity index 87%
rename from clang/include/clang/Driver/DarwinSDKInfo.h
rename to clang/include/clang/Basic/DarwinSDKInfo.h
index f7075a8d3b7f9..f4428f29315b3 100644
--- a/clang/include/clang/Driver/DarwinSDKInfo.h
+++ b/clang/include/clang/Basic/DarwinSDKInfo.h
@@ -6,8 +6,8 @@
 //
 
//===--===//
 
-#ifndef LLVM_CLANG_DRIVER_DARWIN_SDK_INFO_H
-#define LLVM_CLANG_DRIVER_DARWIN_SDK_INFO_H
+#ifndef LLVM_CLANG_BASIC_DARWIN_SDK_INFO_H
+#define LLVM_CLANG_BASIC_DARWIN_SDK_INFO_H
 
 #include "clang/Basic/LLVM.h"
 #include "llvm/Support/Error.h"
@@ -15,7 +15,6 @@
 #include "llvm/Support/VirtualFileSystem.h"
 
 namespace clang {
-namespace driver {
 
 /// The information about the darwin SDK that was used during this compilation.
 class DarwinSDKInfo {
@@ -35,7 +34,6 @@ class DarwinSDKInfo {
 Expected> parseDarwinSDKInfo(llvm::vfs::FileSystem 
,
  StringRef SDKRootPath);
 
-} // end namespace driver
 } // end namespace clang
 
-#endif // LLVM_CLANG_DRIVER_DARWIN_SDK_INFO_H
+#endif // LLVM_CLANG_BASIC_DARWIN_SDK_INFO_H

diff  --git a/clang/lib/Basic/CMakeLists.txt b/clang/lib/Basic/CMakeLists.txt
index cbf99b2a848f2..c550e8cae03f3 100644
--- a/clang/lib/Basic/CMakeLists.txt
+++ b/clang/lib/Basic/CMakeLists.txt
@@ -42,6 +42,7 @@ add_clang_library(clangBasic
   CharInfo.cpp
   CodeGenOptions.cpp
   Cuda.cpp
+  DarwinSDKInfo.cpp
   Diagnostic.cpp
   DiagnosticIDs.cpp
   DiagnosticOptions.cpp

diff  --git a/clang/lib/Driver/DarwinSDKInfo.cpp 
b/clang/lib/Basic/DarwinSDKInfo.cpp
similarity index 90%
rename from clang/lib/Driver/DarwinSDKInfo.cpp
rename to clang/lib/Basic/DarwinSDKInfo.cpp
index 761c6717266bf..e2ea580565b98 100644
--- a/clang/lib/Driver/DarwinSDKInfo.cpp
+++ b/clang/lib/Basic/DarwinSDKInfo.cpp
@@ -6,17 +6,16 @@
 //
 
//===--===//
 
-#include "clang/Driver/DarwinSDKInfo.h"
+#include "clang/Basic/DarwinSDKInfo.h"
 #include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/JSON.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 
-using namespace clang::driver;
 using namespace clang;
 
 Expected>
-driver::parseDarwinSDKInfo(llvm::vfs::FileSystem , StringRef SDKRootPath) {
+clang::parseDarwinSDKInfo(llvm::vfs::FileSystem , StringRef SDKRootPath) {
   llvm::SmallString<256> Filepath = SDKRootPath;
   llvm::sys::path::append(Filepath, "SDKSettings.json");
   llvm::ErrorOr> File =

diff  --git a/clang/lib/Driver/CMakeLists.txt b/clang/lib/Driver/CMakeLists.txt
index f59141f9e19fe..08be9f0115a19 100644
--- a/clang/lib/Driver/CMakeLists.txt
+++ b/clang/lib/Driver/CMakeLists.txt
@@ -13,7 +13,6 @@ endif()
 add_clang_library(clangDriver
   Action.cpp
   Compilation.cpp
-  DarwinSDKInfo.cpp
   Distro.cpp
   Driver.cpp
   DriverOptions.cpp

diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 8a0c4721eea0e..0f41c0ff2a80d 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1786,7 +1786,7 @@ Optional 
parseSDKSettings(llvm::vfs::FileSystem ,
   if (!A)
 return None;
   StringRef isysroot = A->getValue();
-  auto SDKInfoOrErr = driver::parseDarwinSDKInfo(VFS, isysroot);
+  auto SDKInfoOrErr = parseDarwinSDKInfo(VFS, isysroot);
   if (!SDKInfoOrErr) {
 llvm::consumeError(SDKInfoOrErr.takeError());
 TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);

diff  --git a/clang/lib/Driver/ToolChains/Darwin.h 
b/clang/lib/Driver/ToolChains/Darwin.h
index 25c63fed922a8..775336ee3158c 100644
--- a/clang/lib/Driver/ToolChains/Darwin.h
+++ b/clang/lib/Driver/ToolChains/Darwin.h
@@ -11,8 +11,8 @@
 
 #include "Cuda.h"
 #include "ROCm.h"
+#include "clang/Basic/DarwinSDKInfo.h"
 #include "clang/Basic/LangOptions.h"
-#include "clang/Driver/DarwinSDKInfo.h"
 #include "clang/Driver/Tool.h"
 #include "clang/Driver/ToolChain.h"
 #include "clang/Driver/XRayArgs.h"




[clang] a8262a3 - [clang][darwin] add support for Mac Catalyst availability

2021-07-20 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-07-20T12:51:57-07:00
New Revision: a8262a383bc627cef3de78e60bbbedb788157a50

URL: 
https://github.com/llvm/llvm-project/commit/a8262a383bc627cef3de78e60bbbedb788157a50
DIFF: 
https://github.com/llvm/llvm-project/commit/a8262a383bc627cef3de78e60bbbedb788157a50.diff

LOG: [clang][darwin] add support for Mac Catalyst availability

This commit adds support for Mac Catalyst availability attribute, as
supported by the Apple clang compiler. A follow-up commit will provide
additional support for inferring Mac Catalyst availability from macOS
availability using the mapping in the SDKSettings.json.

Differential Revision: https://reviews.llvm.org/D105052

Added: 
clang/test/CodeGenObjC/availability-check-maccatalyst.m
clang/test/FixIt/fixit-availability-maccatalyst.m
clang/test/Sema/attr-availability-maccatalyst.c
clang/test/SemaObjC/unguarded-availability-maccatalyst.m

Modified: 
clang/include/clang/Basic/Attr.td
clang/lib/Basic/Targets/OSTargets.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index e27efd404c218..12d09181a2ea8 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -856,6 +856,8 @@ def Availability : InheritableAttr {
  .Case("macos_app_extension", "macOS (App Extension)")
  .Case("tvos_app_extension", "tvOS (App Extension)")
  .Case("watchos_app_extension", "watchOS (App Extension)")
+ .Case("maccatalyst", "macCatalyst")
+ .Case("maccatalyst_app_extension", "macCatalyst (App Extension)")
  .Case("swift", "Swift")
  .Default(llvm::StringRef());
 }
@@ -869,6 +871,8 @@ static llvm::StringRef 
getPlatformNameSourceSpelling(llvm::StringRef Platform) {
  .Case("macos_app_extension", "macOSApplicationExtension")
  .Case("tvos_app_extension", "tvOSApplicationExtension")
  .Case("watchos_app_extension", "watchOSApplicationExtension")
+ .Case("maccatalyst", "macCatalyst")
+ .Case("maccatalyst_app_extension", 
"macCatalystApplicationExtension")
  .Case("zos", "z/OS")
  .Default(Platform);
 }
@@ -882,6 +886,8 @@ static llvm::StringRef 
canonicalizePlatformName(llvm::StringRef Platform) {
  .Case("macOSApplicationExtension", "macos_app_extension")
  .Case("tvOSApplicationExtension", "tvos_app_extension")
  .Case("watchOSApplicationExtension", "watchos_app_extension")
+ .Case("macCatalyst", "maccatalyst")
+ .Case("macCatalystApplicationExtension", 
"maccatalyst_app_extension")
  .Default(Platform);
 } }];
   let HasCustomParsing = 1;

diff  --git a/clang/lib/Basic/Targets/OSTargets.cpp 
b/clang/lib/Basic/Targets/OSTargets.cpp
index 15e475a31d644..7cd4a51901205 100644
--- a/clang/lib/Basic/Targets/OSTargets.cpp
+++ b/clang/lib/Basic/Targets/OSTargets.cpp
@@ -55,6 +55,8 @@ void getDarwinDefines(MacroBuilder , const 
LangOptions ,
   } else {
 Triple.getOSVersion(Maj, Min, Rev);
 PlatformName = llvm::Triple::getOSTypeName(Triple.getOS());
+if (PlatformName == "ios" && Triple.isMacCatalystEnvironment())
+  PlatformName = "maccatalyst";
   }
 
   // If -target arch-pc-win32-macho option specified, we're

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 9aac9d2156445..c61afa750bc14 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2556,6 +2556,36 @@ static void handleAvailabilityAttr(Sema , Decl *D, 
const ParsedAttr ) {
   if (NewAttr)
 D->addAttr(NewAttr);
   }
+  } else if (S.Context.getTargetInfo().getTriple().getOS() ==
+ llvm::Triple::IOS &&
+ S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) 
{
+// Transcribe "ios" to "maccatalyst" (and add a new attribute).
+IdentifierInfo *NewII = nullptr;
+auto MinMacCatalystVersion = [](const VersionTuple ) {
+  if (V.empty())
+return V;
+  if (V.getMajor() < 13 ||
+  (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
+return VersionTuple(13, 1); // The minimum Mac Catalyst version is 
13.1.
+  return V;
+};
+if (II->getName() == "ios")
+  NewII = ("maccatalyst");
+else if (II->getName() == "ios_app_extension")
+  NewII = ("maccatalyst_app_extension");
+// FIXME: Add support for transcribing macOS availability using mapping 
from
+// SDKSettings.json.
+if (NewII) {
+  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
+  ND, AL.getRange(), NewII, true /*Implicit*/,
+  MinMacCatalystVersion(Introduced.Version),
+  MinMacCatalystVersion(Deprecated.Version),
+  

[clang] c68f247 - [clang-scan-deps] ignore top-level module dependencies that aren't actually imported

2021-07-20 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-07-20T11:11:28-07:00
New Revision: c68f247275eed94a4f4b97ad53b4d599acfd181a

URL: 
https://github.com/llvm/llvm-project/commit/c68f247275eed94a4f4b97ad53b4d599acfd181a
DIFF: 
https://github.com/llvm/llvm-project/commit/c68f247275eed94a4f4b97ad53b4d599acfd181a.diff

LOG: [clang-scan-deps] ignore top-level module dependencies that aren't 
actually imported

Whenever -fmodule-name=top_level_module name is parsed, and clang actually 
tries to
import top_level_module, the headers are imported textually and the module 
isn't actually
built. However, the dependency scanner could still record it as a potential 
dependency
if the module was reimported and thus recorded by the preprocessor callbacks.
This change avoids collecting this kind of module as a dependency by verifying 
that we don't
collect top level modules without actual PCM files.

Differential Revision: https://reviews.llvm.org/D106100

Added: 
clang/test/ClangScanDeps/Inputs/header3.h
clang/test/ClangScanDeps/Inputs/module_fmodule_name_cdb.json
clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m

Modified: 
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/test/ClangScanDeps/Inputs/module.modulemap

Removed: 




diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index 690bd6d476e58..88cee63c98aa5 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -170,8 +170,15 @@ void ModuleDepCollectorPP::EndOfMainFile() {
   if (!Instance.getPreprocessorOpts().ImplicitPCHInclude.empty())
 MDC.FileDeps.push_back(Instance.getPreprocessorOpts().ImplicitPCHInclude);
 
-  for (const Module *M : DirectModularDeps)
+  for (const Module *M : DirectModularDeps) {
+// A top-level module might not be actually imported as a module when
+// -fmodule-name is used to compile a translation unit that imports this
+// module. In that case it can be skipped. The appropriate header
+// dependencies will still be reported as expected.
+if (!M->getASTFile())
+  continue;
 handleTopLevelModule(M);
+  }
 
   MDC.Consumer.handleDependencyOutputOpts(*MDC.Opts);
 

diff  --git a/clang/test/ClangScanDeps/Inputs/header3.h 
b/clang/test/ClangScanDeps/Inputs/header3.h
new file mode 100644
index 0..5bd7e64bcfe36
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/header3.h
@@ -0,0 +1,2 @@
+// import another header from the same module
+#include "header.h"

diff  --git a/clang/test/ClangScanDeps/Inputs/module.modulemap 
b/clang/test/ClangScanDeps/Inputs/module.modulemap
index 13171f29d69af..ae8534247c150 100644
--- a/clang/test/ClangScanDeps/Inputs/module.modulemap
+++ b/clang/test/ClangScanDeps/Inputs/module.modulemap
@@ -5,3 +5,8 @@ module header1 {
 module header2 {
 header "header2.h"
 }
+
+module header3 {
+  header "header.h"
+  header "header3.h"
+}

diff  --git a/clang/test/ClangScanDeps/Inputs/module_fmodule_name_cdb.json 
b/clang/test/ClangScanDeps/Inputs/module_fmodule_name_cdb.json
new file mode 100644
index 0..dec425171875a
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/module_fmodule_name_cdb.json
@@ -0,0 +1,7 @@
+[
+{
+  "directory": "DIR",
+  "command": "clang -E DIR/modules-fmodule-name-no-module-built.m -IInputs -D 
INCLUDE_HEADER2 -MD -MF DIR/modules_cdb.d -fmodules -fcxx-modules 
-fmodules-cache-path=DIR/module-cache -fimplicit-modules -fmodule-name=header3 
-fimplicit-module-maps",
+  "file": "DIR/modules-fmodule-name-no-module-built.m"
+}
+]

diff  --git a/clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m 
b/clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
new file mode 100644
index 0..e30e312b6a8da
--- /dev/null
+++ b/clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
@@ -0,0 +1,59 @@
+// RUN: rm -rf %t.dir
+// RUN: rm -rf %t.cdb
+// RUN: mkdir -p %t.dir
+// RUN: cp %s %t.dir/modules-fmodule-name-no-module-built.m
+// RUN: mkdir %t.dir/Inputs
+// RUN: cp %S/Inputs/header.h %t.dir/Inputs/header.h
+// RUN: cp %S/Inputs/header2.h %t.dir/Inputs/header2.h
+// RUN: cp %S/Inputs/header3.h %t.dir/Inputs/header3.h
+// RUN: cp %S/Inputs/module.modulemap %t.dir/Inputs/module.modulemap
+// RUN: sed -e "s|DIR|%/t.dir|g" %S/Inputs/module_fmodule_name_cdb.json > 
%t.cdb
+
+// RUN: echo %t.dir > %t.result
+// RUN: clang-scan-deps -compilation-database %t.cdb -j 1 -format 
experimental-full \
+// RUN:   -generate-modules-path-args -mode preprocess-minimized-sources >> 
%t.result
+// RUN: cat %t.result | sed 's:\?:/:g' | FileCheck --check-prefixes=CHECK 
%s
+
+#import "header3.h"
+#import "header.h"
+
+// CHECK: [[PREFIX:.*]]
+// CHECK-NEXT: {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   

[clang] 22dea69 - [clang][ObjC] allow the use of NSAttributedString * argument type with format attribute

2021-06-11 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-06-11T13:24:32-07:00
New Revision: 22dea6923155b18d172db64e5dab4b71afe19e6e

URL: 
https://github.com/llvm/llvm-project/commit/22dea6923155b18d172db64e5dab4b71afe19e6e
DIFF: 
https://github.com/llvm/llvm-project/commit/22dea6923155b18d172db64e5dab4b71afe19e6e.diff

LOG: [clang][ObjC] allow the use of NSAttributedString * argument type with 
format attribute

This is useful for APIs that want to accept an attributed NSString as their 
format string

rdar://79163229

Added: 


Modified: 
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/SemaObjC/format-strings-objc.m

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 2448636bdd52..17fe8c071345 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3471,7 +3471,7 @@ static void handleFormatAttr(Sema , Decl *D, const 
ParsedAttr ) {
   } else if (Kind == NSStringFormat) {
 // FIXME: do we need to check if the type is NSString*?  What are the
 // semantics?
-if (!isNSStringType(Ty, S.Context)) {
+if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) {
   S.Diag(AL.getLoc(), diag::err_format_attribute_not)
 << "an NSString" << IdxExpr->getSourceRange()
 << getFunctionOrMethodParamRange(D, ArgIdx);

diff  --git a/clang/test/SemaObjC/format-strings-objc.m 
b/clang/test/SemaObjC/format-strings-objc.m
index e5a1a824abba..d80424487c6f 100644
--- a/clang/test/SemaObjC/format-strings-objc.m
+++ b/clang/test/SemaObjC/format-strings-objc.m
@@ -34,6 +34,11 @@ @interface NSSimpleCString : NSString {} @end
 @interface NSConstantString : NSSimpleCString @end
 extern void *_NSConstantStringClassReference;
 
+@interface NSAttributedString : NSObject
++(instancetype)stringWithFormat:(NSAttributedString *)fmt, ...
+__attribute__((format(__NSString__, 1, 2)));
+@end
+
 typedef const struct __CFString * CFStringRef;
 extern void CFStringCreateWithFormat(CFStringRef format, ...) 
__attribute__((format(CFString, 1, 2)));
 #define CFSTR(cStr)  ((CFStringRef) __builtin___CFStringMakeConstantString ("" 
cStr ""))
@@ -317,6 +322,9 @@ - (NSString *)someRandomMethod:(NSString *)key
  value:(nullable NSString *)value
  table:(nullable NSString *)tableName
 __attribute__((format_arg(1)));
+
+- (NSAttributedString *)someMethod2:(NSString *)key
+__attribute__((format_arg(1)));
 @end
 
 void useLocalizedStringForKey(NSBundle *bndl) {
@@ -341,4 +349,9 @@ void useLocalizedStringForKey(NSBundle *bndl) {
   [bndl someRandomMethod:@"flerp"
value:0
table:0], 42]; // expected-warning{{data 
argument not used by format string}}
+
+  [NSAttributedString stringWithFormat:
+  [bndl someMethod2: @"test"], 5]; // expected-warning{{data 
argument not used by format string}}
+  [NSAttributedString stringWithFormat:
+  [bndl someMethod2: @"%f"], 42]; // expected-warning{{format 
specifies type 'double' but the argument has type 'int'}}
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 50be48b - [clang][ObjC] Allow different availability annotation on a method

2021-05-19 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-05-19T12:13:57-07:00
New Revision: 50be48b0f3c884a87ddf19c7c51abcab035c1efb

URL: 
https://github.com/llvm/llvm-project/commit/50be48b0f3c884a87ddf19c7c51abcab035c1efb
DIFF: 
https://github.com/llvm/llvm-project/commit/50be48b0f3c884a87ddf19c7c51abcab035c1efb.diff

LOG: [clang][ObjC] Allow different availability annotation on a method
when implementing an optional protocol requirement

When an Objective-C method implements an optional protocol requirement,
allow the method to use a newer introduced or older obsoleted
availability version than what's specified on the method in the protocol
itself. This allows SDK adopters to adopt an optional method from a
protocol later than when the method is introduced in the protocol. The users
that call an optional method on an object that conforms to this protocol
are supposed to check whether the object implements the method or not,
so a lack of appropriate `if (@available)` check for a new OS version
is not a cause of concern as there's already another runtime check that's 
required.

Differential Revision: https://reviews.llvm.org/D102459

Added: 
clang/test/SemaObjC/override-opt-prop-availability.m

Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/SemaObjC/attr-availability.m

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index b6143d1d31789..9c459a95a6916 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3255,6 +3255,9 @@ class Sema final {
 /// Merge availability attributes for an implementation of
 /// a protocol requirement.
 AMK_ProtocolImplementation,
+/// Merge availability attributes for an implementation of
+/// an optional protocol requirement.
+AMK_OptionalProtocolImplementation
   };
 
   /// Describes the kind of priority given to an availability attribute.

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index c4db147e7efde..90fae1d9c9286 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2608,7 +2608,8 @@ static bool mergeDeclAttribute(Sema , NamedDecl *D,
 NewAttr = nullptr;
   else if ((isa(Attr) || isa(Attr)) &&
(AMK == Sema::AMK_Override ||
-AMK == Sema::AMK_ProtocolImplementation))
+AMK == Sema::AMK_ProtocolImplementation ||
+AMK == Sema::AMK_OptionalProtocolImplementation))
 NewAttr = nullptr;
   else if (const auto *UA = dyn_cast(Attr))
 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
@@ -2956,6 +2957,7 @@ void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
   case AMK_Redeclaration:
   case AMK_Override:
   case AMK_ProtocolImplementation:
+  case AMK_OptionalProtocolImplementation:
 LocalAMK = AMK;
 break;
   }
@@ -3861,10 +3863,11 @@ void Sema::mergeObjCMethodDecls(ObjCMethodDecl 
*newMethod,
 ObjCMethodDecl *oldMethod) {
   // Merge the attributes, including deprecated/unavailable
   AvailabilityMergeKind MergeKind =
-isa(oldMethod->getDeclContext())
-  ? AMK_ProtocolImplementation
-  : isa(newMethod->getDeclContext()) ? AMK_Redeclaration
-   : AMK_Override;
+  isa(oldMethod->getDeclContext())
+  ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
+ : AMK_ProtocolImplementation)
+  : isa(newMethod->getDeclContext()) ? AMK_Redeclaration
+   : AMK_Override;
 
   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
 

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index c470598ef4f84..4bbbcf985cbd3 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2300,6 +2300,7 @@ AvailabilityAttr *Sema::mergeAvailabilityAttr(
 
   case AMK_Override:
   case AMK_ProtocolImplementation:
+  case AMK_OptionalProtocolImplementation:
 OverrideOrImpl = true;
 break;
   }
@@ -2368,6 +2369,14 @@ AvailabilityAttr *Sema::mergeAvailabilityAttr(
  diag::warn_mismatched_availability_override_unavail)
   << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
   << (AMK == AMK_Override);
+  } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
+// Allow 
diff erent 'introduced' / 'obsoleted' availability versions
+// on a method that implements an optional protocol requirement. It
+// makes less sense to allow this for 'deprecated' as the user 
can't
+// see if the method is 'deprecated' as 'respondsToSelector' will
+// still return true when the method is deprecated.
+   

[clang] 2669aba - [clang][CodeGen] Use llvm::stable_sort for multi version resolver options

2021-05-03 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-05-03T20:07:00-07:00
New Revision: 2669abaecfc47d4d2436559ab8c1fb49ad6e35c3

URL: 
https://github.com/llvm/llvm-project/commit/2669abaecfc47d4d2436559ab8c1fb49ad6e35c3
DIFF: 
https://github.com/llvm/llvm-project/commit/2669abaecfc47d4d2436559ab8c1fb49ad6e35c3.diff

LOG: [clang][CodeGen] Use llvm::stable_sort for multi version resolver options

The use of llvm::sort causes periodic failures on the bot with EXPENSIVE_CHECKS 
enabled,
as the regular sort pre-shuffles the array in the expensive checks mode, 
leading to a
non-deterministic test result which causes the 
CodeGenCXX/attr-cpuspecific-outoflinedefs.cpp
testcase to fail on the bot 
(http://lab.llvm.org:8080/green/job/clang-stage1-cmake-RA-expensive/).

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 8d4a0e0855b11..cb0523898c3af 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3344,7 +3344,7 @@ void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl 
GD) {
 ++Index;
   }
 
-  llvm::sort(
+  llvm::stable_sort(
   Options, [](const CodeGenFunction::MultiVersionResolverOption ,
   const CodeGenFunction::MultiVersionResolverOption ) {
 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) 
>



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8fc5f07 - [clang][driver][darwin] use the deployment target version as the SDK version

2021-04-30 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-04-30T18:54:02-07:00
New Revision: 8fc5f07fc0aee95ff9f79e91035d115690177dc1

URL: 
https://github.com/llvm/llvm-project/commit/8fc5f07fc0aee95ff9f79e91035d115690177dc1
DIFF: 
https://github.com/llvm/llvm-project/commit/8fc5f07fc0aee95ff9f79e91035d115690177dc1.diff

LOG: [clang][driver][darwin] use the deployment target version as the SDK 
version
when passing -platform_version to the linker

The use of a valid SDK version is preferred over an empty SDK version
(0.0.0) as the system's runtime might expect the linked binary to contain
a valid SDK version in order for the binary to work correctly

rdar://66795188

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/darwin-ld-platform-version-macos.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 177cfd60ffb36..5ccd2300afd39 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2671,8 +2671,16 @@ void Darwin::addPlatformVersionArgs(const 
llvm::opt::ArgList ,
 VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
 CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
   } else {
-// Use a blank SDK version if it's not present.
-CmdArgs.push_back("0.0.0");
+// Use an SDK version that's matching the deployment target if the SDK
+// version is missing. This is preferred over an empty SDK version (0.0.0)
+// as the system's runtime might expect the linked binary to contain a
+// valid SDK version in order for the binary to work correctly. It's
+// reasonable to use the deployment target version as a proxy for the
+// SDK version because older SDKs don't guarantee support for deployment
+// targets newer than the SDK versions, so that rules out using some
+// predetermined older SDK version, which leaves the deployment target
+// version as the only reasonable choice.
+CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
   }
 }
 

diff  --git a/clang/test/Driver/darwin-ld-platform-version-macos.c 
b/clang/test/Driver/darwin-ld-platform-version-macos.c
index 5a2510acb6467..8778281925d6b 100644
--- a/clang/test/Driver/darwin-ld-platform-version-macos.c
+++ b/clang/test/Driver/darwin-ld-platform-version-macos.c
@@ -48,4 +48,7 @@
 // RUN: %clang -target x86_64-apple-macos10.13 -mlinker-version=520 \
 // RUN:   -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=NOSDK %s
-// NOSDK: "-platform_version" "macos" "10.13.0" "0.0.0"
+// RUN: %clang -target x86_64-apple-darwin17 -mlinker-version=520 \
+// RUN:   -### %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=NOSDK %s
+// NOSDK: "-platform_version" "macos" "10.13.0" "10.13.0"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 6b938d2 - Recommit "[clang][driver] Use the provided arch name for a Darwin target triple

2021-04-29 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-04-29T15:00:40-07:00
New Revision: 6b938d2ead2cb0465436496c0171c7d750e11773

URL: 
https://github.com/llvm/llvm-project/commit/6b938d2ead2cb0465436496c0171c7d750e11773
DIFF: 
https://github.com/llvm/llvm-project/commit/6b938d2ead2cb0465436496c0171c7d750e11773.diff

LOG: Recommit "[clang][driver] Use the provided arch name for a Darwin target 
triple

This ensures that the Darwin driver uses a consistent target triple
representation when the triple is printed out to the user.

This reverts the revert commit ab0df6c0346e515291a381467527621ab0ccf953.

Differential Revision: https://reviews.llvm.org/D100807

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/aarch64-cpus.c
clang/test/Driver/arm64_32-link.c
clang/test/Driver/darwin-version.c
clang/test/Driver/default-toolchain.c
clang/test/Driver/openmp-offload-gpu.c
clang/test/Driver/openmp-offload.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index bc59b6beafc78..177cfd60ffb36 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -74,12 +74,12 @@ void darwin::setTripleTypeForMachOArchName(llvm::Triple , 
StringRef Str) {
   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
   llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
   T.setArch(Arch);
-
-  if (Str == "x86_64h" || Str == "arm64e")
+  if (Arch != llvm::Triple::UnknownArch)
 T.setArchName(Str);
-  else if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
-   ArchKind == llvm::ARM::ArchKind::ARMV7M ||
-   ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
+
+  if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
+  ArchKind == llvm::ARM::ArchKind::ARMV7M ||
+  ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
 T.setOS(llvm::Triple::UnknownOS);
 T.setObjectFormat(llvm::Triple::MachO);
   }

diff  --git a/clang/test/Driver/aarch64-cpus.c 
b/clang/test/Driver/aarch64-cpus.c
index 92ab325805d8c..0272925bc4e70 100644
--- a/clang/test/Driver/aarch64-cpus.c
+++ b/clang/test/Driver/aarch64-cpus.c
@@ -33,7 +33,7 @@
 // ARM64E-DARWIN: "-cc1"{{.*}} "-triple" "arm64e{{.*}}" "-target-cpu" 
"apple-a12"
 
 // RUN: %clang -target arm64-apple-darwin -arch arm64_32 -### -c %s 2>&1 | 
FileCheck -check-prefix=ARM64_32-DARWIN %s
-// ARM64_32-DARWIN: "-cc1"{{.*}} "-triple" "aarch64_32{{.*}}" "-target-cpu" 
"apple-s4"
+// ARM64_32-DARWIN: "-cc1"{{.*}} "-triple" "arm64_32{{.*}}" "-target-cpu" 
"apple-s4"
 
 // RUN: %clang -target aarch64 -mcpu=cortex-a35 -### -c %s 2>&1 | FileCheck 
-check-prefix=CA35 %s
 // RUN: %clang -target aarch64 -mlittle-endian -mcpu=cortex-a35 -### -c %s 
2>&1 | FileCheck -check-prefix=CA35 %s

diff  --git a/clang/test/Driver/arm64_32-link.c 
b/clang/test/Driver/arm64_32-link.c
index 972ae6a234e1d..6ef0b6f9f2f7d 100644
--- a/clang/test/Driver/arm64_32-link.c
+++ b/clang/test/Driver/arm64_32-link.c
@@ -1,4 +1,4 @@
 // RUN: %clang -target x86_64-apple-darwin -arch arm64_32 
-miphoneos-version-min=8.0 %s -### 2>&1 | FileCheck %s
 
-// CHECK: "-cc1"{{.*}} "-triple" "aarch64_32-apple-ios8.0.0"
+// CHECK: "-cc1"{{.*}} "-triple" "arm64_32-apple-ios8.0.0"
 // CHECK: ld{{.*}} "-arch" "arm64_32"

diff  --git a/clang/test/Driver/darwin-version.c 
b/clang/test/Driver/darwin-version.c
index 3471552c937f2..130a66575a932 100644
--- a/clang/test/Driver/darwin-version.c
+++ b/clang/test/Driver/darwin-version.c
@@ -60,17 +60,17 @@
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX4 %s
 // RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.4 -c %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX4 %s
-// CHECK-VERSION-OSX4: "i386-apple-macosx10.4.0"
+// CHECK-VERSION-OSX4: "i686-apple-macosx10.4.0"
 // RUN: %clang -target i686-apple-darwin9 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX5 %s
 // RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.5 -c %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX5 %s
-// CHECK-VERSION-OSX5: "i386-apple-macosx10.5.0"
+// CHECK-VERSION-OSX5: "i686-apple-macosx10.5.0"
 // RUN: %clang -target i686-apple-darwin10 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX6 %s
 // RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.6 -c %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX6 %s
-// CHECK-VERSION-OSX6: "i386-apple-macosx10.6.0"
+// CHECK-VERSION-OSX6: "i686-apple-macosx10.6.0"
 // RUN: %clang -target x86_64-apple-darwin14 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX10 %s
 // RUN: %clang -target x86_64-apple-darwin -mmacosx-version-min=10.10 -c %s 
-### 2>&1 | \
@@ -100,7 +100,7 @@
 
 // Check environment variable gets interpreted correctly
 // RUN: env MACOSX_DEPLOYMENT_TARGET=10.5 

[clang] 2509f9f - [clang] Don't crash when loading invalid VFS for the module dep collector

2021-04-26 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-04-26T17:05:22-07:00
New Revision: 2509f9fbad0d37e3e5fea934c0ae7af3877ba4ae

URL: 
https://github.com/llvm/llvm-project/commit/2509f9fbad0d37e3e5fea934c0ae7af3877ba4ae
DIFF: 
https://github.com/llvm/llvm-project/commit/2509f9fbad0d37e3e5fea934c0ae7af3877ba4ae.diff

LOG: [clang] Don't crash when loading invalid VFS for the module dep collector

The VFS is null when it's invalid so return early in collectVFSFromYAML.

Added: 
clang/test/VFS/broken-vfs-module-dep.c

Modified: 
llvm/lib/Support/VirtualFileSystem.cpp

Removed: 




diff  --git a/clang/test/VFS/broken-vfs-module-dep.c 
b/clang/test/VFS/broken-vfs-module-dep.c
new file mode 100644
index 0..2336306de8c6d
--- /dev/null
+++ b/clang/test/VFS/broken-vfs-module-dep.c
@@ -0,0 +1,7 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: not %clang_cc1 -module-dependency-dir %t -ivfsoverlay 
%S/Inputs/invalid-yaml.yaml %s 2>&1 | FileCheck %s
+
+// CHECK: error: Unexpected token
+// CHECK: error: Unexpected token
+// CHECK: 1 error generated

diff  --git a/llvm/lib/Support/VirtualFileSystem.cpp 
b/llvm/lib/Support/VirtualFileSystem.cpp
index deb0f37bd159d..dd820c15ca68e 100644
--- a/llvm/lib/Support/VirtualFileSystem.cpp
+++ b/llvm/lib/Support/VirtualFileSystem.cpp
@@ -2127,6 +2127,8 @@ void 
vfs::collectVFSFromYAML(std::unique_ptr Buffer,
   std::unique_ptr VFS = RedirectingFileSystem::create(
   std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
   std::move(ExternalFS));
+  if (!VFS)
+return;
   ErrorOr RootResult =
   VFS->lookupPath("/");
   if (!RootResult)



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ab0df6c - Revert "[clang][driver] Use the provided arch name for a Darwin target triple"

2021-04-26 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-04-26T14:57:00-07:00
New Revision: ab0df6c0346e515291a381467527621ab0ccf953

URL: 
https://github.com/llvm/llvm-project/commit/ab0df6c0346e515291a381467527621ab0ccf953
DIFF: 
https://github.com/llvm/llvm-project/commit/ab0df6c0346e515291a381467527621ab0ccf953.diff

LOG: Revert "[clang][driver] Use the provided arch name for a Darwin target 
triple"

This reverts commit 6cc62043c8bf4daa27664a2e1674abbe8d0492c6.

This caused a test failure on a M1 mac CI job 
(https://reviews.llvm.org/D100807#2718006),
I will recommit this with a fix.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/aarch64-cpus.c
clang/test/Driver/arm64_32-link.c
clang/test/Driver/darwin-version.c
clang/test/Driver/default-toolchain.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 177cfd60ffb3..bc59b6beafc7 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -74,12 +74,12 @@ void darwin::setTripleTypeForMachOArchName(llvm::Triple , 
StringRef Str) {
   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
   llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
   T.setArch(Arch);
-  if (Arch != llvm::Triple::UnknownArch)
-T.setArchName(Str);
 
-  if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
-  ArchKind == llvm::ARM::ArchKind::ARMV7M ||
-  ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
+  if (Str == "x86_64h" || Str == "arm64e")
+T.setArchName(Str);
+  else if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
+   ArchKind == llvm::ARM::ArchKind::ARMV7M ||
+   ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
 T.setOS(llvm::Triple::UnknownOS);
 T.setObjectFormat(llvm::Triple::MachO);
   }

diff  --git a/clang/test/Driver/aarch64-cpus.c 
b/clang/test/Driver/aarch64-cpus.c
index 9a2fc857a0c2..5b9bd5207792 100644
--- a/clang/test/Driver/aarch64-cpus.c
+++ b/clang/test/Driver/aarch64-cpus.c
@@ -33,7 +33,7 @@
 // ARM64E-DARWIN: "-cc1"{{.*}} "-triple" "arm64e{{.*}}" "-target-cpu" 
"apple-a12"
 
 // RUN: %clang -target arm64-apple-darwin -arch arm64_32 -### -c %s 2>&1 | 
FileCheck -check-prefix=ARM64_32-DARWIN %s
-// ARM64_32-DARWIN: "-cc1"{{.*}} "-triple" "arm64_32{{.*}}" "-target-cpu" 
"apple-s4"
+// ARM64_32-DARWIN: "-cc1"{{.*}} "-triple" "aarch64_32{{.*}}" "-target-cpu" 
"apple-s4"
 
 // RUN: %clang -target aarch64 -mcpu=cortex-a35 -### -c %s 2>&1 | FileCheck 
-check-prefix=CA35 %s
 // RUN: %clang -target aarch64 -mlittle-endian -mcpu=cortex-a35 -### -c %s 
2>&1 | FileCheck -check-prefix=CA35 %s

diff  --git a/clang/test/Driver/arm64_32-link.c 
b/clang/test/Driver/arm64_32-link.c
index 6ef0b6f9f2f7..972ae6a234e1 100644
--- a/clang/test/Driver/arm64_32-link.c
+++ b/clang/test/Driver/arm64_32-link.c
@@ -1,4 +1,4 @@
 // RUN: %clang -target x86_64-apple-darwin -arch arm64_32 
-miphoneos-version-min=8.0 %s -### 2>&1 | FileCheck %s
 
-// CHECK: "-cc1"{{.*}} "-triple" "arm64_32-apple-ios8.0.0"
+// CHECK: "-cc1"{{.*}} "-triple" "aarch64_32-apple-ios8.0.0"
 // CHECK: ld{{.*}} "-arch" "arm64_32"

diff  --git a/clang/test/Driver/darwin-version.c 
b/clang/test/Driver/darwin-version.c
index 130a66575a93..3471552c937f 100644
--- a/clang/test/Driver/darwin-version.c
+++ b/clang/test/Driver/darwin-version.c
@@ -60,17 +60,17 @@
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX4 %s
 // RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.4 -c %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX4 %s
-// CHECK-VERSION-OSX4: "i686-apple-macosx10.4.0"
+// CHECK-VERSION-OSX4: "i386-apple-macosx10.4.0"
 // RUN: %clang -target i686-apple-darwin9 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX5 %s
 // RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.5 -c %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX5 %s
-// CHECK-VERSION-OSX5: "i686-apple-macosx10.5.0"
+// CHECK-VERSION-OSX5: "i386-apple-macosx10.5.0"
 // RUN: %clang -target i686-apple-darwin10 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX6 %s
 // RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.6 -c %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX6 %s
-// CHECK-VERSION-OSX6: "i686-apple-macosx10.6.0"
+// CHECK-VERSION-OSX6: "i386-apple-macosx10.6.0"
 // RUN: %clang -target x86_64-apple-darwin14 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX10 %s
 // RUN: %clang -target x86_64-apple-darwin -mmacosx-version-min=10.10 -c %s 
-### 2>&1 | \
@@ -100,7 +100,7 @@
 
 // Check environment variable gets interpreted correctly
 // RUN: env MACOSX_DEPLOYMENT_TARGET=10.5 IPHONEOS_DEPLOYMENT_TARGET=2.0 \
-// RUN:   %clang -target i686-apple-darwin9 -c %s -### 2>&1 | \
+// RUN:   %clang -target i386-apple-darwin9 -c %s 

[clang] 6cc6204 - [clang][driver] Use the provided arch name for a Darwin target triple

2021-04-26 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-04-26T11:31:50-07:00
New Revision: 6cc62043c8bf4daa27664a2e1674abbe8d0492c6

URL: 
https://github.com/llvm/llvm-project/commit/6cc62043c8bf4daa27664a2e1674abbe8d0492c6
DIFF: 
https://github.com/llvm/llvm-project/commit/6cc62043c8bf4daa27664a2e1674abbe8d0492c6.diff

LOG: [clang][driver] Use the provided arch name for a Darwin target triple

This ensures that the Darwin driver uses a consistent target triple
representation when the triple is printed out to the user.

Differential Revision: https://reviews.llvm.org/D100807

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/aarch64-cpus.c
clang/test/Driver/arm64_32-link.c
clang/test/Driver/darwin-version.c
clang/test/Driver/default-toolchain.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index bc59b6beafc7..177cfd60ffb3 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -74,12 +74,12 @@ void darwin::setTripleTypeForMachOArchName(llvm::Triple , 
StringRef Str) {
   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
   llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
   T.setArch(Arch);
-
-  if (Str == "x86_64h" || Str == "arm64e")
+  if (Arch != llvm::Triple::UnknownArch)
 T.setArchName(Str);
-  else if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
-   ArchKind == llvm::ARM::ArchKind::ARMV7M ||
-   ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
+
+  if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
+  ArchKind == llvm::ARM::ArchKind::ARMV7M ||
+  ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
 T.setOS(llvm::Triple::UnknownOS);
 T.setObjectFormat(llvm::Triple::MachO);
   }

diff  --git a/clang/test/Driver/aarch64-cpus.c 
b/clang/test/Driver/aarch64-cpus.c
index 5b9bd5207792..9a2fc857a0c2 100644
--- a/clang/test/Driver/aarch64-cpus.c
+++ b/clang/test/Driver/aarch64-cpus.c
@@ -33,7 +33,7 @@
 // ARM64E-DARWIN: "-cc1"{{.*}} "-triple" "arm64e{{.*}}" "-target-cpu" 
"apple-a12"
 
 // RUN: %clang -target arm64-apple-darwin -arch arm64_32 -### -c %s 2>&1 | 
FileCheck -check-prefix=ARM64_32-DARWIN %s
-// ARM64_32-DARWIN: "-cc1"{{.*}} "-triple" "aarch64_32{{.*}}" "-target-cpu" 
"apple-s4"
+// ARM64_32-DARWIN: "-cc1"{{.*}} "-triple" "arm64_32{{.*}}" "-target-cpu" 
"apple-s4"
 
 // RUN: %clang -target aarch64 -mcpu=cortex-a35 -### -c %s 2>&1 | FileCheck 
-check-prefix=CA35 %s
 // RUN: %clang -target aarch64 -mlittle-endian -mcpu=cortex-a35 -### -c %s 
2>&1 | FileCheck -check-prefix=CA35 %s

diff  --git a/clang/test/Driver/arm64_32-link.c 
b/clang/test/Driver/arm64_32-link.c
index 972ae6a234e1..6ef0b6f9f2f7 100644
--- a/clang/test/Driver/arm64_32-link.c
+++ b/clang/test/Driver/arm64_32-link.c
@@ -1,4 +1,4 @@
 // RUN: %clang -target x86_64-apple-darwin -arch arm64_32 
-miphoneos-version-min=8.0 %s -### 2>&1 | FileCheck %s
 
-// CHECK: "-cc1"{{.*}} "-triple" "aarch64_32-apple-ios8.0.0"
+// CHECK: "-cc1"{{.*}} "-triple" "arm64_32-apple-ios8.0.0"
 // CHECK: ld{{.*}} "-arch" "arm64_32"

diff  --git a/clang/test/Driver/darwin-version.c 
b/clang/test/Driver/darwin-version.c
index 3471552c937f..130a66575a93 100644
--- a/clang/test/Driver/darwin-version.c
+++ b/clang/test/Driver/darwin-version.c
@@ -60,17 +60,17 @@
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX4 %s
 // RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.4 -c %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX4 %s
-// CHECK-VERSION-OSX4: "i386-apple-macosx10.4.0"
+// CHECK-VERSION-OSX4: "i686-apple-macosx10.4.0"
 // RUN: %clang -target i686-apple-darwin9 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX5 %s
 // RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.5 -c %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX5 %s
-// CHECK-VERSION-OSX5: "i386-apple-macosx10.5.0"
+// CHECK-VERSION-OSX5: "i686-apple-macosx10.5.0"
 // RUN: %clang -target i686-apple-darwin10 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX6 %s
 // RUN: %clang -target i686-apple-darwin9 -mmacosx-version-min=10.6 -c %s -### 
2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX6 %s
-// CHECK-VERSION-OSX6: "i386-apple-macosx10.6.0"
+// CHECK-VERSION-OSX6: "i686-apple-macosx10.6.0"
 // RUN: %clang -target x86_64-apple-darwin14 -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX10 %s
 // RUN: %clang -target x86_64-apple-darwin -mmacosx-version-min=10.10 -c %s 
-### 2>&1 | \
@@ -100,7 +100,7 @@
 
 // Check environment variable gets interpreted correctly
 // RUN: env MACOSX_DEPLOYMENT_TARGET=10.5 IPHONEOS_DEPLOYMENT_TARGET=2.0 \
-// RUN:   %clang -target i386-apple-darwin9 -c %s -### 2>&1 | \
+// RUN:   %clang -target i686-apple-darwin9 -c %s -### 2>&1 | \
 // RUN:   FileCheck 

[clang] c1554f3 - [clang][FileManager] Support empty file name in getVirtualFileRef for serialized diagnostics

2021-04-14 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-04-14T11:29:25-07:00
New Revision: c1554f32e3b3fafab64698fdb5b806b1bda4aa8a

URL: 
https://github.com/llvm/llvm-project/commit/c1554f32e3b3fafab64698fdb5b806b1bda4aa8a
DIFF: 
https://github.com/llvm/llvm-project/commit/c1554f32e3b3fafab64698fdb5b806b1bda4aa8a.diff

LOG: [clang][FileManager] Support empty file name in getVirtualFileRef for 
serialized diagnostics

After https://reviews.llvm.org/D90484 libclang is unable to read a serialized 
diagnostic file
which contains a diagnostic which came from a file with an empty filename. The 
reason being is
that the serialized diagnostic reader is creating a virtual file for the "" 
filename, which now
fails after the changes in https://reviews.llvm.org/D90484. This patch restores 
the previous
behavior in getVirtualFileRef by allowing it to construct a file entry ref with 
an empty name by
pretending its name is "." so that the directory entry can be created.

Differential Revision: https://reviews.llvm.org/D100428

Added: 
clang/test/Misc/serialized-diags-empty-filename.c

Modified: 
clang/lib/Basic/FileManager.cpp

Removed: 




diff  --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp
index 6e9d5d7fb4222..d39d7ba22643b 100644
--- a/clang/lib/Basic/FileManager.cpp
+++ b/clang/lib/Basic/FileManager.cpp
@@ -384,9 +384,12 @@ FileEntryRef FileManager::getVirtualFileRef(StringRef 
Filename, off_t Size,
 
   // Now that all ancestors of Filename are in the cache, the
   // following call is guaranteed to find the DirectoryEntry from the
-  // cache.
-  auto DirInfo = expectedToOptional(
-  getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true));
+  // cache. A virtual file can also have an empty filename, that could come
+  // from a source location preprocessor directive with an empty filename as
+  // an example, so we need to pretend it has a name to ensure a valid 
directory
+  // entry can be returned.
+  auto DirInfo = expectedToOptional(getDirectoryFromFile(
+  *this, Filename.empty() ? "." : Filename, /*CacheFailure=*/true));
   assert(DirInfo &&
  "The directory of a virtual file should already be in the cache.");
 

diff  --git a/clang/test/Misc/serialized-diags-empty-filename.c 
b/clang/test/Misc/serialized-diags-empty-filename.c
new file mode 100644
index 0..e86108414273e
--- /dev/null
+++ b/clang/test/Misc/serialized-diags-empty-filename.c
@@ -0,0 +1,8 @@
+// RUN: rm -f %t.diag
+// RUN: not %clang -c %s --serialize-diagnostics %t.diag
+// RUN: c-index-test -read-diagnostics %t.diag 2>&1 | FileCheck %s
+
+# 1 "" 1
+void 1();
+
+// CHECK: :1:6: error:



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d672d52 - Revert "[CodeGenModule] Set dso_local for Mach-O GlobalValue"

2021-03-17 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-03-17T17:27:41-07:00
New Revision: d672d5219a72d2e13dcc257116876d41955e36b2

URL: 
https://github.com/llvm/llvm-project/commit/d672d5219a72d2e13dcc257116876d41955e36b2
DIFF: 
https://github.com/llvm/llvm-project/commit/d672d5219a72d2e13dcc257116876d41955e36b2.diff

LOG: Revert "[CodeGenModule] Set dso_local for Mach-O GlobalValue"

This reverts commit 809a1e0ffd7af40ee27270ff8ba2ffc927330e71.

Mach-O doesn't support dso_local and this change broke XNU because of the use 
of dso_local.

Differential Revision: https://reviews.llvm.org/D98458

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGen/attr-weak-import.c
clang/test/CodeGenCXX/bitfield-layout.cpp
clang/test/CodeGenCXX/const-init.cpp
clang/test/CodeGenCXX/linkage.cpp
clang/test/CodeGenCXX/temporaries.cpp
clang/test/CodeGenCXX/type_visibility.cpp
clang/test/CodeGenCXX/visibility.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index f3a73f8783dc..3a197e85ef7b 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -978,20 +978,14 @@ static bool shouldAssumeDSOLocal(const CodeGenModule ,
   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
 return true;
 
-  const auto  = CGM.getCodeGenOpts();
-  llvm::Reloc::Model RM = CGOpts.RelocationModel;
-  const auto  = CGM.getLangOpts();
-
-  if (TT.isOSBinFormatMachO()) {
-if (RM == llvm::Reloc::Static)
-  return true;
-return GV->isStrongDefinitionForLinker();
-  }
-
   // Only handle COFF and ELF for now.
   if (!TT.isOSBinFormatELF())
 return false;
 
+  // If this is not an executable, don't assume anything is local.
+  const auto  = CGM.getCodeGenOpts();
+  llvm::Reloc::Model RM = CGOpts.RelocationModel;
+  const auto  = CGM.getLangOpts();
   if (RM != llvm::Reloc::Static && !LOpts.PIE) {
 // On ELF, if -fno-semantic-interposition is specified and the target
 // supports local aliases, there will be neither CC1

diff  --git a/clang/test/CodeGen/attr-weak-import.c 
b/clang/test/CodeGen/attr-weak-import.c
index 85989f03a277..f02d09e81509 100644
--- a/clang/test/CodeGen/attr-weak-import.c
+++ b/clang/test/CodeGen/attr-weak-import.c
@@ -18,9 +18,9 @@ extern int E __attribute__((weak_import));
 int E;
 extern int E __attribute__((weak_import));
 
-// CHECK: @A = dso_local global i32
+// CHECK: @A = global i32
 // CHECK-NOT: @B =
-// CHECK: @C = dso_local global i32
-// CHECK: @D = dso_local global i32
-// CHECK: @E = dso_local global i32
+// CHECK: @C = global i32
+// CHECK: @D = global i32
+// CHECK: @E = global i32
 

diff  --git a/clang/test/CodeGenCXX/bitfield-layout.cpp 
b/clang/test/CodeGenCXX/bitfield-layout.cpp
index 79dbf9c691c4..d570b8f33e34 100644
--- a/clang/test/CodeGenCXX/bitfield-layout.cpp
+++ b/clang/test/CodeGenCXX/bitfield-layout.cpp
@@ -93,7 +93,7 @@ int test_trunc_int() {
   } const U = {15};  // 0b
   return U.i;
 }
-// CHECK: define dso_local i32 @test_trunc_int()
+// CHECK: define{{.*}} i32 @test_trunc_int()
 // CHECK: ret i32 -1
 
 int test_trunc_three_bits() {
@@ -102,7 +102,7 @@ int test_trunc_three_bits() {
   } const U = {15};  // 0b
   return U.i;
 }
-// CHECK: define dso_local i32 @test_trunc_three_bits()
+// CHECK: define{{.*}} i32 @test_trunc_three_bits()
 // CHECK: ret i32 -1
 
 int test_trunc_1() {
@@ -111,7 +111,7 @@ int test_trunc_1() {
   } const U = {15};  // 0b
   return U.i;
 }
-// CHECK: define dso_local i32 @test_trunc_1()
+// CHECK: define{{.*}} i32 @test_trunc_1()
 // CHECK: ret i32 -1
 
 int test_trunc_zero() {
@@ -120,7 +120,7 @@ int test_trunc_zero() {
   } const U = {80};  // 0b0101
   return U.i;
 }
-// CHECK: define dso_local i32 @test_trunc_zero()
+// CHECK: define{{.*}} i32 @test_trunc_zero()
 // CHECK: ret i32 0
 
 int test_constexpr() {
@@ -129,7 +129,7 @@ int test_constexpr() {
   } const U = {1 + 2 + 4 + 8}; // 0b
   return U.i;
 }
-// CHECK: define dso_local i32 @test_constexpr()
+// CHECK: define{{.*}} i32 @test_constexpr()
 // CHECK: ret i32 -1
 
 int test_notrunc() {
@@ -138,7 +138,7 @@ int test_notrunc() {
   } const U = {1 + 2 + 4 + 8}; // 0b
   return U.i;
 }
-// CHECK: define dso_local i32 @test_notrunc()
+// CHECK: define{{.*}} i32 @test_notrunc()
 // CHECK: ret i32 15
 
 long long test_trunc_long_long() {
@@ -147,6 +147,6 @@ long long test_trunc_long_long() {
   } const U = {0b010001001101};
   return U.i;
 }
-// CHECK: define dso_local i64 @test_trunc_long_long()
+// CHECK: define{{.*}} i64 @test_trunc_long_long()
 // CHECK: ret i64 3917
 }

diff  --git a/clang/test/CodeGenCXX/const-init.cpp 
b/clang/test/CodeGenCXX/const-init.cpp
index 5b305bc5e4d6..f5c9dae7ba4b 100644
--- a/clang/test/CodeGenCXX/const-init.cpp
+++ b/clang/test/CodeGenCXX/const-init.cpp
@@ -2,17 +2,17 @@
 // 

[clang] 234f321 - [clang][driver] Support Darwin SDK names with an optional prefix in their name

2021-03-09 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-03-09T14:57:58-08:00
New Revision: 234f3211a3dd84bb2c074402054452af24b914a6

URL: 
https://github.com/llvm/llvm-project/commit/234f3211a3dd84bb2c074402054452af24b914a6
DIFF: 
https://github.com/llvm/llvm-project/commit/234f3211a3dd84bb2c074402054452af24b914a6.diff

LOG: [clang][driver] Support Darwin SDK names with an optional prefix in their 
name

rdar://74017977

Added: 
clang/test/Driver/darwin-sdk-with-prefix.c

Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 91241ff9bd81..a09a69f946ef 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1628,6 +1628,15 @@ getDeploymentTargetFromEnvironmentVariables(const Driver 
,
   return None;
 }
 
+/// Returns the SDK name without the optional prefix that ends with a '.' or an
+/// empty string otherwise.
+static StringRef dropSDKNamePrefix(StringRef SDKName) {
+  size_t PrefixPos = SDKName.find('.');
+  if (PrefixPos == StringRef::npos)
+return "";
+  return SDKName.substr(PrefixPos + 1);
+}
+
 /// Tries to infer the deployment target from the SDK specified by -isysroot
 /// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
 /// it's available.
@@ -1657,22 +1666,29 @@ inferDeploymentTargetFromSDK(DerivedArgList ,
   if (Version.empty())
 return None;
 
-  if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
-return DarwinPlatform::createFromSDK(
-Darwin::IPhoneOS, Version,
-/*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
-  else if (SDK.startswith("MacOSX"))
-return DarwinPlatform::createFromSDK(Darwin::MacOS,
- getSystemOrSDKMacOSVersion(Version));
-  else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
-return DarwinPlatform::createFromSDK(
-Darwin::WatchOS, Version,
-/*IsSimulator=*/SDK.startswith("WatchSimulator"));
-  else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
-return DarwinPlatform::createFromSDK(
-Darwin::TvOS, Version,
-/*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
-  return None;
+  auto CreatePlatformFromSDKName =
+  [&](StringRef SDK) -> Optional {
+if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
+  return DarwinPlatform::createFromSDK(
+  Darwin::IPhoneOS, Version,
+  /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
+else if (SDK.startswith("MacOSX"))
+  return DarwinPlatform::createFromSDK(Darwin::MacOS,
+   
getSystemOrSDKMacOSVersion(Version));
+else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
+  return DarwinPlatform::createFromSDK(
+  Darwin::WatchOS, Version,
+  /*IsSimulator=*/SDK.startswith("WatchSimulator"));
+else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
+  return DarwinPlatform::createFromSDK(
+  Darwin::TvOS, Version,
+  /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
+return None;
+  };
+  if (auto Result = CreatePlatformFromSDKName(SDK))
+return Result;
+  // The SDK can be an SDK variant with a name like `.`.
+  return CreatePlatformFromSDKName(dropSDKNamePrefix(SDK));
 }
 
 std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple ,
@@ -1928,7 +1944,8 @@ void Darwin::AddDeploymentTarget(DerivedArgList ) 
const {
 if (SDK.size() > 0) {
   size_t StartVer = SDK.find_first_of("0123456789");
   StringRef SDKName = SDK.slice(0, StartVer);
-  if (!SDKName.startswith(getPlatformFamily()))
+  if (!SDKName.startswith(getPlatformFamily()) &&
+  !dropSDKNamePrefix(SDKName).startswith(getPlatformFamily()))
 getDriver().Diag(diag::warn_incompatible_sysroot)
 << SDKName << getPlatformFamily();
 }

diff  --git a/clang/test/Driver/darwin-sdk-with-prefix.c 
b/clang/test/Driver/darwin-sdk-with-prefix.c
new file mode 100644
index ..7619ded56b65
--- /dev/null
+++ b/clang/test/Driver/darwin-sdk-with-prefix.c
@@ -0,0 +1,10 @@
+// RUN: rm -rf %t.dir
+// RUN: mkdir -p %t.dir
+
+// RUN: rm -rf %t.dir/prefix.iPhoneOS12.0.0.sdk
+// RUN: mkdir -p %t.dir/prefix.iPhoneOS12.0.0.sdk
+// RUN: %clang -c -isysroot %t.dir/prefix.iPhoneOS12.0.0.sdk -target 
arm64-apple-darwin %s -### 2>&1 | FileCheck %s
+// RUN: env SDKROOT=%t.dir/prefix.iPhoneOS12.0.0.sdk %clang -c -target 
arm64-apple-darwin %s -### 2>&1 | FileCheck %s
+//
+// CHECK-NOT: warning: using sysroot for
+// CHECK: "-triple" "arm64-apple-ios12.0.0"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2de0a18 - [clang][ObjC] allow the use of NSAttributedString * return type with format_arg attribute

2021-03-09 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2021-03-09T13:36:57-08:00
New Revision: 2de0a18a8949f0235fb3a08dcc55ff3aa7d969e7

URL: 
https://github.com/llvm/llvm-project/commit/2de0a18a8949f0235fb3a08dcc55ff3aa7d969e7
DIFF: 
https://github.com/llvm/llvm-project/commit/2de0a18a8949f0235fb3a08dcc55ff3aa7d969e7.diff

LOG: [clang][ObjC] allow the use of NSAttributedString * return type with 
format_arg attribute

This is useful for APIs that want to produce an attributed NSString as a result 
of
some formatting API call.

Added: 


Modified: 
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/SemaObjC/format-arg-attribute.m

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 5b9acda6738e..c309f0436437 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -154,7 +154,8 @@ static bool isInstanceMethod(const Decl *D) {
   return false;
 }
 
-static inline bool isNSStringType(QualType T, ASTContext ) {
+static inline bool isNSStringType(QualType T, ASTContext ,
+  bool AllowNSAttributedString = false) {
   const auto *PT = T->getAs();
   if (!PT)
 return false;
@@ -165,6 +166,9 @@ static inline bool isNSStringType(QualType T, ASTContext 
) {
 
   IdentifierInfo* ClsName = Cls->getIdentifier();
 
+  if (AllowNSAttributedString &&
+  ClsName == ("NSAttributedString"))
+return true;
   // FIXME: Should we walk the chain of classes?
   return ClsName == ("NSString") ||
  ClsName == ("NSMutableString");
@@ -3286,7 +3290,7 @@ static void handleFormatArgAttr(Sema , Decl *D, const 
ParsedAttr ) {
 return;
   }
   Ty = getFunctionOrMethodResultType(D);
-  if (!isNSStringType(Ty, S.Context) &&
+  if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) &&
   !isCFStringType(Ty, S.Context) &&
   (!Ty->isPointerType() ||
!Ty->castAs()->getPointeeType()->isCharType())) {

diff  --git a/clang/test/SemaObjC/format-arg-attribute.m 
b/clang/test/SemaObjC/format-arg-attribute.m
index 67c9c2e3d4c9..ac81bdc21dc1 100644
--- a/clang/test/SemaObjC/format-arg-attribute.m
+++ b/clang/test/SemaObjC/format-arg-attribute.m
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -verify -fsyntax-only %s
 
 @class NSString;
+@class NSAttributedString;
 
 extern NSString *fa2 (const NSString *) __attribute__((format_arg(1)));
 extern NSString *fa3 (NSString *) __attribute__((format_arg(1)));
@@ -25,3 +26,5 @@
 extern int fi3 (const NSString *) __attribute__((format_arg(1)));  // 
expected-error {{function does not return NSString}}
 extern NSString *fi4 (const NSString *) __attribute__((format_arg(1))); 
 extern NSString *fi5 (const NSString *) __attribute__((format_arg(1))); 
+
+extern NSAttributedString *fattrs (const NSString *) 
__attribute__((format_arg(1)));



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] db226cd - [objc] diagnose protocol conformance in categories with direct members

2020-12-04 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-12-04T15:55:34-08:00
New Revision: db226cdf4cf91f350267da1a5b95dda42dd23413

URL: 
https://github.com/llvm/llvm-project/commit/db226cdf4cf91f350267da1a5b95dda42dd23413
DIFF: 
https://github.com/llvm/llvm-project/commit/db226cdf4cf91f350267da1a5b95dda42dd23413.diff

LOG: [objc] diagnose protocol conformance in categories with direct members
in their corresponding class interfaces

Categories that add protocol conformances to classes with direct members should 
prohibit protocol
conformances when the methods/properties that the protocol expects are actually 
declared as 'direct' in the class.

Differential Revision: https://reviews.llvm.org/D92602

Added: 
clang/test/SemaObjC/category-direct-members-protocol-conformance.m

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDeclObjC.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 21660965abf7..01a521fc603e 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1062,6 +1062,10 @@ def warn_objc_direct_property_ignored : Warning<
   InGroup;
 def err_objc_direct_dynamic_property : Error<
   "direct property cannot be @dynamic">;
+def err_objc_direct_protocol_conformance : Error<
+  "%select{category %1|class extension}0 cannot conform to protocol %2 because 
"
+  "of direct members declared in interface %3">;
+def note_direct_member_here : Note<"direct member declared here">;
 
 def warn_conflicting_overriding_ret_types : Warning<
   "conflicting return type in "

diff  --git a/clang/lib/Sema/SemaDeclObjC.cpp b/clang/lib/Sema/SemaDeclObjC.cpp
index a48919685ba2..60253a82e93a 100644
--- a/clang/lib/Sema/SemaDeclObjC.cpp
+++ b/clang/lib/Sema/SemaDeclObjC.cpp
@@ -3912,6 +3912,55 @@ static void DiagnoseVariableSizedIvars(Sema , 
ObjCContainerDecl *OCD) {
   }
 }
 
+static void DiagnoseCategoryDirectMembersProtocolConformance(
+Sema , ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl);
+
+static void DiagnoseCategoryDirectMembersProtocolConformance(
+Sema , ObjCCategoryDecl *CDecl,
+const llvm::iterator_range ) {
+  for (auto *PI : Protocols)
+DiagnoseCategoryDirectMembersProtocolConformance(S, PI, CDecl);
+}
+
+static void DiagnoseCategoryDirectMembersProtocolConformance(
+Sema , ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) {
+  if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
+PDecl = PDecl->getDefinition();
+
+  llvm::SmallVector DirectMembers;
+  const auto *IDecl = CDecl->getClassInterface();
+  for (auto *MD : PDecl->methods()) {
+if (!MD->isPropertyAccessor()) {
+  if (const auto *CMD =
+  IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) {
+if (CMD->isDirectMethod())
+  DirectMembers.push_back(CMD);
+  }
+}
+  }
+  for (auto *PD : PDecl->properties()) {
+if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass(
+PD->getIdentifier(),
+PD->isClassProperty()
+? ObjCPropertyQueryKind::OBJC_PR_query_class
+: ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
+  if (CPD->isDirectProperty())
+DirectMembers.push_back(CPD);
+}
+  }
+  if (!DirectMembers.empty()) {
+S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance)
+<< CDecl->IsClassExtension() << CDecl << PDecl << IDecl;
+for (const auto *MD : DirectMembers)
+  S.Diag(MD->getLocation(), diag::note_direct_member_here);
+return;
+  }
+
+  // Check on this protocols's referenced protocols, recursively.
+  DiagnoseCategoryDirectMembersProtocolConformance(S, CDecl,
+   PDecl->protocols());
+}
+
 // Note: For class/category implementations, allMethods is always null.
 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef 
allMethods,
ArrayRef allTUVars) {
@@ -4012,6 +4061,8 @@ Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, 
ArrayRef allMethods,
   ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
   DiagnoseClassExtensionDupMethods(C, CCPrimary);
 }
+
+DiagnoseCategoryDirectMembersProtocolConformance(*this, C, C->protocols());
   }
   if (ObjCContainerDecl *CDecl = dyn_cast(ClassDecl)) {
 if (CDecl->getIdentifier())

diff  --git 
a/clang/test/SemaObjC/category-direct-members-protocol-conformance.m 
b/clang/test/SemaObjC/category-direct-members-protocol-conformance.m
new file mode 100644
index ..dfee42f58869
--- /dev/null
+++ b/clang/test/SemaObjC/category-direct-members-protocol-conformance.m
@@ -0,0 +1,98 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+__attribute__((objc_root_class))
+@interface RootClass
+
+- (void)baseMethod;
+
+@end
+

[clang] eddd1d1 - [clang] add a `swift_async_name` attribute

2020-12-04 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-12-04T15:55:29-08:00
New Revision: eddd1d192bcaf11e449b34a3a569b85eb390e4f2

URL: 
https://github.com/llvm/llvm-project/commit/eddd1d192bcaf11e449b34a3a569b85eb390e4f2
DIFF: 
https://github.com/llvm/llvm-project/commit/eddd1d192bcaf11e449b34a3a569b85eb390e4f2.diff

LOG: [clang] add a `swift_async_name` attribute

The swift_async_name attribute provides a name for a function/method that can 
be used
to call the async overload of this method from Swift. This name specified in 
this attribute
assumes that the last parameter in the function/method its applied to is 
removed when
Swift invokes it, as the the Swift's await/async transformation implicitly 
constructs the callback.

Differential Revision: https://reviews.llvm.org/D92355

Added: 
clang/test/SemaObjCXX/attr-swift_name-cxx.mm

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/Misc/pragma-attribute-supported-attributes-list.test
clang/test/SemaObjC/attr-swift_name.m

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 3beef7b89243..0212b60a2afe 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2149,6 +2149,13 @@ def Regparm : TypeAttr {
   let ASTNode = 0;
 }
 
+def SwiftAsyncName : InheritableAttr {
+  let Spellings = [GNU<"swift_async_name">];
+  let Args = [StringArgument<"Name">];
+  let Subjects = SubjectList<[ObjCMethod, Function], ErrorDiag>;
+  let Documentation = [SwiftAsyncNameDocs];
+}
+
 def SwiftAttr : InheritableAttr {
   let Spellings = [GNU<"swift_attr">];
   let Args = [StringArgument<"Attribute">];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 673c9553c83d..bf985986e21b 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -3628,6 +3628,27 @@ Swift.
   }];
 }
 
+def SwiftAsyncNameDocs : Documentation {
+  let Category = SwiftDocs;
+  let Heading = "swift_async_name";
+  let Content = [{
+The ``swift_async_name`` attribute provides the name of the ``async`` overload 
for
+the given declaration in Swift. If this attribute is absent, the name is
+transformed according to the algorithm built into the Swift compiler.
+
+The argument is a string literal that contains the Swift name of the function 
or
+method. The name may be a compound Swift name. The function or method with such
+an attribute must have more than zero parameters, as its last parameter is
+assumed to be a callback that's eliminated in the Swift ``async`` name.
+
+  .. code-block:: objc
+
+@interface URL
++ (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data 
__attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
+@end
+  }];
+}
+
 def SwiftAttrDocs : Documentation {
   let Category = SwiftDocs;
   let Heading = "swift_attr";

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index f51ef849b932..21660965abf7 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4028,7 +4028,12 @@ def warn_attr_swift_name_subscript_getter_newValue
   : Warning<"%0 attribute for 'subscript' getter cannot have a 'newValue:' 
parameter">,
 InGroup;
 def warn_attr_swift_name_num_params
-  : Warning<"too %select{few|many}0 parameters in %1 attribute (expected %2; 
got %3)">,
+  : Warning<"too %select{few|many}0 parameters in the signature specified by "
+"the %1 attribute (expected %2; got %3)">,
+InGroup;
+def warn_attr_swift_name_decl_missing_params
+  : Warning<"%0 attribute cannot be applied to a %select{function|method}1 "
+"with no parameters">,
 InGroup;
 
 def err_attr_swift_error_no_error_parameter : Error<

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index b3ede504542f..980be69cb1a5 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1977,7 +1977,7 @@ class Sema final {
   ///
   /// \returns true if the name is a valid swift name for \p D, false 
otherwise.
   bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
- const ParsedAttr );
+ const ParsedAttr , bool IsAsync);
 
   /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
   /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index e0aa6d1f119c..a3153979deff 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -5922,7 +5922,7 @@ 

[clang] 03dcd57 - [clang] add a new `swift_attr` attribute

2020-12-04 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-12-04T15:53:24-08:00
New Revision: 03dcd57ecf99b31021644b868cae422897d520f8

URL: 
https://github.com/llvm/llvm-project/commit/03dcd57ecf99b31021644b868cae422897d520f8
DIFF: 
https://github.com/llvm/llvm-project/commit/03dcd57ecf99b31021644b868cae422897d520f8.diff

LOG: [clang] add a new `swift_attr` attribute

The swift_attr attribute is a generic annotation attribute that's not used by 
clang,
but is used by the Swift compiler. The Swift compiler can use these annotations 
to provide
various syntactic and semantic sugars for the imported Objective-C API 
declarations.

Differential Revision: https://reviews.llvm.org/D92354

Added: 
clang/test/AST/attr-swift_attr.m
clang/test/SemaObjC/validate-attr-swift_attr.m

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/lib/Sema/SemaDeclAttr.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 8555bd351747..3beef7b89243 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2149,6 +2149,12 @@ def Regparm : TypeAttr {
   let ASTNode = 0;
 }
 
+def SwiftAttr : InheritableAttr {
+  let Spellings = [GNU<"swift_attr">];
+  let Args = [StringArgument<"Attribute">];
+  let Documentation = [SwiftAttrDocs];
+}
+
 def SwiftBridge : InheritableAttr {
   let Spellings = [GNU<"swift_bridge">];
   let Args = [StringArgument<"SwiftType">];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 1781543cc4f3..673c9553c83d 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -3628,6 +3628,19 @@ Swift.
   }];
 }
 
+def SwiftAttrDocs : Documentation {
+  let Category = SwiftDocs;
+  let Heading = "swift_attr";
+  let Content = [{
+The ``swift_attr`` provides a Swift-specific annotation for the declaration
+to which the attribute appertains to. It can be used on any declaration
+in Clang. This kind of annotation is ignored by Clang as it doesn't have any
+semantic meaning in languages supported by Clang. The Swift compiler can
+interpret these annotations according to its own rules when importing C or
+Objective-C declarations.
+}];
+}
+
 def SwiftBridgeDocs : Documentation {
   let Category = SwiftDocs;
   let Heading = "swift_bridge";

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index d31d18eac474..e0aa6d1f119c 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -5607,6 +5607,16 @@ static void handleObjCPreciseLifetimeAttr(Sema , Decl 
*D,
   D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
 }
 
+static void handleSwiftAttrAttr(Sema , Decl *D, const ParsedAttr ) {
+  // Make sure that there is a string literal as the annotation's single
+  // argument.
+  StringRef Str;
+  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
+return;
+
+  D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str));
+}
+
 static void handleSwiftBridge(Sema , Decl *D, const ParsedAttr ) {
   // Make sure that there is a string literal as the annotation's single
   // argument.
@@ -7941,6 +7951,9 @@ static void ProcessDeclAttribute(Sema , Scope *scope, 
Decl *D,
 break;
 
   // Swift attributes.
+  case ParsedAttr::AT_SwiftAttr:
+handleSwiftAttrAttr(S, D, AL);
+break;
   case ParsedAttr::AT_SwiftBridge:
 handleSwiftBridge(S, D, AL);
 break;

diff  --git a/clang/test/AST/attr-swift_attr.m 
b/clang/test/AST/attr-swift_attr.m
new file mode 100644
index ..3cd51b81e349
--- /dev/null
+++ b/clang/test/AST/attr-swift_attr.m
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -fsyntax-only -ast-dump %s | FileCheck %s
+
+__attribute__((swift_attr("@actor")))
+@interface View
+@end
+
+// CHECK: InterfaceDecl {{.*}} View
+// CHECK-NEXT: SwiftAttrAttr {{.*}} "@actor"

diff  --git a/clang/test/SemaObjC/validate-attr-swift_attr.m 
b/clang/test/SemaObjC/validate-attr-swift_attr.m
new file mode 100644
index ..4ff434d17972
--- /dev/null
+++ b/clang/test/SemaObjC/validate-attr-swift_attr.m
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -verify -fsyntax-only %s
+
+// expected-error@+1 {{'swift_attr' attribute takes one argument}}
+__attribute__((swift_attr))
+@interface I
+@end
+
+// expected-error@+1 {{'swift_attr' attribute requires a string}}
+__attribute__((swift_attr(1)))
+@interface J
+@end



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 3df3b62 - [clang] ns_error_domain attribute also supports CFString typed variables

2020-11-11 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-11-11T08:50:30-08:00
New Revision: 3df3b62018c0015b0786b124827c276e8ee57117

URL: 
https://github.com/llvm/llvm-project/commit/3df3b62018c0015b0786b124827c276e8ee57117
DIFF: 
https://github.com/llvm/llvm-project/commit/3df3b62018c0015b0786b124827c276e8ee57117.diff

LOG: [clang] ns_error_domain attribute also supports CFString typed variables

Differential Revision: https://reviews.llvm.org/D90891

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/Sema/ns_error_enum.m

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index a2f7b7a5bc1f..085d2bac1dea 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -3594,9 +3594,10 @@ def NSErrorDomainDocs : Documentation {
 In Cocoa frameworks in Objective-C, one can group related error codes in enums
 and categorize these enums with error domains.
 
-The ``ns_error_domain`` attribute indicates a global ``NSString`` constant
-representing the error domain that an error code belongs to. For pointer
-uniqueness and code size this is a constant symbol, not a literal.
+The ``ns_error_domain`` attribute indicates a global ``NSString`` or
+``CFString`` constant representing the error domain that an error code belongs
+to. For pointer uniqueness and code size this is a constant symbol, not a
+literal.
 
 The domain and error code need to be used together. The ``ns_error_domain``
 attribute links error codes to their domain at the source level.

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 63475811b117..554d5943a63a 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9597,7 +9597,7 @@ def err_nsreturns_retained_attribute_mismatch : Error<
 def err_nserrordomain_invalid_decl : Error<
   "domain argument %select{|%1 }0does not refer to global constant">;
 def err_nserrordomain_wrong_type : Error<
-  "domain argument %0 does not point to an NSString constant">;
+  "domain argument %0 does not point to an NSString or CFString constant">;
 
 def warn_nsconsumed_attribute_mismatch : Warning<
   err_nsconsumed_attribute_mismatch.Text>, InGroup;

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index ec3ea9ebd85e..a2df339151fb 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -5436,7 +5436,8 @@ static void handleNSErrorDomain(Sema , Decl *D, const 
ParsedAttr ) {
 return;
   }
 
-  if (!isNSStringType(VD->getType(), S.Context)) {
+  if (!isNSStringType(VD->getType(), S.Context) &&
+  !isCFStringType(VD->getType(), S.Context)) {
 S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD;
 return;
   }

diff  --git a/clang/test/Sema/ns_error_enum.m b/clang/test/Sema/ns_error_enum.m
index c8323d903d15..895f9b8b3356 100644
--- a/clang/test/Sema/ns_error_enum.m
+++ b/clang/test/Sema/ns_error_enum.m
@@ -36,9 +36,24 @@ typedef NS_ERROR_ENUM(unsigned char, MyTypedefErrorEnum, 
MyTypedefErrorDomain) {
   MyTypedefErrSecond,
 };
 
+typedef const struct __CFString * CFStringRef;
+
+extern CFStringRef const MyCFErrorDomain;
+typedef NS_ERROR_ENUM(unsigned char, MyCFErrorEnum, MyCFErrorDomain) {
+  MyCFErrFirst,
+  MyCFErrSecond,
+};
+
+typedef CFStringRef CFErrorDomain;
+extern CFErrorDomain const MyCFTypedefErrorDomain;
+typedef NS_ERROR_ENUM(unsigned char, MyCFTypedefErrorEnum, 
MyCFTypedefErrorDomain) {
+  MyCFTypedefErrFirst,
+  MyCFTypedefErrSecond,
+};
+
 extern char *const WrongErrorDomainType;
 enum __attribute__((ns_error_domain(WrongErrorDomainType))) 
MyWrongErrorDomainType { MyWrongErrorDomain };
-// expected-error@-1{{domain argument 'WrongErrorDomainType' does not point to 
an NSString constant}}
+// expected-error@-1{{domain argument 'WrongErrorDomainType' does not point to 
an NSString or CFString constant}}
 
 struct __attribute__((ns_error_domain(MyErrorDomain))) MyStructWithErrorDomain 
{};
 // expected-error@-1{{'ns_error_domain' attribute only applies to enums}}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 701456b - [darwin] add support for __isPlatformVersionAtLeast check for if (@available)

2020-11-02 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-11-02T16:28:09-08:00
New Revision: 701456b52355c25089e1b536805164570f5def6f

URL: 
https://github.com/llvm/llvm-project/commit/701456b52355c25089e1b536805164570f5def6f
DIFF: 
https://github.com/llvm/llvm-project/commit/701456b52355c25089e1b536805164570f5def6f.diff

LOG: [darwin] add support for __isPlatformVersionAtLeast check for if 
(@available)

The __isPlatformVersionAtLeast routine is an implementation of `if 
(@available)` check
that uses the _availability_version_check API on Darwin that's supported on
macOS 10.15, iOS 13, tvOS 13 and watchOS 6.

Differential Revision: https://reviews.llvm.org/D90367

Added: 
compiler-rt/test/builtins/TestCases/Darwin/platform_version_check_test.c

Modified: 
clang/lib/CodeGen/CGExprScalar.cpp
clang/lib/CodeGen/CGObjC.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/CodeGen/CodeGenModule.h
clang/test/CodeGenObjC/availability-cf-link-guard.m
clang/test/CodeGenObjC/availability-check.m
compiler-rt/lib/builtins/os_version_check.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index f14f862a5f67..ab2bb2de1439 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -529,14 +529,7 @@ class ScalarExprEmitter
 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
   return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
 
-Optional Min = Version.getMinor(), SMin = Version.getSubminor();
-llvm::Value *Args[] = {
-llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
-llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
-llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
-};
-
-return CGF.EmitBuiltinAvailable(Args);
+return CGF.EmitBuiltinAvailable(Version);
   }
 
   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);

diff  --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp
index a64712898b70..89bf402c19f8 100644
--- a/clang/lib/CodeGen/CGObjC.cpp
+++ b/clang/lib/CodeGen/CGObjC.cpp
@@ -23,6 +23,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/BinaryFormat/MachO.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/InlineAsm.h"
 using namespace clang;
@@ -3814,9 +3815,61 @@ CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value 
*Block, QualType Ty) {
   return Val;
 }
 
+static unsigned getBaseMachOPlatformID(const llvm::Triple ) {
+  switch (TT.getOS()) {
+  case llvm::Triple::Darwin:
+  case llvm::Triple::MacOSX:
+return llvm::MachO::PLATFORM_MACOS;
+  case llvm::Triple::IOS:
+return llvm::MachO::PLATFORM_IOS;
+  case llvm::Triple::TvOS:
+return llvm::MachO::PLATFORM_TVOS;
+  case llvm::Triple::WatchOS:
+return llvm::MachO::PLATFORM_WATCHOS;
+  default:
+return /*Unknown platform*/ 0;
+  }
+}
+
+static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction ,
+ const VersionTuple ) {
+  CodeGenModule  = CGF.CGM;
+  // Note: we intend to support multi-platform version checks, so reserve
+  // the room for a dual platform checking invocation that will be
+  // implemented in the future.
+  llvm::SmallVector Args;
+
+  auto EmitArgs = [&](const VersionTuple , const llvm::Triple ) {
+Optional Min = Version.getMinor(), SMin = Version.getSubminor();
+Args.push_back(
+llvm::ConstantInt::get(CGM.Int32Ty, getBaseMachOPlatformID(TT)));
+Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()));
+Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Min ? *Min : 0));
+Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin ? *SMin : 0));
+  };
+
+  assert(!Version.empty() && "unexpected empty version");
+  EmitArgs(Version, CGM.getTarget().getTriple());
+
+  if (!CGM.IsPlatformVersionAtLeastFn) {
+llvm::FunctionType *FTy = llvm::FunctionType::get(
+CGM.Int32Ty, {CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty},
+false);
+CGM.IsPlatformVersionAtLeastFn =
+CGM.CreateRuntimeFunction(FTy, "__isPlatformVersionAtLeast");
+  }
+
+  llvm::Value *Check =
+  CGF.EmitNounwindRuntimeCall(CGM.IsPlatformVersionAtLeastFn, Args);
+  return CGF.Builder.CreateICmpNE(Check,
+  llvm::Constant::getNullValue(CGM.Int32Ty));
+}
+
 llvm::Value *
-CodeGenFunction::EmitBuiltinAvailable(ArrayRef Args) {
-  assert(Args.size() == 3 && "Expected 3 argument here!");
+CodeGenFunction::EmitBuiltinAvailable(const VersionTuple ) {
+  // Darwin uses the new __isPlatformVersionAtLeast family of routines.
+  if (CGM.getTarget().getTriple().isOSDarwin())
+return emitIsPlatformVersionAtLeast(*this, Version);
 
   if (!CGM.IsOSVersionAtLeastFn) {
 llvm::FunctionType *FTy =
@@ -3825,18 +3878,51 @@ 

[clang] de1016c - [driver][arm64] Set target CPU to A12 for compiler invocations that

2020-10-22 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-10-21T23:35:27-07:00
New Revision: de1016ce5cdca2df51c00fbc5d3a750d5d72364a

URL: 
https://github.com/llvm/llvm-project/commit/de1016ce5cdca2df51c00fbc5d3a750d5d72364a
DIFF: 
https://github.com/llvm/llvm-project/commit/de1016ce5cdca2df51c00fbc5d3a750d5d72364a.diff

LOG: [driver][arm64] Set target CPU to A12 for compiler invocations that
target Apple Silicon macOS machines

Differential Revision: https://reviews.llvm.org/D82699

Added: 
clang/test/Driver/aarch64-mac-cpus.c

Modified: 
clang/lib/Driver/ToolChains/Arch/AArch64.cpp
clang/test/Preprocessor/aarch64-target-features.c
llvm/include/llvm/ADT/Triple.h

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp 
b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
index fe742b4bcfcd..06bb705a3721 100644
--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -43,6 +43,12 @@ std::string aarch64::getAArch64TargetCPU(const ArgList ,
   else if (CPU.size())
 return CPU;
 
+  if (Triple.isTargetMachineMac() &&
+  Triple.getArch() == llvm::Triple::aarch64) {
+// Apple Silicon macs default to A12 CPUs.
+return "apple-a12";
+  }
+
   // Make sure we pick the appropriate Apple CPU if -arch is used or when
   // targetting a Darwin OS.
   if (Args.getLastArg(options::OPT_arch) || Triple.isOSDarwin())

diff  --git a/clang/test/Driver/aarch64-mac-cpus.c 
b/clang/test/Driver/aarch64-mac-cpus.c
new file mode 100644
index ..437c38376545
--- /dev/null
+++ b/clang/test/Driver/aarch64-mac-cpus.c
@@ -0,0 +1,20 @@
+// arm64 Mac-based targets default to Apple A12.
+
+// RUN: %clang -target arm64-apple-macos -### -c %s 2>&1 | 
FileCheck %s
+// RUN: %clang -target arm64-apple-ios-macabi-### -c %s 2>&1 | 
FileCheck %s
+// RUN: %clang -target arm64-apple-ios-simulator -### -c %s 2>&1 | 
FileCheck %s
+// RUN: %clang -target arm64-apple-watchos-simulator -### -c %s 2>&1 | 
FileCheck %s
+// RUN: %clang -target arm64-apple-tvos-simulator-### -c %s 2>&1 | 
FileCheck %s
+
+// RUN: %clang -target arm64-apple-macos -arch arm64 -### -c %s 2>&1 | 
FileCheck %s
+
+// RUN: %clang -target arm64-apple-macos -mcpu=apple-a11 -### -c %s 2>&1 | 
FileCheck --check-prefix=EXPLICIT-A11 %s
+// RUN: %clang -target arm64-apple-macos -mcpu=apple-a7  -### -c %s 2>&1 | 
FileCheck --check-prefix=EXPLICIT-A7 %s
+// RUN: %clang -target arm64-apple-macos -mcpu=apple-a13 -### -c %s 2>&1 | 
FileCheck --check-prefix=EXPLICIT-A13 %s
+
+// CHECK: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "apple-a12"
+// CHECK-SAME: "-target-feature" "+v8.3a"
+
+// EXPLICIT-A11: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "apple-a11"
+// EXPLICIT-A7: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "apple-a7"
+// EXPLICIT-A13: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "apple-a13"

diff  --git a/clang/test/Preprocessor/aarch64-target-features.c 
b/clang/test/Preprocessor/aarch64-target-features.c
index ad84ba93ccf3..0529a3a3d534 100644
--- a/clang/test/Preprocessor/aarch64-target-features.c
+++ b/clang/test/Preprocessor/aarch64-target-features.c
@@ -247,7 +247,7 @@
 // CHECK-MCPU-CARMEL: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" 
"+v8.2a" "-target-feature" "+fp-armv8" "-target-feature" "+neon" 
"-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" 
"+fullfp16" "-target-feature" "+ras" "-target-feature" "+lse" "-target-feature" 
"+rdm" "-target-feature" "+sha2" "-target-feature" "+aes"
 
 // RUN: %clang -target x86_64-apple-macosx -arch arm64 -### -c %s 2>&1 | 
FileCheck --check-prefix=CHECK-ARCH-ARM64 %s
-// CHECK-ARCH-ARM64: "-target-cpu" "apple-a7" "-target-feature" "+fp-armv8" 
"-target-feature" "+neon" "-target-feature" "+crypto" "-target-feature" "+zcm" 
"-target-feature" "+zcz"
+// CHECK-ARCH-ARM64: "-target-cpu" "apple-a12" "-target-feature" "+v8.3a" 
"-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" 
"+crc" "-target-feature" "+crypto" "-target-feature" "+fullfp16" 
"-target-feature" "+ras" "-target-feature" "+lse" "-target-feature" "+rdm" 
"-target-feature" "+rcpc" "-target-feature" "+zcm" "-target-feature" "+zcz"
 
 // RUN: %clang -target x86_64-apple-macosx -arch arm64_32 -### -c %s 2>&1 | 
FileCheck --check-prefix=CHECK-ARCH-ARM64_32 %s
 // CHECK-ARCH-ARM64_32: "-target-cpu" "apple-s4" "-target-feature" "+v8.3a" 
"-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" 
"+crc" "-target-feature" "+crypto" "-target-feature" "+fullfp16" 
"-target-feature" "+ras" "-target-feature" "+lse" "-target-feature" "+rdm" 
"-target-feature" "+rcpc" "-target-feature" "+zcm" "-target-feature" "+zcz" 
"-target-feature" "+sha2" "-target-feature" "+aes"

diff  --git a/llvm/include/llvm/ADT/Triple.h b/llvm/include/llvm/ADT/Triple.h
index 57b283c3c84a..2d1d43d3c66e 100644
--- 

[clang] 1192747 - NFC, add a missing stdlib include for the use of abort

2020-09-29 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-09-29T08:50:51-07:00
New Revision: 119274748bce6d1248aa57cb55d79bfeae8a2f8e

URL: 
https://github.com/llvm/llvm-project/commit/119274748bce6d1248aa57cb55d79bfeae8a2f8e
DIFF: 
https://github.com/llvm/llvm-project/commit/119274748bce6d1248aa57cb55d79bfeae8a2f8e.diff

LOG: NFC, add a missing stdlib include for the use of abort

The FatalErrorHandler.cpp file uses 'abort', but doesn't include
'stdlib.h'. This causes a build error when modules are used in clang.

Added: 


Modified: 
clang/tools/libclang/FatalErrorHandler.cpp

Removed: 




diff  --git a/clang/tools/libclang/FatalErrorHandler.cpp 
b/clang/tools/libclang/FatalErrorHandler.cpp
index 6b435fcfcc95..ef21569637f0 100644
--- a/clang/tools/libclang/FatalErrorHandler.cpp
+++ b/clang/tools/libclang/FatalErrorHandler.cpp
@@ -9,6 +9,7 @@
 
 #include "clang-c/FatalErrorHandler.h"
 #include "llvm/Support/ErrorHandling.h"
+#include 
 
 static void aborting_fatal_error_handler(void *, const std::string ,
  bool) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c2807b2 - [darwin][driver] fix isMacosxVersionLT minimum supported OS version check

2020-08-13 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-08-13T12:06:45-07:00
New Revision: c2807b2e56c05080354818c221ed4a35abd8a5c8

URL: 
https://github.com/llvm/llvm-project/commit/c2807b2e56c05080354818c221ed4a35abd8a5c8
DIFF: 
https://github.com/llvm/llvm-project/commit/c2807b2e56c05080354818c221ed4a35abd8a5c8.diff

LOG: [darwin][driver] fix isMacosxVersionLT minimum supported OS version check

The previous Driver's triple check only worked for -target, but not for -arch 
-mmacosx-version-min invocations

Added: 
clang/test/Driver/macos-apple-silicon-slice-link-libs-darwin-only.cpp

Modified: 
clang/lib/Driver/ToolChains/Darwin.h
clang/test/Driver/macos-apple-silicon-slice-link-libs.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.h 
b/clang/lib/Driver/ToolChains/Darwin.h
index 64c252efea7d..e67b2c5c87cd 100644
--- a/clang/lib/Driver/ToolChains/Darwin.h
+++ b/clang/lib/Driver/ToolChains/Darwin.h
@@ -436,7 +436,11 @@ class LLVM_LIBRARY_VISIBILITY Darwin : public MachO {
   bool isMacosxVersionLT(unsigned V0, unsigned V1 = 0, unsigned V2 = 0) const {
 assert(isTargetMacOS() && getTriple().isMacOSX() &&
"Unexpected call for non OS X target!");
-VersionTuple MinVers = getTriple().getMinimumSupportedOSVersion();
+// The effective triple might not be initialized yet, so construct a
+// pseudo-effective triple to get the minimum supported OS version.
+VersionTuple MinVers =
+llvm::Triple(getTriple().getArchName(), "apple", "macos")
+.getMinimumSupportedOSVersion();
 return (!MinVers.empty() && MinVers > TargetVersion
 ? MinVers
 : TargetVersion) < VersionTuple(V0, V1, V2);

diff  --git 
a/clang/test/Driver/macos-apple-silicon-slice-link-libs-darwin-only.cpp 
b/clang/test/Driver/macos-apple-silicon-slice-link-libs-darwin-only.cpp
new file mode 100644
index ..ec3b710c4da8
--- /dev/null
+++ b/clang/test/Driver/macos-apple-silicon-slice-link-libs-darwin-only.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang -### -arch arm64 -mmacosx-version-min=10.7 %s 2>&1 | FileCheck 
-check-prefix=ARM64-10_7 %s
+// RUN: %clang -### -arch x86_64 -mmacosx-version-min=10.7 %s 2>&1 | FileCheck 
-check-prefix=x86_64-10_7 %s
+// REQUIRES: system-darwin
+
+// ARM64-10_7-NOT: -lcrt1.10.6.o
+// x86_64-10_7:-lcrt1.10.6.o

diff  --git a/clang/test/Driver/macos-apple-silicon-slice-link-libs.cpp 
b/clang/test/Driver/macos-apple-silicon-slice-link-libs.cpp
index 522fda34987e..4a2a029c736f 100644
--- a/clang/test/Driver/macos-apple-silicon-slice-link-libs.cpp
+++ b/clang/test/Driver/macos-apple-silicon-slice-link-libs.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang -### -target arm64-apple-macos10.7 %s 2>&1 | FileCheck 
-check-prefix=ARM64-10_7 %s
 // RUN: %clang -### -target x86_64-apple-macos10.7 %s 2>&1 | FileCheck 
-check-prefix=x86_64-10_7 %s
+// RUN: %clang -### -target arm64-apple-darwin6 %s 2>&1 | FileCheck 
-check-prefix=ARM64-10_7 %s
 
 // RUN: %clang -### -target arm64-apple-macos10.5 %s 2>&1 | FileCheck 
-check-prefix=ARM64-10_5 %s
 // RUN: %clang -### -target x86_64-apple-macos10.5 %s 2>&1 | FileCheck 
-check-prefix=x86_64-10_5 %s



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] dc22182 - [darwin] build and link with a separate compiler-rt builtins library

2020-07-29 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-07-29T15:32:30-07:00
New Revision: dc22182d1f7489239388f7bdd04170573c0652a3

URL: 
https://github.com/llvm/llvm-project/commit/dc22182d1f7489239388f7bdd04170573c0652a3
DIFF: 
https://github.com/llvm/llvm-project/commit/dc22182d1f7489239388f7bdd04170573c0652a3.diff

LOG: [darwin] build and link with a separate compiler-rt builtins library
for device simulators

This change separates out the iOS/tvOS/watchOS simulator slices from the 
"libclang_rt..a"
fat archive, by moving them out to their own "libclang_rt.sim.a" static 
archive.
This allows us to build and to link with an arm64 device simulator slice for 
the simulators running
on Apple Silicons, and to distribute it in one archive alongside the Intel 
simulator slices.

Differential Revision: https://reviews.llvm.org/D84564

Added: 
clang/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.iossim.a

Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/darwin-ld.c
compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 325dcb7df545..cf8a3e6aee27 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1062,10 +1062,9 @@ void MachO::AddLinkRuntimeLib(const ArgList , 
ArgStringList ,
 DarwinLibName += Component;
 if (!(Opts & RLO_IsEmbedded))
   DarwinLibName += "_";
-DarwinLibName += getOSLibraryNameSuffix();
-  } else
-DarwinLibName += getOSLibraryNameSuffix(true);
+  }
 
+  DarwinLibName += getOSLibraryNameSuffix();
   DarwinLibName += IsShared ? "_dynamic.dylib" : ".a";
   SmallString<128> Dir(getDriver().ResourceDir);
   llvm::sys::path::append(

diff  --git 
a/clang/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.iossim.a 
b/clang/test/Driver/Inputs/resource_dir/lib/darwin/libclang_rt.iossim.a
new file mode 100644
index ..e69de29bb2d1

diff  --git a/clang/test/Driver/darwin-ld.c b/clang/test/Driver/darwin-ld.c
index ea71142e88c1..82cd36d59f80 100644
--- a/clang/test/Driver/darwin-ld.c
+++ b/clang/test/Driver/darwin-ld.c
@@ -156,7 +156,7 @@
 // RUN: FileCheck -check-prefix=LINK_IOSSIM_PROFILE %s < %t.log
 // LINK_IOSSIM_PROFILE: {{ld(.exe)?"}}
 // LINK_IOSSIM_PROFILE: libclang_rt.profile_iossim.a
-// LINK_IOSSIM_PROFILE: libclang_rt.ios.a
+// LINK_IOSSIM_PROFILE: libclang_rt.iossim.a
 
 // RUN: %clang -target arm64-apple-tvos8.3 -mlinker-version=400 
-mtvos-version-min=8.3 -resource-dir=%S/Inputs/resource_dir -### %t.o 2> %t.log
 // RUN: FileCheck -check-prefix=LINK_TVOS_ARM64 %s < %t.log

diff  --git a/compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake 
b/compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake
index be8d7e733c7a..c37b5e98bcc6 100644
--- a/compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake
+++ b/compiler-rt/cmake/Modules/CompilerRTDarwinUtils.cmake
@@ -289,6 +289,15 @@ macro(darwin_add_builtin_library name suffix)
 endforeach(cflag)
   endif()
 
+  if ("${LIB_OS}" MATCHES ".*sim$")
+# Pass an explicit -simulator environment to the -target option to ensure
+# that we don't rely on the architecture to infer whether we're building
+# for the simulator.
+string(REGEX REPLACE "sim" "" base_os "${LIB_OS}")
+list(APPEND builtin_cflags
+ -target 
"${LIB_ARCH}-apple-${base_os}${DARWIN_${LIBOS}_BUILTIN_MIN_VER}-simulator")
+  endif()
+
   set_target_compile_flags(${libname}
 ${sysroot_flag}
 ${DARWIN_${LIB_OS}_BUILTIN_MIN_VER_FLAG}
@@ -449,16 +458,13 @@ macro(darwin_add_builtin_libraries)
 endif()
   endforeach()
 
-  # We put the x86 sim slices into the archives for their base OS
   foreach (os ${ARGN})
-if(NOT ${os} MATCHES ".*sim$")
-  darwin_lipo_libs(clang_rt.${os}
-PARENT_TARGET builtins
-LIPO_FLAGS ${${os}_builtins_lipo_flags} 
${${os}sim_builtins_lipo_flags}
-DEPENDS ${${os}_builtins_libs} 
${${os}sim_builtins_libs}
-OUTPUT_DIR ${COMPILER_RT_LIBRARY_OUTPUT_DIR}
-INSTALL_DIR ${COMPILER_RT_LIBRARY_INSTALL_DIR})
-endif()
+darwin_lipo_libs(clang_rt.${os}
+ PARENT_TARGET builtins
+ LIPO_FLAGS ${${os}_builtins_lipo_flags}
+ DEPENDS ${${os}_builtins_libs}
+ OUTPUT_DIR ${COMPILER_RT_LIBRARY_OUTPUT_DIR}
+ INSTALL_DIR ${COMPILER_RT_LIBRARY_INSTALL_DIR})
   endforeach()
   darwin_add_embedded_builtin_libraries()
 endmacro()



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bb162df - [clang] attempt to fix a linux test failure for the darwin-ld-platform-version-macos.c test

2020-06-29 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-06-29T20:13:41-07:00
New Revision: bb162dfe252a1abc15af411d8ba51dda63af306c

URL: 
https://github.com/llvm/llvm-project/commit/bb162dfe252a1abc15af411d8ba51dda63af306c
DIFF: 
https://github.com/llvm/llvm-project/commit/bb162dfe252a1abc15af411d8ba51dda63af306c.diff

LOG: [clang] attempt to fix a linux test failure for the 
darwin-ld-platform-version-macos.c test

Clang should use explicit -target to ensure that the Darwin driver is used.
Also drop arm64e test-case for now.

Added: 


Modified: 
clang/test/Driver/darwin-ld-platform-version-macos.c

Removed: 




diff  --git a/clang/test/Driver/darwin-ld-platform-version-macos.c 
b/clang/test/Driver/darwin-ld-platform-version-macos.c
index 5c7af058e462..d3f49093ef86 100644
--- a/clang/test/Driver/darwin-ld-platform-version-macos.c
+++ b/clang/test/Driver/darwin-ld-platform-version-macos.c
@@ -13,14 +13,8 @@
 // RUN:   | FileCheck --check-prefix=ARM64_NEW %s
 // RUN: %clang -target arm64-apple-macos11.1 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=ARM64_NEW_1 %s
-// RUN: %clang -arch arm64 -mmacosx-version-min=10.15 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=520 -### %t.o 2>&1 \
-// RUN:   | FileCheck --check-prefix=ARM64_NEW %s
 // RUN: %clang -target arm64-apple-macos10.13 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=400 -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=ARM64_OLD %s
-// RUN: %clang -arch arm64 -mmacosx-version-min=10.15 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=400 -### %t.o 2>&1 \
-// RUN:   | FileCheck --check-prefix=ARM64_OLD %s
-// RUN: %clang -target arm64e-apple-macos10.13 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=520 -### %t.o 2>&1 \
-// RUN:   | FileCheck --check-prefix=ARM64_NEW %s
 
 // LINKER-OLD: "-macosx_version_min" "10.13.0"
 // LINKER-NEW: "-platform_version" "macos" "10.13.0" "10.14"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 6792a60 - [darwin][driver] pass the minimum supported OS version to the linker

2020-06-29 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-06-29T19:03:57-07:00
New Revision: 6792a6077889f1ce77a3aa55b3e4fd3f1eb4333b

URL: 
https://github.com/llvm/llvm-project/commit/6792a6077889f1ce77a3aa55b3e4fd3f1eb4333b
DIFF: 
https://github.com/llvm/llvm-project/commit/6792a6077889f1ce77a3aa55b3e4fd3f1eb4333b.diff

LOG: [darwin][driver] pass the minimum supported OS version to the linker
if it's newer than the target version

This change ensures that the arm64-apple-macOS slice is linked for
macOS 11 even if the deployment target is earlier than macOS 11.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/darwin-ld-platform-version-macos.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 4b98fd09b4b0..ad3b3a955d42 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2546,6 +2546,9 @@ void Darwin::addMinVersionArgs(const ArgList ,
 CmdArgs.push_back("-macosx_version_min");
   }
 
+  VersionTuple MinTgtVers = 
getEffectiveTriple().getMinimumSupportedOSVersion();
+  if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
+TargetVersion = MinTgtVers;
   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
 }
 
@@ -2578,6 +2581,9 @@ void Darwin::addPlatformVersionArgs(const 
llvm::opt::ArgList ,
 PlatformName += "-simulator";
   CmdArgs.push_back(Args.MakeArgString(PlatformName));
   VersionTuple TargetVersion = getTargetVersion().withoutBuild();
+  VersionTuple MinTgtVers = 
getEffectiveTriple().getMinimumSupportedOSVersion();
+  if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
+TargetVersion = MinTgtVers;
   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
   if (SDKInfo) {
 VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();

diff  --git a/clang/test/Driver/darwin-ld-platform-version-macos.c 
b/clang/test/Driver/darwin-ld-platform-version-macos.c
index c1b940a3f35f..5c7af058e462 100644
--- a/clang/test/Driver/darwin-ld-platform-version-macos.c
+++ b/clang/test/Driver/darwin-ld-platform-version-macos.c
@@ -7,9 +7,28 @@
 // RUN: env SDKROOT=%S/Inputs/MacOSX10.14.sdk %clang -target 
x86_64-apple-macos10.13.0.1 -mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=LINKER-NEW %s
 
+// RUN: %clang -target arm64-apple-macos10.13 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=520 -### %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=ARM64_NEW %s
+// RUN: %clang -target arm64-apple-darwin19 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=520 -### %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=ARM64_NEW %s
+// RUN: %clang -target arm64-apple-macos11.1 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=520 -### %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=ARM64_NEW_1 %s
+// RUN: %clang -arch arm64 -mmacosx-version-min=10.15 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=520 -### %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=ARM64_NEW %s
+// RUN: %clang -target arm64-apple-macos10.13 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=400 -### %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=ARM64_OLD %s
+// RUN: %clang -arch arm64 -mmacosx-version-min=10.15 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=400 -### %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=ARM64_OLD %s
+// RUN: %clang -target arm64e-apple-macos10.13 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=520 -### %t.o 2>&1 \
+// RUN:   | FileCheck --check-prefix=ARM64_NEW %s
+
 // LINKER-OLD: "-macosx_version_min" "10.13.0"
 // LINKER-NEW: "-platform_version" "macos" "10.13.0" "10.14"
 
+// ARM64_NEW: "-platform_version" "macos" "11.0.0" "10.14"
+// ARM64_NEW_1: "-platform_version" "macos" "11.1.0" "10.14"
+// ARM64_OLD: "-macosx_version_min" "11.0.0"
+
 // RUN: %clang -target x86_64-apple-macos10.13  -mlinker-version=520 -### %t.o 
2>&1 \
 // RUN:   | FileCheck --check-prefix=NOSDK %s
 // NOSDK: "-platform_version" "macos" "10.13.0" "0.0.0"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f7a1451 - [darwin][driver] isMacosxVersionLT should check against the minimum supported OS version

2020-06-29 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-06-29T12:21:54-07:00
New Revision: f7a14514ee63dc2ab9558c50254efb8ac2ad7cc6

URL: 
https://github.com/llvm/llvm-project/commit/f7a14514ee63dc2ab9558c50254efb8ac2ad7cc6
DIFF: 
https://github.com/llvm/llvm-project/commit/f7a14514ee63dc2ab9558c50254efb8ac2ad7cc6.diff

LOG: [darwin][driver] isMacosxVersionLT should check against the minimum 
supported OS version

This change ensures that the Darwin driver doesn't add unsupported libraries to 
the link
invocation when linking the Apple Silicon macOS slice.

rdar://61011136

Differential Revision: https://reviews.llvm.org/D82696

Added: 
clang/test/Driver/macos-apple-silicon-slice-link-libs.cpp

Modified: 
clang/lib/Driver/ToolChains/Darwin.h
llvm/include/llvm/ADT/Triple.h
llvm/lib/Support/Triple.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.h 
b/clang/lib/Driver/ToolChains/Darwin.h
index 438455996ccb..04c5bfa69a5a 100644
--- a/clang/lib/Driver/ToolChains/Darwin.h
+++ b/clang/lib/Driver/ToolChains/Darwin.h
@@ -434,9 +434,17 @@ class LLVM_LIBRARY_VISIBILITY Darwin : public MachO {
 return TargetVersion < VersionTuple(V0, V1, V2);
   }
 
+  /// Returns true if the minimum supported macOS version for the slice that's
+  /// being built is less than the specified version. If there's no minimum
+  /// supported macOS version, the deployment target version is compared to the
+  /// specifed version instead.
   bool isMacosxVersionLT(unsigned V0, unsigned V1 = 0, unsigned V2 = 0) const {
-assert(isTargetMacOS() && "Unexpected call for non OS X target!");
-return TargetVersion < VersionTuple(V0, V1, V2);
+assert(isTargetMacOS() && getTriple().isMacOSX() &&
+   "Unexpected call for non OS X target!");
+VersionTuple MinVers = getTriple().getMinimumSupportedOSVersion();
+return (!MinVers.empty() && MinVers > TargetVersion
+? MinVers
+: TargetVersion) < VersionTuple(V0, V1, V2);
   }
 
 protected:

diff  --git a/clang/test/Driver/macos-apple-silicon-slice-link-libs.cpp 
b/clang/test/Driver/macos-apple-silicon-slice-link-libs.cpp
new file mode 100644
index ..522fda34987e
--- /dev/null
+++ b/clang/test/Driver/macos-apple-silicon-slice-link-libs.cpp
@@ -0,0 +1,42 @@
+// RUN: %clang -### -target arm64-apple-macos10.7 %s 2>&1 | FileCheck 
-check-prefix=ARM64-10_7 %s
+// RUN: %clang -### -target x86_64-apple-macos10.7 %s 2>&1 | FileCheck 
-check-prefix=x86_64-10_7 %s
+
+// RUN: %clang -### -target arm64-apple-macos10.5 %s 2>&1 | FileCheck 
-check-prefix=ARM64-10_5 %s
+// RUN: %clang -### -target x86_64-apple-macos10.5 %s 2>&1 | FileCheck 
-check-prefix=x86_64-10_5 %s
+
+// RUN: %clang -### -target arm64-apple-macos10.4 %s 2>&1 | FileCheck 
-check-prefix=ARM64-10_4 %s
+// RUN: %clang -### -target x86_64-apple-macos10.4 %s 2>&1 | FileCheck 
-check-prefix=x86_64-10_4 %s
+
+// RUN: %clang -### -target arm64-apple-macos10.5 -bundle %s 2>&1 | FileCheck 
-check-prefix=ARM64-BUNDLE %s
+// RUN: %clang -### -target x86_64-apple-macos10.5 -bundle %s 2>&1 | FileCheck 
-check-prefix=x86_64-BUNDLE %s
+
+// RUN: %clang -### -target arm64-apple-macos10.5 -dynamiclib %s 2>&1 | 
FileCheck -check-prefix=ARM64-10_5-DYNAMICLIB %s
+// RUN: %clang -### -target x86_64-apple-macos10.5 -dynamiclib %s 2>&1 | 
FileCheck -check-prefix=x86_64-10_5-DYNAMICLIB %s
+
+// RUN: %clang -### -target arm64-apple-macos10.4 -dynamiclib %s 2>&1 | 
FileCheck -check-prefix=ARM64-10_4-DYNAMICLIB %s
+// RUN: %clang -### -target arm64-apple-darwin8 -dynamiclib %s 2>&1 | 
FileCheck -check-prefix=ARM64-10_4-DYNAMICLIB %s
+// RUN: %clang -### -target x86_64-apple-macos10.4 -dynamiclib %s 2>&1 | 
FileCheck -check-prefix=x86_64-10_4-DYNAMICLIB %s
+// RUN: %clang -### -target x86_64-apple-darwin8 -dynamiclib %s 2>&1 | 
FileCheck -check-prefix=x86_64-10_4-DYNAMICLIB %s
+
+// RUN: %clang -### -target arm64-apple-macos10.7 -static %s 2>&1 | FileCheck 
-check-prefix=STATIC %s
+// RUN: %clang -### -target x86_64-apple-macos10.7 -static %s 2>&1 | FileCheck 
-check-prefix=STATIC %s
+
+// ARM64-10_7-NOT: -lcrt1.10.6.o
+// x86_64-10_7:-lcrt1.10.6.o
+
+// ARM64-10_5-NOT: -lcrt1.10.5.o
+// x86_64-10_5:-lcrt1.10.5.o
+
+// ARM64-10_4-NOT: -lcrt1.o
+// x86_64-10_4:-lcrt1.o
+
+// ARM64-BUNDLE-NOT: -lbundle1.o
+// x86_64-BUNDLE:-lbundle1.o
+
+// ARM64-10_5-DYNAMICLIB-NOT: -ldylib1.10.5.o
+// x86_64-10_5-DYNAMICLIB:-ldylib1.10.5.o
+
+// ARM64-10_4-DYNAMICLIB-NOT: -ldylib1.o
+// x86_64-10_4-DYNAMICLIB:-ldylib1.o
+
+// STATIC: -lcrt0.o

diff  --git a/llvm/include/llvm/ADT/Triple.h b/llvm/include/llvm/ADT/Triple.h
index 89679619dd55..6bad18f19244 100644
--- a/llvm/include/llvm/ADT/Triple.h
+++ b/llvm/include/llvm/ADT/Triple.h
@@ -860,6 +860,12 @@ class Triple {
   /// Merge target triples.
   std::string merge(const Triple ) const;
 
+  /// Some platforms have 
diff erent minimum supported OS versions 

[clang] 2b00cac - [darwin][driver] NFC, split addStartObjectFileArgs into multiple functions

2020-06-26 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-06-26T17:15:37-07:00
New Revision: 2b00cacb2835d11cab6f71466604b7b1bdd46a8d

URL: 
https://github.com/llvm/llvm-project/commit/2b00cacb2835d11cab6f71466604b7b1bdd46a8d
DIFF: 
https://github.com/llvm/llvm-project/commit/2b00cacb2835d11cab6f71466604b7b1bdd46a8d.diff

LOG: [darwin][driver] NFC, split addStartObjectFileArgs into multiple functions

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 36559483593b..47bf036d24d8 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2574,98 +2574,102 @@ void Darwin::addPlatformVersionArgs(const 
llvm::opt::ArgList ,
   }
 }
 
-void Darwin::addStartObjectFileArgs(const ArgList ,
-ArgStringList ) const {
-  // Derived from startfile spec.
-  if (Args.hasArg(options::OPT_dynamiclib)) {
-// Derived from darwin_dylib1 spec.
-if (isTargetWatchOSBased()) {
-  ; // watchOS does not need dylib1.o.
-} else if (isTargetIOSSimulator()) {
-  ; // iOS simulator does not need dylib1.o.
-} else if (isTargetIPhoneOS()) {
-  if (isIPhoneOSVersionLT(3, 1))
-CmdArgs.push_back("-ldylib1.o");
+// Add additional link args for the -dynamiclib option.
+static void addDynamicLibLinkArgs(const Darwin , const ArgList ,
+  ArgStringList ) {
+  // Derived from darwin_dylib1 spec.
+  if (D.isTargetIPhoneOS()) {
+if (D.isIPhoneOSVersionLT(3, 1))
+  CmdArgs.push_back("-ldylib1.o");
+return;
+  }
+
+  if (!D.isTargetMacOS())
+return;
+  if (D.isMacosxVersionLT(10, 5))
+CmdArgs.push_back("-ldylib1.o");
+  else if (D.isMacosxVersionLT(10, 6))
+CmdArgs.push_back("-ldylib1.10.5.o");
+}
+
+// Add additional link args for the -bundle option.
+static void addBundleLinkArgs(const Darwin , const ArgList ,
+  ArgStringList ) {
+  if (Args.hasArg(options::OPT_static))
+return;
+  // Derived from darwin_bundle1 spec.
+  if ((D.isTargetIPhoneOS() && D.isIPhoneOSVersionLT(3, 1)) ||
+  (D.isTargetMacOS() && D.isMacosxVersionLT(10, 6)))
+CmdArgs.push_back("-lbundle1.o");
+}
+
+// Add additional link args for the -pg option.
+static void addPgProfilingLinkArgs(const Darwin , const ArgList ,
+   ArgStringList ) {
+  if (D.isTargetMacOS() && D.isMacosxVersionLT(10, 9)) {
+if (Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_object) ||
+Args.hasArg(options::OPT_preload)) {
+  CmdArgs.push_back("-lgcrt0.o");
 } else {
-  if (isMacosxVersionLT(10, 5))
-CmdArgs.push_back("-ldylib1.o");
-  else if (isMacosxVersionLT(10, 6))
-CmdArgs.push_back("-ldylib1.10.5.o");
+  CmdArgs.push_back("-lgcrt1.o");
+
+  // darwin_crt2 spec is empty.
 }
+// By default on OS X 10.8 and later, we don't link with a crt1.o
+// file and the linker knows to use _main as the entry point.  But,
+// when compiling with -pg, we need to link with the gcrt1.o file,
+// so pass the -no_new_main option to tell the linker to use the
+// "start" symbol as the entry point.
+if (!D.isMacosxVersionLT(10, 8))
+  CmdArgs.push_back("-no_new_main");
   } else {
-if (Args.hasArg(options::OPT_bundle)) {
-  if (!Args.hasArg(options::OPT_static)) {
-// Derived from darwin_bundle1 spec.
-if (isTargetWatchOSBased()) {
-  ; // watchOS does not need bundle1.o.
-} else if (isTargetIOSSimulator()) {
-  ; // iOS simulator does not need bundle1.o.
-} else if (isTargetIPhoneOS()) {
-  if (isIPhoneOSVersionLT(3, 1))
-CmdArgs.push_back("-lbundle1.o");
-} else {
-  if (isMacosxVersionLT(10, 6))
-CmdArgs.push_back("-lbundle1.o");
-}
-  }
-} else {
-  if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
-if (isTargetMacOS() && isMacosxVersionLT(10, 9)) {
-  if (Args.hasArg(options::OPT_static) ||
-  Args.hasArg(options::OPT_object) ||
-  Args.hasArg(options::OPT_preload)) {
-CmdArgs.push_back("-lgcrt0.o");
-  } else {
-CmdArgs.push_back("-lgcrt1.o");
-
-// darwin_crt2 spec is empty.
-  }
-  // By default on OS X 10.8 and later, we don't link with a crt1.o
-  // file and the linker knows to use _main as the entry point.  But,
-  // when compiling with -pg, we need to link with the gcrt1.o file,
-  // so pass the -no_new_main option to tell the linker to use the
-  // "start" symbol as the entry point.
-  if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
-

[clang] 253988f - [darwin][driver] Do not link with libarclite when building for Apple Silicon macOS

2020-06-26 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-06-26T17:15:37-07:00
New Revision: 253988f0f400201adb094d0f81d2c0c3fac94f4f

URL: 
https://github.com/llvm/llvm-project/commit/253988f0f400201adb094d0f81d2c0c3fac94f4f
DIFF: 
https://github.com/llvm/llvm-project/commit/253988f0f400201adb094d0f81d2c0c3fac94f4f.diff

LOG: [darwin][driver] Do not link with libarclite when building for Apple 
Silicon macOS

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h
clang/test/Driver/arclite-link.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 1b3a3e934995..36559483593b 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -971,6 +971,8 @@ void DarwinClang::AddLinkARCArgs(const ArgList ,
   // Avoid linking compatibility stubs on i386 mac.
   if (isTargetMacOS() && getArch() == llvm::Triple::x86)
 return;
+  if (isTargetAppleSiliconMac())
+return;
 
   ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
 

diff  --git a/clang/lib/Driver/ToolChains/Darwin.h 
b/clang/lib/Driver/ToolChains/Darwin.h
index 1b193a4c4eb9..e6f2beb94a2e 100644
--- a/clang/lib/Driver/ToolChains/Darwin.h
+++ b/clang/lib/Driver/ToolChains/Darwin.h
@@ -409,6 +409,17 @@ class LLVM_LIBRARY_VISIBILITY Darwin : public MachO {
 return TargetPlatform == MacOS;
   }
 
+  bool isTargetMacOSBased() const {
+assert(TargetInitialized && "Target not initialized!");
+// FIXME (Alex L): Add remaining MacCatalyst suppport.
+return TargetPlatform == MacOS;
+  }
+
+  bool isTargetAppleSiliconMac() const {
+assert(TargetInitialized && "Target not initialized!");
+return isTargetMacOSBased() && getArch() == llvm::Triple::aarch64;
+  }
+
   bool isTargetInitialized() const { return TargetInitialized; }
 
   VersionTuple getTargetVersion() const {

diff  --git a/clang/test/Driver/arclite-link.c 
b/clang/test/Driver/arclite-link.c
index 2cc0271fc022..a53b12daa47b 100644
--- a/clang/test/Driver/arclite-link.c
+++ b/clang/test/Driver/arclite-link.c
@@ -15,3 +15,6 @@
 // RUN: %clang -### -target x86_64-apple-darwin10 -fobjc-link-runtime 
-fobjc-arc -mmacosx-version-min=10.10 %s 2>&1 | FileCheck 
-check-prefix=CHECK-UNUSED %s
 
 // CHECK-UNUSED-NOT: warning: argument unused during compilation: 
'-fobjc-link-runtime'
+
+// RUN: %clang -### -target arm64-apple-macos10.8 -fobjc-link-runtime %t.o 
2>&1 | FileCheck -check-prefix=CHECK-ARCLITE-ARM-MAC %s
+// CHECK-ARCLITE-ARM-MAC-NOT: libarclite



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1a342ff - test fix: add missing system-darwin REQUIRES

2020-06-23 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-06-23T21:17:58-07:00
New Revision: 1a342ff3753d0354bab3d82fa8e493e21d50c79f

URL: 
https://github.com/llvm/llvm-project/commit/1a342ff3753d0354bab3d82fa8e493e21d50c79f
DIFF: 
https://github.com/llvm/llvm-project/commit/1a342ff3753d0354bab3d82fa8e493e21d50c79f.diff

LOG: test fix: add missing system-darwin REQUIRES

The test should only run with a Darwin driver only.

Added: 


Modified: 
clang/test/Driver/apple-arm64-arch.c

Removed: 




diff  --git a/clang/test/Driver/apple-arm64-arch.c 
b/clang/test/Driver/apple-arm64-arch.c
index fd9f9a2ccedb..a37346b1a9bb 100644
--- a/clang/test/Driver/apple-arm64-arch.c
+++ b/clang/test/Driver/apple-arm64-arch.c
@@ -1,6 +1,7 @@
 // RUN: env SDKROOT="/" %clang -arch arm64 -c -### %s 2>&1 | \
 // RUN:   FileCheck %s
 //
+// REQUIRES: system-darwin
 // XFAIL: apple-silicon-mac
 //
 // CHECK: "-triple" "arm64-apple-ios{{[0-9.]+}}"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 565603c - [clang][driver] set macOS as the target OS for -arch arm64 when clang

2020-06-23 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-06-23T21:08:11-07:00
New Revision: 565603cc94d79a8d0de6df840fd53714899fb890

URL: 
https://github.com/llvm/llvm-project/commit/565603cc94d79a8d0de6df840fd53714899fb890
DIFF: 
https://github.com/llvm/llvm-project/commit/565603cc94d79a8d0de6df840fd53714899fb890.diff

LOG: [clang][driver] set macOS as the target OS for -arch arm64 when clang
is running on an Apple Silicon mac

This change allows users to use `-arch arm64` to build for mac when
running it on Apple Silicon mac without explicit `-target` option.

Differential Revision: https://reviews.llvm.org/D82428

Added: 
clang/test/Driver/apple-arm64-arch.c
clang/test/Driver/apple-silicon-arch.c

Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/lit.cfg.py

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index bb7c7f768b35..1b3a3e934995 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1672,8 +1672,16 @@ inferDeploymentTargetFromArch(DerivedArgList , 
const Darwin ,
   llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
 
   StringRef MachOArchName = Toolchain.getMachOArchName(Args);
-  if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
-  MachOArchName == "arm64")
+  if (MachOArchName == "arm64") {
+#if __arm64__
+// A clang running on an Apple Silicon mac defaults
+// to building for mac when building for arm64 rather than
+// defaulting to iOS.
+OSTy = llvm::Triple::MacOSX;
+#else
+OSTy = llvm::Triple::IOS;
+#endif
+  } else if (MachOArchName == "armv7" || MachOArchName == "armv7s")
 OSTy = llvm::Triple::IOS;
   else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
 OSTy = llvm::Triple::WatchOS;

diff  --git a/clang/test/Driver/apple-arm64-arch.c 
b/clang/test/Driver/apple-arm64-arch.c
new file mode 100644
index ..fd9f9a2ccedb
--- /dev/null
+++ b/clang/test/Driver/apple-arm64-arch.c
@@ -0,0 +1,6 @@
+// RUN: env SDKROOT="/" %clang -arch arm64 -c -### %s 2>&1 | \
+// RUN:   FileCheck %s
+//
+// XFAIL: apple-silicon-mac
+//
+// CHECK: "-triple" "arm64-apple-ios{{[0-9.]+}}"

diff  --git a/clang/test/Driver/apple-silicon-arch.c 
b/clang/test/Driver/apple-silicon-arch.c
new file mode 100644
index ..b1201fa2d7dd
--- /dev/null
+++ b/clang/test/Driver/apple-silicon-arch.c
@@ -0,0 +1,6 @@
+// RUN: env SDKROOT="/" %clang -arch arm64 -c -### %s 2>&1 | \
+// RUN:   FileCheck %s
+//
+// REQUIRES: apple-silicon-mac
+//
+// CHECK: "-triple" "arm64-apple-macosx{{[0-9.]+}}"

diff  --git a/clang/test/lit.cfg.py b/clang/test/lit.cfg.py
index 413f81175420..ade32988b9a8 100644
--- a/clang/test/lit.cfg.py
+++ b/clang/test/lit.cfg.py
@@ -155,6 +155,10 @@ def is_filesystem_case_insensitive():
 if not re.match(r'.*-(cygwin)$', config.target_triple):
 config.available_features.add('clang-driver')
 
+# Tests that are specific to the Apple Silicon macOS.
+if re.match(r'^arm64(e)?-apple-(macos|darwin)', config.target_triple):
+config.available_features.add('apple-silicon-mac')
+
 # [PR18856] Depends to remove opened file. On win32, a file could be removed
 # only if all handles were closed.
 if platform.system() not in ['Windows']:



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f724ce0 - [clang][driver] allow macOS 11 OS version in the driver

2020-06-23 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-06-23T15:14:26-07:00
New Revision: f724ce0d73eb3f85364e346a036588825bc47567

URL: 
https://github.com/llvm/llvm-project/commit/f724ce0d73eb3f85364e346a036588825bc47567
DIFF: 
https://github.com/llvm/llvm-project/commit/f724ce0d73eb3f85364e346a036588825bc47567.diff

LOG: [clang][driver] allow macOS 11 OS version in the driver

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/darwin-version.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 3bf7f9cbc139..bb7c7f768b35 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1822,7 +1822,7 @@ void Darwin::AddDeploymentTarget(DerivedArgList ) 
const {
   if (Platform == MacOS) {
 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
Micro, HadExtra) ||
-HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
+HadExtra || Major < 10 || Major >= 100 || Minor >= 100 || Micro >= 100)
   getDriver().Diag(diag::err_drv_invalid_version_number)
   << OSTarget->getAsString(Args, Opts);
   } else if (Platform == IPhoneOS) {

diff  --git a/clang/test/Driver/darwin-version.c 
b/clang/test/Driver/darwin-version.c
index 7885b5964626..3471552c937f 100644
--- a/clang/test/Driver/darwin-version.c
+++ b/clang/test/Driver/darwin-version.c
@@ -305,3 +305,13 @@
 // RUN: %clang -target armv7k-apple-ios10.1-simulator -c %s -### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-TENV-SIM2 %s
 // CHECK-VERSION-TENV-SIM2: "thumbv7k-apple-ios10.1.0-simulator"
+
+
+// RUN: %clang -target x86_64-apple-macos11 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-MACOS11 %s
+// RUN: %clang -target x86_64-apple-darwin20 -c %s -### 2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-MACOS11 %s
+// RUN: %clang -target x86_64-apple-darwin -mmacos-version-min=11 -c %s -### 
2>&1 | \
+// RUN:   FileCheck --check-prefix=CHECK-MACOS11 %s
+
+// CHECK-MACOS11: "x86_64-apple-macosx11.0.0"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5eedf07 - [apple clang] disable in-process CC1 to preserve crashlog compatibility

2020-06-05 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-06-05T10:55:42-07:00
New Revision: 5eedf07ab999d0a8ba43f41e0c1012d8f6e62c11

URL: 
https://github.com/llvm/llvm-project/commit/5eedf07ab999d0a8ba43f41e0c1012d8f6e62c11
DIFF: 
https://github.com/llvm/llvm-project/commit/5eedf07ab999d0a8ba43f41e0c1012d8f6e62c11.diff

LOG: [apple clang] disable in-process CC1 to preserve crashlog compatibility

The in-process CC1 currently doesn't interoperate with the macOS crash 
analytics,
which we would like to keep enabled for Apple clang. This commit restores the
out-of-process CC1 to the Apple clang CMake configuration for now.

Differential Revision: https://reviews.llvm.org/D80849

Added: 
clang/test/Driver/apple-clang-defaults.c

Modified: 
clang/cmake/caches/Apple-stage1.cmake
clang/cmake/caches/Apple-stage2.cmake
clang/test/lit.cfg.py
clang/test/lit.site.cfg.py.in

Removed: 




diff  --git a/clang/cmake/caches/Apple-stage1.cmake 
b/clang/cmake/caches/Apple-stage1.cmake
index 4b11342086a5..8a4fe6dfdfdf 100644
--- a/clang/cmake/caches/Apple-stage1.cmake
+++ b/clang/cmake/caches/Apple-stage1.cmake
@@ -20,6 +20,7 @@ set(CMAKE_MACOSX_RPATH ON CACHE BOOL "")
 set(LLVM_ENABLE_ZLIB OFF CACHE BOOL "")
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
 set(CLANG_PLUGIN_SUPPORT OFF CACHE BOOL "")
+set(CLANG_SPAWN_CC1 ON CACHE BOOL "")
 set(CLANG_BOOTSTRAP_PASSTHROUGH
   CMAKE_OSX_ARCHITECTURES
   CACHE STRING "")

diff  --git a/clang/cmake/caches/Apple-stage2.cmake 
b/clang/cmake/caches/Apple-stage2.cmake
index eb4827002011..b24ec558c071 100644
--- a/clang/cmake/caches/Apple-stage2.cmake
+++ b/clang/cmake/caches/Apple-stage2.cmake
@@ -16,6 +16,7 @@ set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
 set(LLVM_ENABLE_MODULES ON CACHE BOOL "")
 set(LLVM_EXTERNALIZE_DEBUGINFO ON CACHE BOOL "")
 set(CLANG_PLUGIN_SUPPORT OFF CACHE BOOL "")
+set(CLANG_SPAWN_CC1 ON CACHE BOOL "")
 set(BUG_REPORT_URL "http://developer.apple.com/bugreporter/; CACHE STRING "")
 
 set(LLVM_BUILD_EXTERNAL_COMPILER_RT ON CACHE BOOL "Build Compiler-RT with 
just-built clang")

diff  --git a/clang/test/Driver/apple-clang-defaults.c 
b/clang/test/Driver/apple-clang-defaults.c
new file mode 100644
index ..5673e32855a5
--- /dev/null
+++ b/clang/test/Driver/apple-clang-defaults.c
@@ -0,0 +1,7 @@
+// RUN: %clang -c %s -### 2>&1 | FileCheck %s --check-prefix=APPLE-CLANG
+// RUN: %clang -fintegrated-cc1 -c %s -### 2>&1 | FileCheck %s 
--check-prefix=EXPLICIT-IN-PROCESS
+
+// REQUIRES: clang-vendor=com.apple.clang
+
+// APPLE-CLANG-NOT: (in-process)
+// EXPLICIT-IN-PROCESS: (in-process)

diff  --git a/clang/test/lit.cfg.py b/clang/test/lit.cfg.py
index 0358a9d8a959..413f81175420 100644
--- a/clang/test/lit.cfg.py
+++ b/clang/test/lit.cfg.py
@@ -198,3 +198,7 @@ def calculate_arch_features(arch_string):
 
 if config.enable_shared:
 config.available_features.add("enable_shared")
+
+# Add a vendor-specific feature.
+if config.clang_vendor_uti:
+config.available_features.add('clang-vendor=' + config.clang_vendor_uti)

diff  --git a/clang/test/lit.site.cfg.py.in b/clang/test/lit.site.cfg.py.in
index 4527ccadbb4a..d9b5b2f2592e 100644
--- a/clang/test/lit.site.cfg.py.in
+++ b/clang/test/lit.site.cfg.py.in
@@ -30,6 +30,7 @@ config.host_arch = "@HOST_ARCH@"
 config.python_executable = "@Python3_EXECUTABLE@"
 config.use_z3_solver = lit_config.params.get('USE_Z3_SOLVER', 
"@USE_Z3_SOLVER@")
 config.has_plugins = @LLVM_ENABLE_PLUGINS@
+config.clang_vendor_uti = "@CLANG_VENDOR_UTI@"
 
 # Support substitution of the tools and libs dirs with user parameters. This is
 # used when we can't determine the tool dir at configuration time.



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 11d612a - [clang][Preprocessor] Replace the slow translateFile call by a new, faster isMainFile check

2020-05-14 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-05-14T14:13:34-07:00
New Revision: 11d612ac99a621c762c2cc8f7bacbb8ae32d7fe9

URL: 
https://github.com/llvm/llvm-project/commit/11d612ac99a621c762c2cc8f7bacbb8ae32d7fe9
DIFF: 
https://github.com/llvm/llvm-project/commit/11d612ac99a621c762c2cc8f7bacbb8ae32d7fe9.diff

LOG: [clang][Preprocessor] Replace the slow translateFile call by a new, faster 
isMainFile check

The commit 3c28a2dc6bdc331e5a0d8097a5fa59d06682b9d0 introduced the check that 
checks if we're
trying to re-enter a main file when building a preamble. Unfortunately this 
slowed down the preamble
compilation by 80-90% in some test cases, as translateFile is really slow. This 
change checks
to see if the FileEntry is the main file without calling translateFile, but by 
using the new
isMainFile check instead. This speeds up preamble building by 1.5-2x for 
certain test cases that we have.

rdar://59361291

Differential Revision: https://reviews.llvm.org/D79834

Added: 


Modified: 
clang/include/clang/Basic/SourceManager.h
clang/lib/Basic/SourceManager.cpp
clang/lib/Lex/PPDirectives.cpp
clang/unittests/Basic/SourceManagerTest.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index d0910ea31827..693ae4f938e1 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -813,6 +813,11 @@ class SourceManager : public RefCountedBase 
{
 MainFileID = FID;
   }
 
+  /// Returns true when the given FileEntry corresponds to the main file.
+  ///
+  /// The main file should be set prior to calling this function.
+  bool isMainFile(FileEntryRef SourceFile);
+
   /// Set the file ID for the precompiled preamble.
   void setPreambleFileID(FileID Preamble) {
 assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");

diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index e42c3f4ca73f..6e4c8e8052bd 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -389,6 +389,14 @@ void SourceManager::clearIDTables() {
   createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
 }
 
+bool SourceManager::isMainFile(FileEntryRef SourceFile) {
+  assert(MainFileID.isValid() && "expected initialized SourceManager");
+  auto FE = getFileEntryRefForID(MainFileID);
+  if (!FE)
+return false;
+  return FE->getUID() == SourceFile.getUID();
+}
+
 void SourceManager::initializeForReplay(const SourceManager ) {
   assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
 

diff  --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index db249126d393..396ba529fc9a 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -2054,8 +2054,7 @@ Preprocessor::ImportAction 
Preprocessor::HandleHeaderIncludeOrImport(
   // some directives (e.g. #endif of a header guard) will never be seen.
   // Since this will lead to confusing errors, avoid the inclusion.
   if (Action == Enter && File && PreambleConditionalStack.isRecording() &&
-  SourceMgr.translateFile(>getFileEntry()) ==
-  SourceMgr.getMainFileID()) {
+  SourceMgr.isMainFile(*File)) {
 Diag(FilenameTok.getLocation(),
  diag::err_pp_including_mainfile_in_preamble);
 return {ImportAction::None};

diff  --git a/clang/unittests/Basic/SourceManagerTest.cpp 
b/clang/unittests/Basic/SourceManagerTest.cpp
index 850a08b74ace..5fd7607f76d7 100644
--- a/clang/unittests/Basic/SourceManagerTest.cpp
+++ b/clang/unittests/Basic/SourceManagerTest.cpp
@@ -491,6 +491,30 @@ TEST_F(SourceManagerTest, 
isBeforeInTranslationUnitWithMacroInInclude) {
   EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(Macros[10].Loc, 
Macros[11].Loc));
 }
 
+TEST_F(SourceManagerTest, isMainFile) {
+  const char *Source = "int x;";
+
+  std::unique_ptr Buf =
+  llvm::MemoryBuffer::getMemBuffer(Source);
+  const FileEntry *SourceFile =
+  FileMgr.getVirtualFile("mainFile.cpp", Buf->getBufferSize(), 0);
+  SourceMgr.overrideFileContents(SourceFile, std::move(Buf));
+
+  std::unique_ptr Buf2 =
+  llvm::MemoryBuffer::getMemBuffer(Source);
+  const FileEntry *SecondFile =
+  FileMgr.getVirtualFile("file2.cpp", Buf2->getBufferSize(), 0);
+  SourceMgr.overrideFileContents(SecondFile, std::move(Buf2));
+
+  FileID MainFileID = SourceMgr.getOrCreateFileID(SourceFile, SrcMgr::C_User);
+  SourceMgr.setMainFileID(MainFileID);
+
+  EXPECT_TRUE(SourceMgr.isMainFile(FileEntryRef("mainFile.cpp", *SourceFile)));
+  EXPECT_TRUE(
+  SourceMgr.isMainFile(FileEntryRef("anotherName.cpp", *SourceFile)));
+  EXPECT_FALSE(SourceMgr.isMainFile(FileEntryRef("mainFile.cpp", 
*SecondFile)));
+}
+
 #endif
 
 } // anonymous namespace



___
cfe-commits mailing list

[clang-tools-extra] 10b4931 - [test] NFC, add missing declarations and include to test files to avoid 'implicit-function-declaration' diagnostics in the tests

2020-05-14 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-05-14T10:01:50-07:00
New Revision: 10b49315faa6338eaf52bb782e7c53644ad17dab

URL: 
https://github.com/llvm/llvm-project/commit/10b49315faa6338eaf52bb782e7c53644ad17dab
DIFF: 
https://github.com/llvm/llvm-project/commit/10b49315faa6338eaf52bb782e7c53644ad17dab.diff

LOG: [test] NFC, add missing declarations and include to test files to avoid 
'implicit-function-declaration' diagnostics in the tests

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m
compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c
compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov
compiler-rt/test/profile/instrprof-value-prof.c

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m 
b/clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m
index c870e0a0fed0..f395386a02f4 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m
+++ b/clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m
@@ -2,6 +2,10 @@
 
 typedef int OSSpinLock;
 
+void OSSpinlockLock(OSSpinLock *l);
+void OSSpinlockTry(OSSpinLock *l);
+void OSSpinlockUnlock(OSSpinLock *l);
+
 @implementation Foo
 - (void)f {
 int i = 1;

diff  --git 
a/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c 
b/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c
index dadd8959991a..56e0538b1e83 100644
--- a/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c
+++ b/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c
@@ -1,3 +1,5 @@
+extern void __gcov_flush();
+extern int remove(const char *);
 int main(void) {
   __gcov_flush();
 

diff  --git 
a/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov 
b/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov
index 83755451631d..b0921d22461e 100644
--- 
a/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov
+++ 
b/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov
@@ -3,19 +3,21 @@
 // CHECK-NEXT:-:0:Data:instrprof-gcov-__gcov_flush-multiple.gcda
 // CHECK-NEXT:-:0:Runs:1
 // CHECK-NEXT:-:0:Programs:1
-// CHECK-NEXT:#:1:int main(void) {
-// CHECK-NEXT:#:2:  __gcov_flush();
-// CHECK-NEXT:-:3:
-// CHECK-NEXT:#:4:  if 
(remove("instrprof-gcov-__gcov_flush-multiple.gcda") != 0) {
-// CHECK-NEXT:#:5:return 1;
-// CHECK-NEXT:-:6:  }
-// CHECK-NEXT:-:7:
-// CHECK-NEXT:#:8:  __gcov_flush();
-// CHECK-NEXT:#:9:  __gcov_flush();
-// CHECK-NEXT:-:   10:
-// CHECK-NEXT:#:   11:  if 
(remove("instrprof-gcov-__gcov_flush-multiple.gcda") != 0) {
-// CHECK-NEXT:#:   12:return 1;
-// CHECK-NEXT:-:   13:  }
-// CHECK-NEXT:-:   14:
-// CHECK-NEXT:1:   15:  return 0;
-// CHECK-NEXT:1:   16:}
+// CHECK-NEXT:-:1:extern void __gcov_flush();
+// CHECK-NEXT:-:2:extern int remove(const char *);
+// CHECK-NEXT:#:3:int main(void) {
+// CHECK-NEXT:#:4:  __gcov_flush();
+// CHECK-NEXT:-:5:
+// CHECK-NEXT:#:6:  if 
(remove("instrprof-gcov-__gcov_flush-multiple.gcda") != 0) {
+// CHECK-NEXT:#:7:return 1;
+// CHECK-NEXT:-:8:  }
+// CHECK-NEXT:-:9:
+// CHECK-NEXT:#:   10:  __gcov_flush();
+// CHECK-NEXT:#:   11:  __gcov_flush();
+// CHECK-NEXT:-:   12:
+// CHECK-NEXT:#:   13:  if 
(remove("instrprof-gcov-__gcov_flush-multiple.gcda") != 0) {
+// CHECK-NEXT:#:   14:return 1;
+// CHECK-NEXT:-:   15:  }
+// CHECK-NEXT:-:   16:
+// CHECK-NEXT:1:   17:  return 0;
+// CHECK-NEXT:1:   18:}

diff  --git a/compiler-rt/test/profile/instrprof-value-prof.c 
b/compiler-rt/test/profile/instrprof-value-prof.c
index 3a5bdbdd552e..53e5fdafc520 100644
--- a/compiler-rt/test/profile/instrprof-value-prof.c
+++ b/compiler-rt/test/profile/instrprof-value-prof.c
@@ -27,6 +27,7 @@
 #include 
 #include 
 #include 
+#include 
 typedef struct __llvm_profile_data __llvm_profile_data;
 const __llvm_profile_data *__llvm_profile_begin_data(void);
 const __llvm_profile_data *__llvm_profile_end_data(void);



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f96f64d - [driver][Darwin] Add an -ibuiltininc flag that lets Darwin driver

2020-01-28 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-01-28T18:18:43-08:00
New Revision: f96f64d0f2793fe720bf847cac4a45d74a81c0ef

URL: 
https://github.com/llvm/llvm-project/commit/f96f64d0f2793fe720bf847cac4a45d74a81c0ef
DIFF: 
https://github.com/llvm/llvm-project/commit/f96f64d0f2793fe720bf847cac4a45d74a81c0ef.diff

LOG: [driver][Darwin] Add an -ibuiltininc flag that lets Darwin driver
include Clang builtin headers even with -nostdinc

Some projects use -nostdinc, but need to access some intrinsics files when 
building specific files.
The new -ibuiltininc flag lets them use this flag when compiling these files to 
ensure they can
find Clang's builtin headers.

The use of -nobuiltininc after the -ibuiltininc flag does not add the builtin 
header
search path to the list of header search paths.

Differential Revision: https://reviews.llvm.org/D73500

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/darwin-header-search-system.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 650da3ae6462..4d5806154968 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2081,6 +2081,10 @@ def gno_embed_source : Flag<["-"], "gno-embed-source">, 
Group,
 def headerpad__max__install__names : Joined<["-"], 
"headerpad_max_install_names">;
 def help : Flag<["-", "--"], "help">, Flags<[CC1Option,CC1AsOption]>,
   HelpText<"Display available options">;
+def ibuiltininc : Flag<["-"], "ibuiltininc">,
+  HelpText<"Enable builtin #include directories even when -nostdinc is used "
+   "before or after -ibuiltininc. "
+   "Using -nobuiltininc after the option disables it">;
 def index_header_map : Flag<["-"], "index-header-map">, Flags<[CC1Option]>,
   HelpText<"Make the next included directory (-I or -F) an indexer header 
map">;
 def idirafter : JoinedOrSeparate<["-"], "idirafter">, Group, 
Flags<[CC1Option]>,

diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 5588f89a9bae..97f7905685c1 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1870,7 +1870,10 @@ void DarwinClang::AddClangSystemIncludeArgs(const 
llvm::opt::ArgList 
 
   bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
   bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
-  bool NoBuiltinInc = DriverArgs.hasArg(options::OPT_nobuiltininc);
+  bool NoBuiltinInc = DriverArgs.hasFlag(
+  options::OPT_nobuiltininc, options::OPT_ibuiltininc, /*Default=*/false);
+  bool ForceBuiltinInc = DriverArgs.hasFlag(
+  options::OPT_ibuiltininc, options::OPT_nobuiltininc, /*Default=*/false);
 
   // Add /usr/local/include
   if (!NoStdInc && !NoStdlibInc) {
@@ -1880,7 +1883,7 @@ void DarwinClang::AddClangSystemIncludeArgs(const 
llvm::opt::ArgList 
   }
 
   // Add the Clang builtin headers (/include)
-  if (!NoStdInc && !NoBuiltinInc) {
+  if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
 SmallString<128> P(D.ResourceDir);
 llvm::sys::path::append(P, "include");
 addSystemInclude(DriverArgs, CC1Args, P);

diff  --git a/clang/test/Driver/darwin-header-search-system.cpp 
b/clang/test/Driver/darwin-header-search-system.cpp
index fa2ad0ec62b3..a8cd48755179 100644
--- a/clang/test/Driver/darwin-header-search-system.cpp
+++ b/clang/test/Driver/darwin-header-search-system.cpp
@@ -101,3 +101,77 @@
 // CHECK-NOSYSROOT: "-internal-isystem" "/usr/local/include"
 // CHECK-NOSYSROOT: "-internal-isystem" "[[RESOURCE]]/include"
 // CHECK-NOSYSROOT: "-internal-externc-isystem" "/usr/include"
+
+// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
+// RUN: -target x86_64-apple-darwin \
+// RUN: -ccc-install-dir 
%S/Inputs/basic_darwin_toolchain_no_libcxx/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: -isysroot %S/Inputs/basic_darwin_sdk_usr_and_usr_local \
+// RUN: -nostdinc -ibuiltininc \
+// RUN:   | FileCheck -DSYSROOT=%S/Inputs/basic_darwin_sdk_usr_and_usr_local \
+// RUN:   -DRESOURCE=%S/Inputs/resource_dir \
+// RUN:   --check-prefix=CHECK-NOSTDINC-BUILTINC %s
+// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
+// RUN: -target x86_64-apple-darwin \
+// RUN: -ccc-install-dir 
%S/Inputs/basic_darwin_toolchain_no_libcxx/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: -isysroot %S/Inputs/basic_darwin_sdk_usr_and_usr_local \
+// RUN: -ibuiltininc -nostdinc \
+// RUN:   | FileCheck -DSYSROOT=%S/Inputs/basic_darwin_sdk_usr_and_usr_local \
+// RUN:   -DRESOURCE=%S/Inputs/resource_dir \
+// RUN:   --check-prefix=CHECK-NOSTDINC-BUILTINC %s
+// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
+// RUN: -target 

[clang] be88a20 - [driver][darwin] Use explicit -mlinker-version in the -platform_version tests

2019-12-17 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2019-12-17T14:25:22-08:00
New Revision: be88a20c900463c4919433109e4c17cd001da580

URL: 
https://github.com/llvm/llvm-project/commit/be88a20c900463c4919433109e4c17cd001da580
DIFF: 
https://github.com/llvm/llvm-project/commit/be88a20c900463c4919433109e4c17cd001da580.diff

LOG: [driver][darwin] Use explicit -mlinker-version in the -platform_version 
tests

The driver actually adds a default -mlinker-version, based on HOST_LINK_VERSION
cmake variable. The tests should be explicit about which version they're using 
to
trigger the right behavior.

Added: 


Modified: 
clang/test/Driver/darwin-ld-platform-version-ios.c
clang/test/Driver/darwin-ld-platform-version-macos.c
clang/test/Driver/darwin-ld-platform-version-tvos.c
clang/test/Driver/darwin-ld-platform-version-watchos.c

Removed: 




diff  --git a/clang/test/Driver/darwin-ld-platform-version-ios.c 
b/clang/test/Driver/darwin-ld-platform-version-ios.c
index 157aa18bc32f..2255d3f990d7 100644
--- a/clang/test/Driver/darwin-ld-platform-version-ios.c
+++ b/clang/test/Driver/darwin-ld-platform-version-ios.c
@@ -1,8 +1,8 @@
 // RUN: touch %t.o
 
-// RUN: %clang -target arm64-apple-ios12.3 -isysroot 
%S/Inputs/iPhoneOS13.0.sdk -### %t.o 2>&1 \
+// RUN: %clang -target arm64-apple-ios12.3 -isysroot 
%S/Inputs/iPhoneOS13.0.sdk -mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck %s
-// RUN: %clang -target x86_64-apple-ios13-simulator -isysroot 
%S/Inputs/iPhoneOS13.0.sdk -### %t.o 2>&1 \
+// RUN: %clang -target x86_64-apple-ios13-simulator -isysroot 
%S/Inputs/iPhoneOS13.0.sdk -mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=SIMUL %s
 
 // CHECK: "-platform_version" "ios" "12.3.0" "13.0"

diff  --git a/clang/test/Driver/darwin-ld-platform-version-macos.c 
b/clang/test/Driver/darwin-ld-platform-version-macos.c
index 1e86a28b05b6..1b849a6d2dfa 100644
--- a/clang/test/Driver/darwin-ld-platform-version-macos.c
+++ b/clang/test/Driver/darwin-ld-platform-version-macos.c
@@ -1,12 +1,12 @@
 // RUN: touch %t.o
 
-// RUN: %clang -target x86_64-apple-macos10.13 -isysroot 
%S/Inputs/MacOSX10.14.sdk -### %t.o 2>&1 \
+// RUN: %clang -target x86_64-apple-macos10.13 -isysroot 
%S/Inputs/MacOSX10.14.sdk -mlinker-version=0 -### %t.o 2>&1 \
 // RUN:   | FileCheck %s
 // RUN: env SDKROOT=%S/Inputs/MacOSX10.14.sdk %clang -target 
x86_64-apple-macos10.13.0.1 -mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck %s
 
 // CHECK: "-platform_version" "macos" "10.13.0" "10.14"
 
-// RUN: %clang -target x86_64-apple-macos10.13 -### %t.o 2>&1 \
+// RUN: %clang -target x86_64-apple-macos10.13  -mlinker-version=520 -### %t.o 
2>&1 \
 // RUN:   | FileCheck --check-prefix=NOSDK %s
 // NOSDK: "-platform_version" "macos" "10.13.0" "0.0.0"

diff  --git a/clang/test/Driver/darwin-ld-platform-version-tvos.c 
b/clang/test/Driver/darwin-ld-platform-version-tvos.c
index cb32f7096f5c..1ef6a0b60004 100644
--- a/clang/test/Driver/darwin-ld-platform-version-tvos.c
+++ b/clang/test/Driver/darwin-ld-platform-version-tvos.c
@@ -1,8 +1,8 @@
 // RUN: touch %t.o
 
-// RUN: %clang -target arm64-apple-tvos12.3 -isysroot 
%S/Inputs/iPhoneOS13.0.sdk -### %t.o 2>&1 \
+// RUN: %clang -target arm64-apple-tvos12.3 -isysroot 
%S/Inputs/iPhoneOS13.0.sdk -mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck %s
-// RUN: %clang -target x86_64-apple-tvos13-simulator -isysroot 
%S/Inputs/iPhoneOS13.0.sdk -### %t.o 2>&1 \
+// RUN: %clang -target x86_64-apple-tvos13-simulator -isysroot 
%S/Inputs/iPhoneOS13.0.sdk -mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=SIMUL %s
 
 // CHECK: "-platform_version" "tvos" "12.3.0" "13.0"

diff  --git a/clang/test/Driver/darwin-ld-platform-version-watchos.c 
b/clang/test/Driver/darwin-ld-platform-version-watchos.c
index f2666b014f0e..9663fc613816 100644
--- a/clang/test/Driver/darwin-ld-platform-version-watchos.c
+++ b/clang/test/Driver/darwin-ld-platform-version-watchos.c
@@ -1,8 +1,8 @@
 // RUN: touch %t.o
 
-// RUN: %clang -target arm64_32-apple-watchos5.2 -isysroot 
%S/Inputs/WatchOS6.0.sdk -### %t.o 2>&1 \
+// RUN: %clang -target arm64_32-apple-watchos5.2 -isysroot 
%S/Inputs/WatchOS6.0.sdk -mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck %s
-// RUN: %clang -target x86_64-apple-watchos6-simulator -isysroot 
%S/Inputs/WatchOS6.0.sdk -### %t.o 2>&1 \
+// RUN: %clang -target x86_64-apple-watchos6-simulator -isysroot 
%S/Inputs/WatchOS6.0.sdk -mlinker-version=520 -### %t.o 2>&1 \
 // RUN:   | FileCheck --check-prefix=SIMUL %s
 
 // CHECK: "-platform_version" "watchos" "5.2.0" "6.0.0"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a4e1819 - [objc_direct] fix uniquing when re-declaring a readwrite-direct property

2019-12-17 Thread Alex Lorenz via cfe-commits

Author: Pierre Habouzit
Date: 2019-12-17T11:07:48-08:00
New Revision: a4e1819c16836dba928e646024a2406bb2eb3f94

URL: 
https://github.com/llvm/llvm-project/commit/a4e1819c16836dba928e646024a2406bb2eb3f94
DIFF: 
https://github.com/llvm/llvm-project/commit/a4e1819c16836dba928e646024a2406bb2eb3f94.diff

LOG: [objc_direct] fix uniquing when re-declaring a readwrite-direct property

ObjCMethodDecl::getCanonicalDecl() for re-declared readwrite properties,
only looks in the ObjCInterface for the declaration of the setter
method, which it won't find.

When the method is a property accessor, we must look in extensions for a
possible redeclaration.

Radar-Id: rdar://problem/57991337

Differential Revision: https://reviews.llvm.org/D71588

Added: 


Modified: 
clang/lib/AST/DeclObjC.cpp
clang/test/CodeGenObjC/direct-method.m

Removed: 




diff  --git a/clang/lib/AST/DeclObjC.cpp b/clang/lib/AST/DeclObjC.cpp
index fed76aecdaa2..ca70afd9db25 100644
--- a/clang/lib/AST/DeclObjC.cpp
+++ b/clang/lib/AST/DeclObjC.cpp
@@ -958,10 +958,18 @@ ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
   auto *CtxD = cast(getDeclContext());
 
   if (auto *ImplD = dyn_cast(CtxD)) {
-if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
+if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) {
   if (ObjCMethodDecl *MD = IFD->getMethod(getSelector(),
   isInstanceMethod()))
 return MD;
+  // readwrite properties may have been re-declared in an extension.
+  // look harder.
+  if (isPropertyAccessor())
+for (auto *Ext : IFD->known_extensions())
+  if (ObjCMethodDecl *MD =
+  Ext->getMethod(getSelector(), isInstanceMethod()))
+return MD;
+}
   } else if (auto *CImplD = dyn_cast(CtxD)) {
 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
   if (ObjCMethodDecl *MD = CatD->getMethod(getSelector(),

diff  --git a/clang/test/CodeGenObjC/direct-method.m 
b/clang/test/CodeGenObjC/direct-method.m
index 373bd22a84cd..c42910c1676a 100644
--- a/clang/test/CodeGenObjC/direct-method.m
+++ b/clang/test/CodeGenObjC/direct-method.m
@@ -191,6 +191,14 @@ int useRoot(Root *r) {
   return [r getInt] + [r intProperty] + [r intProperty2];
 }
 
+int useFoo(Foo *f) {
+  // CHECK-LABEL: define i32 @useFoo
+  // CHECK: call void bitcast {{.*}} @"\01-[Foo setGetDynamic_setDirect:]"
+  // CHECK: %{{[^ ]*}} = call i32 bitcast {{.*}} @"\01-[Foo 
getDirect_setDynamic]"
+  [f setGetDynamic_setDirect:1];
+  return [f getDirect_setDynamic];
+}
+
 __attribute__((objc_root_class))
 @interface RootDeclOnly
 @property(direct, readonly) int intProperty;



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 25ce33a - [driver][darwin] Pass -platform_version flag to the linker instead of the -_version_min flag

2019-12-17 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2019-12-17T10:26:32-08:00
New Revision: 25ce33a6e4f3b13732c0f851e68390dc2acb9123

URL: 
https://github.com/llvm/llvm-project/commit/25ce33a6e4f3b13732c0f851e68390dc2acb9123
DIFF: 
https://github.com/llvm/llvm-project/commit/25ce33a6e4f3b13732c0f851e68390dc2acb9123.diff

LOG: [driver][darwin] Pass -platform_version flag to the linker instead of the 
-_version_min flag

In Xcode 11, ld added a new flag called -platform_version that can be used 
instead of the old -_version_min flags.
The new flag allows Clang to pass the SDK version from the driver to the linker.
This patch adopts the new -platform_version flag in Clang, and starts using it 
by default,
unless a linker version < 520 is passed to the driver.

Differential Revision: https://reviews.llvm.org/D71579

Added: 
clang/test/Driver/Inputs/WatchOS6.0.sdk/SDKSettings.json
clang/test/Driver/Inputs/iPhoneOS13.0.sdk/SDKSettings.json
clang/test/Driver/darwin-ld-platform-version-ios.c
clang/test/Driver/darwin-ld-platform-version-macos.c
clang/test/Driver/darwin-ld-platform-version-tvos.c
clang/test/Driver/darwin-ld-platform-version-watchos.c

Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h
clang/test/Driver/darwin-infer-simulator-sdkroot.c
clang/test/Driver/darwin-ld.c
clang/test/Driver/darwin-sdkroot.c
clang/test/Driver/target-triple-deployment.c
llvm/include/llvm/Support/VersionTuple.h

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 75a47d2c3a23..5725a326ca5f 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -336,7 +336,10 @@ void darwin::Linker::AddLinkArgs(Compilation , const 
ArgList ,
   Args.AddAllArgs(CmdArgs, options::OPT_init);
 
   // Add the deployment target.
-  MachOTC.addMinVersionArgs(Args, CmdArgs);
+  if (!Version[0] || Version[0] >= 520)
+MachOTC.addPlatformVersionArgs(Args, CmdArgs);
+  else
+MachOTC.addMinVersionArgs(Args, CmdArgs);
 
   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
@@ -2515,6 +2518,45 @@ void Darwin::addMinVersionArgs(const ArgList ,
   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
 }
 
+static const char *getPlatformName(Darwin::DarwinPlatformKind Platform,
+   Darwin::DarwinEnvironmentKind Environment) {
+  switch (Platform) {
+  case Darwin::MacOS:
+return "macos";
+  case Darwin::IPhoneOS:
+if (Environment == Darwin::NativeEnvironment ||
+Environment == Darwin::Simulator)
+  return "ios";
+// FIXME: Add macCatalyst support here ("\"mac catalyst\"").
+llvm_unreachable("macCatalyst isn't yet supported");
+  case Darwin::TvOS:
+return "tvos";
+  case Darwin::WatchOS:
+return "watchos";
+  }
+  llvm_unreachable("invalid platform");
+}
+
+void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList ,
+llvm::opt::ArgStringList ) const {
+  // -platform_version   
+  // Both the target and SDK version support only up to 3 components.
+  CmdArgs.push_back("-platform_version");
+  std::string PlatformName = getPlatformName(TargetPlatform, 
TargetEnvironment);
+  if (TargetEnvironment == Darwin::Simulator)
+PlatformName += "-simulator";
+  CmdArgs.push_back(Args.MakeArgString(PlatformName));
+  VersionTuple TargetVersion = getTargetVersion().withoutBuild();
+  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
+  if (SDKInfo) {
+VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
+CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
+  } else {
+// Use a blank SDK version if it's not present.
+CmdArgs.push_back("0.0.0");
+  }
+}
+
 void Darwin::addStartObjectFileArgs(const ArgList ,
 ArgStringList ) const {
   // Derived from startfile spec.

diff  --git a/clang/lib/Driver/ToolChains/Darwin.h 
b/clang/lib/Driver/ToolChains/Darwin.h
index 1b1c358c40a4..1b193a4c4eb9 100644
--- a/clang/lib/Driver/ToolChains/Darwin.h
+++ b/clang/lib/Driver/ToolChains/Darwin.h
@@ -167,6 +167,10 @@ class LLVM_LIBRARY_VISIBILITY MachO : public ToolChain {
   virtual void addMinVersionArgs(const llvm::opt::ArgList ,
  llvm::opt::ArgStringList ) const {}
 
+  virtual void addPlatformVersionArgs(const llvm::opt::ArgList ,
+  llvm::opt::ArgStringList ) const 
{
+  }
+
   /// On some iOS platforms, kernel and kernel modules were built statically. 
Is
   /// this such a target?
   virtual bool isKernelStatic() const { return false; }
@@ -314,6 +318,9 @@ class LLVM_LIBRARY_VISIBILITY Darwin : public MachO {
   void addMinVersionArgs(const llvm::opt::ArgList ,
  

[clang] 1646bb8 - Also synthesize _cmd and self for properties

2019-12-09 Thread Alex Lorenz via cfe-commits

Author: Pierre Habouzit
Date: 2019-12-09T14:30:01-08:00
New Revision: 1646bb86643326db6e220291d5c71c8d616f66fb

URL: 
https://github.com/llvm/llvm-project/commit/1646bb86643326db6e220291d5c71c8d616f66fb
DIFF: 
https://github.com/llvm/llvm-project/commit/1646bb86643326db6e220291d5c71c8d616f66fb.diff

LOG: Also synthesize _cmd and self for properties

Patch by: Pierre Habouzit

Differential Revision: https://reviews.llvm.org/D71226

Added: 


Modified: 
clang/lib/Sema/SemaObjCProperty.cpp
clang/test/CodeGenObjC/direct-method.m

Removed: 




diff  --git a/clang/lib/Sema/SemaObjCProperty.cpp 
b/clang/lib/Sema/SemaObjCProperty.cpp
index 2d91ea1f5fd0..f6717f4cbe5e 100644
--- a/clang/lib/Sema/SemaObjCProperty.cpp
+++ b/clang/lib/Sema/SemaObjCProperty.cpp
@@ -2498,6 +2498,9 @@ void Sema::ProcessPropertyDecl(ObjCPropertyDecl 
*property) {
 // A user declared getter will be synthesize when @synthesize of
 // the property with the same name is seen in the @implementation
 GetterMethod->setPropertyAccessor(true);
+
+  GetterMethod->createImplicitParams(Context,
+ GetterMethod->getClassInterface());
   property->setGetterMethodDecl(GetterMethod);
 
   // Skip setter if property is read-only.
@@ -2569,6 +2572,9 @@ void Sema::ProcessPropertyDecl(ObjCPropertyDecl 
*property) {
   // A user declared setter will be synthesize when @synthesize of
   // the property with the same name is seen in the @implementation
   SetterMethod->setPropertyAccessor(true);
+
+SetterMethod->createImplicitParams(Context,
+   SetterMethod->getClassInterface());
 property->setSetterMethodDecl(SetterMethod);
   }
   // Add any synthesized methods to the global pool. This allows us to

diff  --git a/clang/test/CodeGenObjC/direct-method.m 
b/clang/test/CodeGenObjC/direct-method.m
index eb5a52eb11a2..373bd22a84cd 100644
--- a/clang/test/CodeGenObjC/direct-method.m
+++ b/clang/test/CodeGenObjC/direct-method.m
@@ -190,3 +190,14 @@ int useRoot(Root *r) {
   // CHECK: %{{[^ ]*}} = call i32 bitcast {{.*}} @"\01-[Root intProperty2]"
   return [r getInt] + [r intProperty] + [r intProperty2];
 }
+
+__attribute__((objc_root_class))
+@interface RootDeclOnly
+@property(direct, readonly) int intProperty;
+@end
+
+int useRootDeclOnly(RootDeclOnly *r) {
+  // CHECK-LABEL: define i32 @useRootDeclOnly
+  // CHECK: %{{[^ ]*}} = call i32 bitcast {{.*}} @"\01-[RootDeclOnly 
intProperty]"
+  return [r intProperty];
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f3efd69 - [ObjC] Make sure that the implicit arguments for direct methods have been setup

2019-12-06 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2019-12-06T14:28:28-08:00
New Revision: f3efd6957474bfd3b9b232ac6e4b3608174c3b79

URL: 
https://github.com/llvm/llvm-project/commit/f3efd6957474bfd3b9b232ac6e4b3608174c3b79
DIFF: 
https://github.com/llvm/llvm-project/commit/f3efd6957474bfd3b9b232ac6e4b3608174c3b79.diff

LOG: [ObjC] Make sure that the implicit arguments for direct methods have been 
setup

This commit sets the Self and Imp declarations for ObjC method declarations,
in addition to the definitions. It also fixes
a bunch of code in clang that had wrong assumptions about when getSelfDecl() 
would be set:

- CGDebugInfo::getObjCMethodName and AnalysisConsumer::getFunctionName would 
assume that it was
  set for method declarations part of a protocol, which they never were,
  and that self would be a Class type, which it isn't as it is id for a 
protocol.

Also use the Canonical Decl to index the set of Direct methods so that
when calls and implementations interleave, the same llvm::Function is
used and the same symbol name emitted.

Radar-Id: rdar://problem/57661767

Patch by: Pierre Habouzit

Differential Revision: https://reviews.llvm.org/D71091

Added: 


Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGObjCMac.cpp
clang/lib/Sema/SemaDeclObjC.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriterDecl.cpp
clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
clang/test/CodeGenObjC/direct-method.m

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 8d6406c02773..7ea3c0850fe2 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -292,13 +292,6 @@ StringRef CGDebugInfo::getObjCMethodName(const 
ObjCMethodDecl *OMD) {
 }
   } else if (const auto *OCD = dyn_cast(DC)) {
 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
-  } else if (isa(DC)) {
-// We can extract the type of the class from the self pointer.
-if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
-  QualType ClassTy =
-  cast(SelfDecl->getType())->getPointeeType();
-  ClassTy.print(OS, PrintingPolicy(LangOptions()));
-}
   }
   OS << ' ' << OMD->getSelector().getAsString() << ']';
 

diff  --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 775e3406da7e..5bd04bc88b75 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -4027,7 +4027,7 @@ llvm::Function *CGObjCCommonMac::GenerateMethod(const 
ObjCMethodDecl *OMD,
 llvm::Function *
 CGObjCCommonMac::GenerateDirectMethod(const ObjCMethodDecl *OMD,
   const ObjCContainerDecl *CD) {
-  auto I = DirectMethodDefinitions.find(OMD);
+  auto I = DirectMethodDefinitions.find(OMD->getCanonicalDecl());
   if (I != DirectMethodDefinitions.end())
 return I->second;
 
@@ -4040,7 +4040,7 @@ CGObjCCommonMac::GenerateDirectMethod(const 
ObjCMethodDecl *OMD,
   llvm::Function *Method =
   llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage,
  Name.str(), ());
-  DirectMethodDefinitions.insert(std::make_pair(OMD, Method));
+  DirectMethodDefinitions.insert(std::make_pair(OMD->getCanonicalDecl(), 
Method));
 
   return Method;
 }

diff  --git a/clang/lib/Sema/SemaDeclObjC.cpp b/clang/lib/Sema/SemaDeclObjC.cpp
index e84dc47a1ee1..70c04571ac67 100644
--- a/clang/lib/Sema/SemaDeclObjC.cpp
+++ b/clang/lib/Sema/SemaDeclObjC.cpp
@@ -4869,6 +4869,9 @@ Decl *Sema::ActOnMethodDeclaration(
 }
   }
 
+  // Insert the invisible arguments, self and _cmd!
+  ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface());
+
   ActOnDocumentableDecl(ObjCMethod);
 
   return ObjCMethod;

diff  --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index d989f46c4ab4..8990379069b3 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -1017,9 +1017,9 @@ void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl 
*MD) {
 // definitions rarely show up in headers.
 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
 HasPendingBody = true;
-MD->setSelfDecl(ReadDeclAs());
-MD->setCmdDecl(ReadDeclAs());
   }
+  MD->setSelfDecl(ReadDeclAs());
+  MD->setCmdDecl(ReadDeclAs());
   MD->setInstanceMethod(Record.readInt());
   MD->setVariadic(Record.readInt());
   MD->setPropertyAccessor(Record.readInt());

diff  --git a/clang/lib/Serialization/ASTWriterDecl.cpp 
b/clang/lib/Serialization/ASTWriterDecl.cpp
index 38eb64e52e4a..eaf2c5458be7 100644
--- a/clang/lib/Serialization/ASTWriterDecl.cpp
+++ b/clang/lib/Serialization/ASTWriterDecl.cpp
@@ -664,14 +664,13 @@ void ASTDeclWriter::VisitObjCMethodDecl(ObjCMethodDecl 
*D) {
   VisitNamedDecl(D);
   // FIXME: convert to LazyStmtPtr?
   // 

[clang-tools-extra] 27f1244 - [clangd] Add a tweak refactoring to wrap Objective-C string literals in `NSLocalizedString` macros

2019-12-04 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2019-12-04T16:58:12-08:00
New Revision: 27f124445755a80e048a68d2fabbd2fa6f40a723

URL: 
https://github.com/llvm/llvm-project/commit/27f124445755a80e048a68d2fabbd2fa6f40a723
DIFF: 
https://github.com/llvm/llvm-project/commit/27f124445755a80e048a68d2fabbd2fa6f40a723.diff

LOG: [clangd]  Add a tweak refactoring to wrap Objective-C string literals in 
`NSLocalizedString` macros

The commit adds a refactoring to Clangd that mimics the existing refactoring 
action in Xcode that wraps around an Objective-C string literal in an 
NSLocalizedString macro.

Differential Revision: https://reviews.llvm.org/D69543

Added: 
clang-tools-extra/clangd/refactor/tweaks/ObjCLocalizeStringLiteral.cpp

Modified: 
clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
clang-tools-extra/clangd/unittests/TweakTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt 
b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index cd68d7afe6ab..6f6ef4a2ace2 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -20,6 +20,7 @@ add_clang_library(clangDaemonTweaks OBJECT
   ExpandMacro.cpp
   ExtractFunction.cpp
   ExtractVariable.cpp
+  ObjCLocalizeStringLiteral.cpp
   RawStringLiteral.cpp
   RemoveUsingNamespace.cpp
   SwapIfBranches.cpp

diff  --git 
a/clang-tools-extra/clangd/refactor/tweaks/ObjCLocalizeStringLiteral.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/ObjCLocalizeStringLiteral.cpp
new file mode 100644
index ..62d0c6a2d20c
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/ObjCLocalizeStringLiteral.cpp
@@ -0,0 +1,85 @@
+//===--- ObjcLocalizeStringLiteral.cpp ---*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "Logger.h"
+#include "ParsedAST.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "clang/AST/ExprObjC.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/iterator_range.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+/// Wraps an Objective-C string literal with the NSLocalizedString macro.
+/// Before:
+///   @"description"
+///   ^^^
+/// After:
+///   NSLocalizedString(@"description", @"")
+class ObjCLocalizeStringLiteral : public Tweak {
+public:
+  const char *id() const override final;
+  Intent intent() const override { return Intent::Refactor; }
+
+  bool prepare(const Selection ) override;
+  Expected apply(const Selection ) override;
+  std::string title() const override;
+
+private:
+  const clang::ObjCStringLiteral *Str = nullptr;
+};
+
+REGISTER_TWEAK(ObjCLocalizeStringLiteral)
+
+bool ObjCLocalizeStringLiteral::prepare(const Selection ) {
+  const SelectionTree::Node *N = Inputs.ASTSelection.commonAncestor();
+  if (!N)
+return false;
+  // Allow the refactoring even if the user selected only the C string part
+  // of the expression.
+  if (N->ASTNode.get()) {
+if (N->Parent)
+  N = N->Parent;
+  }
+  Str = dyn_cast_or_null(N->ASTNode.get());
+  return Str;
+}
+
+Expected
+ObjCLocalizeStringLiteral::apply(const Selection ) {
+  auto  = Inputs.AST.getSourceManager();
+  auto  = Inputs.AST.getASTContext().getLangOpts();
+  auto Reps = tooling::Replacements(tooling::Replacement(
+  SM, CharSourceRange::getCharRange(Str->getBeginLoc()),
+  "NSLocalizedString(", LangOpts));
+  SourceLocation EndLoc = Lexer::getLocForEndOfToken(
+  Str->getEndLoc(), 0, Inputs.AST.getSourceManager(), LangOpts);
+  if (auto Err = Reps.add(tooling::Replacement(
+  SM, CharSourceRange::getCharRange(EndLoc), ", @\"\")", LangOpts)))
+return std::move(Err);
+  return Effect::mainFileEdit(SM, std::move(Reps));
+}
+
+std::string ObjCLocalizeStringLiteral::title() const {
+  return "Wrap in NSLocalizedString";
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang

diff  --git a/clang-tools-extra/clangd/unittests/TweakTests.cpp 
b/clang-tools-extra/clangd/unittests/TweakTests.cpp
index 7bdf599f302e..f45866a52bd5 100644
--- a/clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -122,6 +122,25 @@ literal)")cpp";
   EXPECT_EQ(apply(Input), Output);
 }
 
+TWEAK_TEST(ObjCLocalizeStringLiteral);
+TEST_F(ObjCLocalizeStringLiteralTest, Test) {
+  

[clang-tools-extra] c0ee022 - [clangd] NFC, add getLangOpts helper to ParsedAST

2019-12-04 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2019-12-04T16:55:25-08:00
New Revision: c0ee0224c4cf52bc6ba74dec88b30b850deca523

URL: 
https://github.com/llvm/llvm-project/commit/c0ee0224c4cf52bc6ba74dec88b30b850deca523
DIFF: 
https://github.com/llvm/llvm-project/commit/c0ee0224c4cf52bc6ba74dec88b30b850deca523.diff

LOG: [clangd] NFC, add getLangOpts helper to ParsedAST

The addition of the helper is split out from https://reviews.llvm.org/D69543
as suggested by Kadir. I also updated the existing uses to use the new API.

Added: 


Modified: 
clang-tools-extra/clangd/ClangdServer.cpp
clang-tools-extra/clangd/HeaderSourceSwitch.cpp
clang-tools-extra/clangd/Hover.cpp
clang-tools-extra/clangd/ParsedAST.h
clang-tools-extra/clangd/SemanticSelection.cpp
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/refactor/Rename.cpp
clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
clang-tools-extra/clangd/unittests/CollectMacrosTests.cpp
clang-tools-extra/clangd/unittests/SelectionTests.cpp
clang-tools-extra/clangd/unittests/SourceCodeTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 6c5fabdce5c3..e9e03dbc3742 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -312,8 +312,8 @@ void ClangdServer::prepareRename(PathRef File, Position Pos,
 const auto  = AST.getSourceManager();
 SourceLocation Loc =
 SM.getMacroArgExpandedLocation(getBeginningOfIdentifier(
-Pos, AST.getSourceManager(), AST.getASTContext().getLangOpts()));
-auto Range = getTokenRange(SM, AST.getASTContext().getLangOpts(), Loc);
+Pos, AST.getSourceManager(), AST.getLangOpts()));
+auto Range = getTokenRange(SM, AST.getLangOpts(), Loc);
 if (!Range)
   return CB(llvm::None); // "rename" is not valid at the position.
 

diff  --git a/clang-tools-extra/clangd/HeaderSourceSwitch.cpp 
b/clang-tools-extra/clangd/HeaderSourceSwitch.cpp
index 698f2460fea5..f90e46a24f32 100644
--- a/clang-tools-extra/clangd/HeaderSourceSwitch.cpp
+++ b/clang-tools-extra/clangd/HeaderSourceSwitch.cpp
@@ -97,7 +97,7 @@ llvm::Optional getCorrespondingHeaderOrSource(const 
Path ,
   //
   // For each symbol in the original file, we get its target location (decl or
   // def) from the index, then award that target file.
-  bool IsHeader = isHeaderFile(OriginalFile, 
AST.getASTContext().getLangOpts());
+  bool IsHeader = isHeaderFile(OriginalFile, AST.getLangOpts());
   Index->lookup(Request, [&](const Symbol ) {
 if (IsHeader)
   AwardTarget(Sym.Definition.FileURI);

diff  --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index c14ff1b3fe63..9053bc08b4ec 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -367,8 +367,7 @@ HoverInfo getHoverContents(const DefinedMacro , 
ParsedAST ) {
   SourceLocation StartLoc = Macro.Info->getDefinitionLoc();
   SourceLocation EndLoc = Macro.Info->getDefinitionEndLoc();
   if (EndLoc.isValid()) {
-EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM,
-AST.getASTContext().getLangOpts());
+EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM, AST.getLangOpts());
 bool Invalid;
 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), );
 if (!Invalid) {
@@ -391,7 +390,7 @@ llvm::Optional getHover(ParsedAST , Position 
Pos,
   const SourceManager  = AST.getSourceManager();
   llvm::Optional HI;
   SourceLocation SourceLocationBeg = SM.getMacroArgExpandedLocation(
-  getBeginningOfIdentifier(Pos, SM, AST.getASTContext().getLangOpts()));
+  getBeginningOfIdentifier(Pos, SM, AST.getLangOpts()));
 
   if (auto Deduced = getDeducedType(AST.getASTContext(), SourceLocationBeg)) {
 // Find the corresponding decl to populate kind and fetch documentation.
@@ -435,9 +434,8 @@ llvm::Optional getHover(ParsedAST , Position 
Pos,
   tooling::applyAllReplacements(HI->Definition, Replacements))
 HI->Definition = *Formatted;
 
-  HI->SymRange =
-  getTokenRange(AST.getASTContext().getSourceManager(),
-AST.getASTContext().getLangOpts(), SourceLocationBeg);
+  HI->SymRange = getTokenRange(AST.getASTContext().getSourceManager(),
+   AST.getLangOpts(), SourceLocationBeg);
   return HI;
 }
 

diff  --git a/clang-tools-extra/clangd/ParsedAST.h 
b/clang-tools-extra/clangd/ParsedAST.h
index 0b4a6ab73df8..f2afc264e23a 100644
--- a/clang-tools-extra/clangd/ParsedAST.h
+++ b/clang-tools-extra/clangd/ParsedAST.h
@@ -77,6 +77,10 @@ class ParsedAST {
 return getASTContext().getSourceManager();
   }
 
+  const LangOptions () const {

[clang] 3895305 - [clang-scan-deps] do not skip empty #if/#elif in the minimizer to avoid missing `__has_include` dependencies

2019-12-02 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2019-12-02T18:47:22-08:00
New Revision: 389530524be1715e97947810514f3a75dfe73975

URL: 
https://github.com/llvm/llvm-project/commit/389530524be1715e97947810514f3a75dfe73975
DIFF: 
https://github.com/llvm/llvm-project/commit/389530524be1715e97947810514f3a75dfe73975.diff

LOG: [clang-scan-deps] do not skip empty #if/#elif in the minimizer to avoid 
missing `__has_include` dependencies

This patch makes the minimizer more conservative to avoid missing dependency 
files that are brought in by __has_include
PP expressions that occur in a condition of an #if/#elif that was previously 
skipped. The __has_include PP expressions
can be used in an #if/#elif either directly, or through macro expansion, so we 
can't detect them at the time of minimization.

Differential Revision: https://reviews.llvm.org/D70936

Added: 
clang/test/ClangScanDeps/Inputs/has_include_if_elif.json
clang/test/ClangScanDeps/has_include_if_elif.cpp

Modified: 
clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp

Removed: 




diff  --git a/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp 
b/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
index f063ed711c44..029bfe1cd600 100644
--- a/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
+++ b/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
@@ -763,12 +763,13 @@ bool Minimizer::lexEndif(const char *, const char 
*const End) {
   if (top() == pp_else)
 popToken();
 
-  // Strip out "#elif" if they're empty.
-  while (top() == pp_elif)
-popToken();
-
-  // If "#if" is empty, strip it and skip the "#endif".
-  if (top() == pp_if || top() == pp_ifdef || top() == pp_ifndef) {
+  // If "#ifdef" is empty, strip it and skip the "#endif".
+  //
+  // FIXME: Once/if Clang starts disallowing __has_include in macro expansions,
+  // we can skip empty `#if` and `#elif` blocks as well after scanning for a
+  // literal __has_include in the condition.  Even without that rule we could
+  // drop the tokens if we scan for identifiers in the condition and find none.
+  if (top() == pp_ifdef || top() == pp_ifndef) {
 popToken();
 skipLine(First, End);
 return false;

diff  --git a/clang/test/ClangScanDeps/Inputs/has_include_if_elif.json 
b/clang/test/ClangScanDeps/Inputs/has_include_if_elif.json
new file mode 100644
index ..36ca006b0329
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/has_include_if_elif.json
@@ -0,0 +1,7 @@
+[
+{
+  "directory": "DIR",
+  "command": "clang -E DIR/has_include_if_elif2.cpp -IInputs",
+  "file": "DIR/has_include_if_elif2.cpp"
+}
+]

diff  --git a/clang/test/ClangScanDeps/has_include_if_elif.cpp 
b/clang/test/ClangScanDeps/has_include_if_elif.cpp
new file mode 100644
index ..dd56ecac69db
--- /dev/null
+++ b/clang/test/ClangScanDeps/has_include_if_elif.cpp
@@ -0,0 +1,38 @@
+// RUN: rm -rf %t.dir
+// RUN: rm -rf %t.cdb
+// RUN: mkdir -p %t.dir
+// RUN: cp %s %t.dir/has_include_if_elif2.cpp
+// RUN: mkdir %t.dir/Inputs
+// RUN: cp %S/Inputs/header.h %t.dir/Inputs/header.h
+// RUN: cp %S/Inputs/header.h %t.dir/Inputs/header2.h
+// RUN: cp %S/Inputs/header.h %t.dir/Inputs/header3.h
+// RUN: cp %S/Inputs/header.h %t.dir/Inputs/header4.h
+// RUN: sed -e "s|DIR|%/t.dir|g" %S/Inputs/has_include_if_elif.json > %t.cdb
+//
+// RUN: clang-scan-deps -compilation-database %t.cdb -j 1 -mode 
preprocess-minimized-sources | \
+// RUN:   FileCheck %s
+// RUN: clang-scan-deps -compilation-database %t.cdb -j 1 -mode preprocess | \
+// RUN:   FileCheck %s
+
+#if __has_include("header.h")
+#endif
+
+#if 0
+#elif __has_include("header2.h")
+#endif
+
+#define H3 __has_include("header3.h")
+#if H3
+#endif
+
+#define H4 __has_include("header4.h")
+
+#if 0
+#elif H4
+#endif
+
+// CHECK: has_include_if_elif2.cpp
+// CHECK-NEXT: Inputs{{/|\\}}header.h
+// CHECK-NEXT: Inputs{{/|\\}}header2.h
+// CHECK-NEXT: Inputs{{/|\\}}header3.h
+// CHECK-NEXT: Inputs{{/|\\}}header4.h

diff  --git a/clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp 
b/clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp
index ed44cd86b3e4..b5bba30db78d 100644
--- a/clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp
+++ b/clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp
@@ -328,12 +328,17 @@ TEST(MinimizeSourceToDependencyDirectivesTest, 
EmptyIfdef) {
   SmallVector Out;
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives("#ifdef A\n"
+"void skip();\n"
 "#elif B\n"
 "#elif C\n"
 "#else D\n"
 "#endif\n",
 Out));
-  EXPECT_STREQ("", 

[clang-tools-extra] e1b07aa - [clangd] NFC, reuse the source manager variable in the RawStringLiteral apply method

2019-11-08 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2019-11-08T14:50:54-08:00
New Revision: e1b07aac3d1c92f58e05cb5c37c0707842da5839

URL: 
https://github.com/llvm/llvm-project/commit/e1b07aac3d1c92f58e05cb5c37c0707842da5839
DIFF: 
https://github.com/llvm/llvm-project/commit/e1b07aac3d1c92f58e05cb5c37c0707842da5839.diff

LOG: [clangd] NFC, reuse the source manager variable in the RawStringLiteral 
apply method

Differential Revision: https://reviews.llvm.org/D69544

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
index 17eed4b7962f..42d0122b3382 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
@@ -90,8 +90,7 @@ bool RawStringLiteral::prepare(const Selection ) {
 Expected RawStringLiteral::apply(const Selection ) {
   auto  = Inputs.AST.getSourceManager();
   auto Reps = tooling::Replacements(
-  tooling::Replacement(Inputs.AST.getSourceManager(), Str,
-   ("R\"(" + Str->getBytes() + ")\"").str(),
+  tooling::Replacement(SM, Str, ("R\"(" + Str->getBytes() + ")\"").str(),
Inputs.AST.getASTContext().getLangOpts()));
   return Effect::mainFileEdit(SM, std::move(Reps));
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r374127 - [clang-scan-deps] Improve string/character literal skipping

2019-10-08 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Tue Oct  8 15:42:44 2019
New Revision: 374127

URL: http://llvm.org/viewvc/llvm-project?rev=374127=rev
Log:
[clang-scan-deps] Improve string/character literal skipping

The existing string/character literal skipping code in the
dependency directives source minimizer has two issues:

- It doesn't stop the scanning when a newline is reached before the terminating 
character,
unlike the lexer which considers the token to be done (even if it's invalid) at 
the end of the line.

- It doesn't support whitespace between '\' and the newline when looking if the 
'\' is used as a line continuation character.

This commit fixes both issues.

Differential Revision: https://reviews.llvm.org/D68436

Modified:
cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp

Modified: cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp?rev=374127=374126=374127=diff
==
--- cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp (original)
+++ cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp Tue Oct  8 
15:42:44 2019
@@ -185,17 +185,6 @@ static void skipRawString(const char *
   }
 }
 
-static void skipString(const char *, const char *const End) {
-  assert(*First == '\'' || *First == '"' || *First == '<');
-  const char Terminator = *First == '<' ? '>' : *First;
-  for (++First; First != End && *First != Terminator; ++First)
-if (*First == '\\')
-  if (++First == End)
-return;
-  if (First != End)
-++First; // Finish off the string.
-}
-
 // Returns the length of EOL, either 0 (no end-of-line), 1 (\n) or 2 (\r\n)
 static unsigned isEOL(const char *First, const char *const End) {
   if (First == End)
@@ -206,6 +195,35 @@ static unsigned isEOL(const char *First,
   return !!isVerticalWhitespace(First[0]);
 }
 
+static void skipString(const char *, const char *const End) {
+  assert(*First == '\'' || *First == '"' || *First == '<');
+  const char Terminator = *First == '<' ? '>' : *First;
+  for (++First; First != End && *First != Terminator; ++First) {
+// String and character literals don't extend past the end of the line.
+if (isVerticalWhitespace(*First))
+  return;
+if (*First != '\\')
+  continue;
+// Skip past backslash to the next character. This ensures that the
+// character right after it is skipped as well, which matters if it's
+// the terminator.
+if (++First == End)
+  return;
+if (!isWhitespace(*First))
+  continue;
+// Whitespace after the backslash might indicate a line continuation.
+const char *FirstAfterBackslashPastSpace = First;
+skipOverSpaces(FirstAfterBackslashPastSpace, End);
+if (unsigned NLSize = isEOL(FirstAfterBackslashPastSpace, End)) {
+  // Advance the character pointer to the next line for the next
+  // iteration.
+  First = FirstAfterBackslashPastSpace + NLSize - 1;
+}
+  }
+  if (First != End)
+++First; // Finish off the string.
+}
+
 // Returns the length of the skipped newline
 static unsigned skipNewline(const char *, const char *End) {
   if (First == End)

Modified: cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp?rev=374127=374126=374127=diff
==
--- cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp 
(original)
+++ cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp Tue Oct 
 8 15:42:44 2019
@@ -594,6 +594,50 @@ TEST(MinimizeSourceToDependencyDirective
   EXPECT_STREQ("#pragma once\n#include \n", Out.data());
 }
 
+TEST(MinimizeSourceToDependencyDirectivesTest,
+ SkipLineStringCharLiteralsUntilNewline) {
+  SmallVector Out;
+
+  StringRef Source = R"(#if NEVER_ENABLED
+#define why(fmt, ...) #error don't try me
+#endif
+
+void foo();
+)";
+  ASSERT_FALSE(minimizeSourceToDependencyDirectives(Source, Out));
+  EXPECT_STREQ(
+  "#if NEVER_ENABLED\n#define why(fmt,...) #error don't try me\n#endif\n",
+  Out.data());
+
+  Source = R"(#if NEVER_ENABLED
+  #define why(fmt, ...) "quote dropped
+  #endif
+
+  void foo();
+  )";
+  ASSERT_FALSE(minimizeSourceToDependencyDirectives(Source, Out));
+  EXPECT_STREQ(
+  "#if NEVER_ENABLED\n#define why(fmt,...) \"quote dropped\n#endif\n",
+  Out.data());
+}
+
+TEST(MinimizeSourceToDependencyDirectivesTest,
+ SupportWhitespaceBeforeLineContinuationInStringSkipping) {
+  SmallVector Out;
+
+  StringRef Source = "#define X '\\ \t\nx'\nvoid foo() {}";
+  ASSERT_FALSE(minimizeSourceToDependencyDirectives(Source, Out));
+  EXPECT_STREQ("#define X '\\ \t\nx'\n", Out.data());
+
+  Source = 

r373007 - [clang-scan-deps] Allow continuation line backslashes followed by whitespace

2019-09-26 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Thu Sep 26 12:28:51 2019
New Revision: 373007

URL: http://llvm.org/viewvc/llvm-project?rev=373007=rev
Log:
[clang-scan-deps] Allow continuation line backslashes followed by whitespace
in the dependency source minimizer

Clang allows continuations that have whitespace between the backslash and the 
newline.
This patch ensures that the dependency source minimizer can handle the 
whitespace between
the backslash and the newline when looking for a line continuation.

Differential Revision: https://reviews.llvm.org/D68052

Modified:
cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp

Modified: cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp?rev=373007=373006=373007=diff
==
--- cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp (original)
+++ cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp Thu Sep 26 
12:28:51 2019
@@ -244,14 +244,20 @@ static void skipToNewlineRaw(const char
   }
 }
 
-static const char *reverseOverSpaces(const char *First, const char *Last) {
+static const char *findLastNonSpace(const char *First, const char *Last) {
   assert(First <= Last);
-  const char *PrevLast = Last;
-  while (First != Last && isHorizontalWhitespace(Last[-1])) {
-PrevLast = Last;
+  while (First != Last && isHorizontalWhitespace(Last[-1]))
 --Last;
-  }
-  return PrevLast;
+  return Last;
+}
+
+static const char *findFirstTrailingSpace(const char *First,
+  const char *Last) {
+  const char *LastNonSpace = findLastNonSpace(First, Last);
+  if (Last == LastNonSpace)
+return Last;
+  assert(isHorizontalWhitespace(LastNonSpace[0]));
+  return LastNonSpace + 1;
 }
 
 static void skipLineComment(const char *, const char *const End) {
@@ -385,7 +391,7 @@ void Minimizer::printToNewline(const cha
   }
 
   // Deal with "//..." and "/*...*/".
-  append(First, reverseOverSpaces(First, Last));
+  append(First, findFirstTrailingSpace(First, Last));
   First = Last;
 
   if (Last[1] == '/') {
@@ -400,15 +406,20 @@ void Minimizer::printToNewline(const cha
 } while (Last != End && !isVerticalWhitespace(*Last));
 
 // Print out the string.
-if (Last == End || Last == First || Last[-1] != '\\') {
-  append(First, reverseOverSpaces(First, Last));
+const char *LastBeforeTrailingSpace = findLastNonSpace(First, Last);
+if (Last == End || LastBeforeTrailingSpace == First ||
+LastBeforeTrailingSpace[-1] != '\\') {
+  append(First, LastBeforeTrailingSpace);
   First = Last;
   skipNewline(First, End);
   return;
 }
 
-// Print up to the backslash, backing up over spaces.
-append(First, reverseOverSpaces(First, Last - 1));
+// Print up to the backslash, backing up over spaces. Preserve at least one
+// space, as the space matters when tokens are separated by a line
+// continuation.
+append(First, findFirstTrailingSpace(
+  First, LastBeforeTrailingSpace - 1));
 
 First = Last;
 skipNewline(First, End);

Modified: cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp?rev=373007=373006=373007=diff
==
--- cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp 
(original)
+++ cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp Thu Sep 
26 12:28:51 2019
@@ -157,19 +157,19 @@ TEST(MinimizeSourceToDependencyDirective
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO(\t)\tcon \t tent\t", Out));
-  EXPECT_STREQ("#define MACRO() con \t tent\t\n", Out.data());
+  EXPECT_STREQ("#define MACRO() con \t tent\n", Out.data());
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO(\f)\fcon \f tent\f", Out));
-  EXPECT_STREQ("#define MACRO() con \f tent\f\n", Out.data());
+  EXPECT_STREQ("#define MACRO() con \f tent\n", Out.data());
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO(\v)\vcon \v tent\v", Out));
-  EXPECT_STREQ("#define MACRO() con \v tent\v\n", Out.data());
+  EXPECT_STREQ("#define MACRO() con \v tent\n", Out.data());
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO \t\v\f\v\t con\f\t\vtent\v\f \v", Out));
-  EXPECT_STREQ("#define MACRO con\f\t\vtent\v\n", Out.data());
+  EXPECT_STREQ("#define MACRO con\f\t\vtent\n", Out.data());
 }
 
 TEST(MinimizeSourceToDependencyDirectivesTest, DefineMultilineArgs) {
@@ -476,6 +476,17 @@ TEST(MinimizeSourceToDependencyDirective
   EXPECT_STREQ("#define GUA RD\n", Out.data());
 }
 

r372444 - [clang-scan-deps] strip the --serialize-diagnostics argument

2019-09-20 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Fri Sep 20 17:17:26 2019
New Revision: 372444

URL: http://llvm.org/viewvc/llvm-project?rev=372444=rev
Log:
[clang-scan-deps] strip the --serialize-diagnostics argument

This ensures that clang-scan-deps won't write out diagnostics when
scanning dependencies.

Added:
cfe/trunk/test/ClangScanDeps/Inputs/strip_diag_serialize.json
cfe/trunk/test/ClangScanDeps/strip_diag_serialize.cpp
Modified:
cfe/trunk/include/clang/Tooling/ArgumentsAdjusters.h
cfe/trunk/lib/Tooling/ArgumentsAdjusters.cpp
cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp

Modified: cfe/trunk/include/clang/Tooling/ArgumentsAdjusters.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/ArgumentsAdjusters.h?rev=372444=372443=372444=diff
==
--- cfe/trunk/include/clang/Tooling/ArgumentsAdjusters.h (original)
+++ cfe/trunk/include/clang/Tooling/ArgumentsAdjusters.h Fri Sep 20 17:17:26 
2019
@@ -43,6 +43,10 @@ ArgumentsAdjuster getClangSyntaxOnlyAdju
 /// arguments.
 ArgumentsAdjuster getClangStripOutputAdjuster();
 
+/// Gets an argument adjuster which removes command line arguments related to
+/// diagnostic serialization.
+ArgumentsAdjuster getClangStripSerializeDiagnosticAdjuster();
+
 /// Gets an argument adjuster which removes dependency-file
 /// related command line arguments.
 ArgumentsAdjuster getClangStripDependencyFileAdjuster();

Modified: cfe/trunk/lib/Tooling/ArgumentsAdjusters.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/ArgumentsAdjusters.cpp?rev=372444=372443=372444=diff
==
--- cfe/trunk/lib/Tooling/ArgumentsAdjusters.cpp (original)
+++ cfe/trunk/lib/Tooling/ArgumentsAdjusters.cpp Fri Sep 20 17:17:26 2019
@@ -57,6 +57,22 @@ ArgumentsAdjuster getClangStripOutputAdj
   };
 }
 
+ArgumentsAdjuster getClangStripSerializeDiagnosticAdjuster() {
+  return [](const CommandLineArguments , StringRef /*unused*/) {
+CommandLineArguments AdjustedArgs;
+for (size_t i = 0, e = Args.size(); i < e; ++i) {
+  StringRef Arg = Args[i];
+  if (Arg == "--serialize-diagnostics") {
+// Skip the diagnostic output argument.
+++i;
+continue;
+  }
+  AdjustedArgs.push_back(Args[i]);
+}
+return AdjustedArgs;
+  };
+}
+
 ArgumentsAdjuster getClangStripDependencyFileAdjuster() {
   return [](const CommandLineArguments , StringRef /*unused*/) {
 CommandLineArguments AdjustedArgs;

Added: cfe/trunk/test/ClangScanDeps/Inputs/strip_diag_serialize.json
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/ClangScanDeps/Inputs/strip_diag_serialize.json?rev=372444=auto
==
--- cfe/trunk/test/ClangScanDeps/Inputs/strip_diag_serialize.json (added)
+++ cfe/trunk/test/ClangScanDeps/Inputs/strip_diag_serialize.json Fri Sep 20 
17:17:26 2019
@@ -0,0 +1,7 @@
+[
+{
+  "directory": "DIR",
+  "command": "clang -E -fsyntax-only DIR/strip_diag_serialize_input.cpp 
--serialize-diagnostics /does/not/exist",
+  "file": "DIR/strip_diag_serialize_input.cpp"
+}
+]

Added: cfe/trunk/test/ClangScanDeps/strip_diag_serialize.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/ClangScanDeps/strip_diag_serialize.cpp?rev=372444=auto
==
--- cfe/trunk/test/ClangScanDeps/strip_diag_serialize.cpp (added)
+++ cfe/trunk/test/ClangScanDeps/strip_diag_serialize.cpp Fri Sep 20 17:17:26 
2019
@@ -0,0 +1,11 @@
+// RUN: rm -rf %t.dir
+// RUN: rm -rf %t.cdb
+// RUN: mkdir -p %t.dir
+// RUN: cp %s %t.dir/strip_diag_serialize_input.cpp
+// RUN: sed -e "s|DIR|%/t.dir|g" %S/Inputs/strip_diag_serialize.json > %t.cdb
+//
+// RUN: clang-scan-deps -compilation-database %t.cdb 2>&1 | FileCheck %s
+// CHECK-NOT: unable to open file
+// CHECK: strip_diag_serialize_input.cpp
+
+#warning "diagnostic"

Modified: cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp?rev=372444=372443=372444=diff
==
--- cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp (original)
+++ cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp Fri Sep 20 17:17:26 2019
@@ -266,6 +266,8 @@ int main(int argc, const char **argv) {
 AdjustedArgs.push_back("-Wno-error");
 return AdjustedArgs;
   });
+  AdjustingCompilations->appendArgumentsAdjuster(
+  tooling::getClangStripSerializeDiagnosticAdjuster());
 
   SharedStream Errs(llvm::errs());
   // Print out the dependency results to STDOUT by default.


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r372360 - Fix for stringized function-macro args continued across lines

2019-09-19 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Thu Sep 19 15:39:24 2019
New Revision: 372360

URL: http://llvm.org/viewvc/llvm-project?rev=372360=rev
Log:
Fix for stringized function-macro args continued across lines

In case of certain #define'd macros, there's a space just before line 
continuation
that the minimized-source lexer was missing to include, resulting in invalid 
stringize.

Patch by: kousikk (Kousik Kumar)

Differential Revision: https://reviews.llvm.org/D67635

Modified:
cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp

Modified: cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp?rev=372360=372359=372360=diff
==
--- cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp (original)
+++ cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp Thu Sep 19 
15:39:24 2019
@@ -246,9 +246,12 @@ static void skipToNewlineRaw(const char
 
 static const char *reverseOverSpaces(const char *First, const char *Last) {
   assert(First <= Last);
-  while (First != Last && isHorizontalWhitespace(Last[-1]))
+  const char *PrevLast = Last;
+  while (First != Last && isHorizontalWhitespace(Last[-1])) {
+PrevLast = Last;
 --Last;
-  return Last;
+  }
+  return PrevLast;
 }
 
 static void skipLineComment(const char *, const char *const End) {

Modified: cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp?rev=372360=372359=372360=diff
==
--- cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp 
(original)
+++ cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp Thu Sep 
19 15:39:24 2019
@@ -157,19 +157,19 @@ TEST(MinimizeSourceToDependencyDirective
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO(\t)\tcon \t tent\t", Out));
-  EXPECT_STREQ("#define MACRO() con \t tent\n", Out.data());
+  EXPECT_STREQ("#define MACRO() con \t tent\t\n", Out.data());
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO(\f)\fcon \f tent\f", Out));
-  EXPECT_STREQ("#define MACRO() con \f tent\n", Out.data());
+  EXPECT_STREQ("#define MACRO() con \f tent\f\n", Out.data());
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO(\v)\vcon \v tent\v", Out));
-  EXPECT_STREQ("#define MACRO() con \v tent\n", Out.data());
+  EXPECT_STREQ("#define MACRO() con \v tent\v\n", Out.data());
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO \t\v\f\v\t con\f\t\vtent\v\f \v", Out));
-  EXPECT_STREQ("#define MACRO con\f\t\vtent\n", Out.data());
+  EXPECT_STREQ("#define MACRO con\f\t\vtent\v\n", Out.data());
 }
 
 TEST(MinimizeSourceToDependencyDirectivesTest, DefineMultilineArgs) {
@@ -187,7 +187,7 @@ TEST(MinimizeSourceToDependencyDirective
"call((a),  \\\n"
" (b))",
Out));
-  EXPECT_STREQ("#define MACRO(a,b) call((a),(b))\n", Out.data());
+  EXPECT_STREQ("#define MACRO(a,b) call((a), (b))\n", Out.data());
 }
 
 TEST(MinimizeSourceToDependencyDirectivesTest,
@@ -200,7 +200,17 @@ TEST(MinimizeSourceToDependencyDirective
"call((a),  \\\r"
" (b))",
Out));
-  EXPECT_STREQ("#define MACRO(a,b) call((a),(b))\n", Out.data());
+  EXPECT_STREQ("#define MACRO(a,b) call((a), (b))\n", Out.data());
+}
+
+TEST(MinimizeSourceToDependencyDirectivesTest, DefineMultilineArgsStringize) {
+  SmallVector Out;
+
+  ASSERT_FALSE(minimizeSourceToDependencyDirectives("#define MACRO(a,b) \\\n"
+"#a \\\n"
+"#b",
+Out));
+  EXPECT_STREQ("#define MACRO(a,b) #a #b\n", Out.data());
 }
 
 TEST(MinimizeSourceToDependencyDirectivesTest,
@@ -213,7 +223,7 @@ TEST(MinimizeSourceToDependencyDirective
"call((a),  \\\r\n"
" (b))",
Out));
-  EXPECT_STREQ("#define MACRO(a,b) call((a),(b))\n", Out.data());
+  EXPECT_STREQ("#define MACRO(a,b) call((a), (b))\n", Out.data());
 }
 
 TEST(MinimizeSourceToDependencyDirectivesTest,
@@ -226,7 +236,7 @@ TEST(MinimizeSourceToDependencyDirective
"call((a),  \\\n\r"
   

r371903 - [clang-scan-deps] Fix for headers having the same name as a directory

2019-09-13 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Fri Sep 13 15:12:02 2019
New Revision: 371903

URL: http://llvm.org/viewvc/llvm-project?rev=371903=rev
Log:
[clang-scan-deps] Fix for headers having the same name as a directory

Scan deps tool crashes when called on a C++ file, containing an include
that has the same name as a directory.
The tool crashes since it finds foo/dir and tries to read that as a file and 
fails.

Patch by: kousikk (Kousik Kumar)

Differential Revision: https://reviews.llvm.org/D67091

Added:
cfe/trunk/test/ClangScanDeps/Inputs/foodir
cfe/trunk/test/ClangScanDeps/Inputs/headerwithdirname.json
cfe/trunk/test/ClangScanDeps/headerwithdirname.cpp
Modified:

cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp

Modified: 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h?rev=371903=371902=371903=diff
==
--- 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
 (original)
+++ 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
 Fri Sep 13 15:12:02 2019
@@ -56,6 +56,9 @@ public:
   /// \returns True if the entry is valid.
   bool isValid() const { return !MaybeStat || MaybeStat->isStatusKnown(); }
 
+  /// \returns True if the current entry points to a directory.
+  bool isDirectory() const { return MaybeStat && MaybeStat->isDirectory(); }
+
   /// \returns The error or the file's contents.
   llvm::ErrorOr getContents() const {
 if (!MaybeStat)

Modified: 
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp?rev=371903=371902=371903=diff
==
--- cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
(original)
+++ cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
Fri Sep 13 15:12:02 2019
@@ -193,6 +193,9 @@ private:
 llvm::ErrorOr>
 createFile(const CachedFileSystemEntry *Entry,
ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings) {
+  if (Entry->isDirectory())
+return llvm::ErrorOr>(
+std::make_error_code(std::errc::is_a_directory));
   llvm::ErrorOr Contents = Entry->getContents();
   if (!Contents)
 return Contents.getError();

Added: cfe/trunk/test/ClangScanDeps/Inputs/foodir
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/ClangScanDeps/Inputs/foodir?rev=371903=auto
==
--- cfe/trunk/test/ClangScanDeps/Inputs/foodir (added)
+++ cfe/trunk/test/ClangScanDeps/Inputs/foodir Fri Sep 13 15:12:02 2019
@@ -0,0 +1 @@
+// A C++ header with same name as that of a directory in the include path.

Added: cfe/trunk/test/ClangScanDeps/Inputs/headerwithdirname.json
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/ClangScanDeps/Inputs/headerwithdirname.json?rev=371903=auto
==
--- cfe/trunk/test/ClangScanDeps/Inputs/headerwithdirname.json (added)
+++ cfe/trunk/test/ClangScanDeps/Inputs/headerwithdirname.json Fri Sep 13 
15:12:02 2019
@@ -0,0 +1,7 @@
+[
+{
+  "directory": "DIR",
+  "command": "clang -c -IDIR -IDIR/foodir -IInputs 
DIR/headerwithdirname_input.cpp",
+  "file": "DIR/headerwithdirname_input.cpp"
+}
+]

Added: cfe/trunk/test/ClangScanDeps/headerwithdirname.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/ClangScanDeps/headerwithdirname.cpp?rev=371903=auto
==
--- cfe/trunk/test/ClangScanDeps/headerwithdirname.cpp (added)
+++ cfe/trunk/test/ClangScanDeps/headerwithdirname.cpp Fri Sep 13 15:12:02 2019
@@ -0,0 +1,17 @@
+// RUN: rm -rf %t.dir
+// RUN: rm -rf %t.dir/foodir
+// RUN: rm -rf %t.cdb
+// RUN: mkdir -p %t.dir
+// RUN: mkdir -p %t.dir/foodir
+// RUN: cp %s %t.dir/headerwithdirname_input.cpp
+// RUN: mkdir %t.dir/Inputs
+// RUN: cp %S/Inputs/foodir %t.dir/Inputs/foodir
+// RUN: sed -e "s|DIR|%/t.dir|g" %S/Inputs/headerwithdirname.json > %t.cdb
+//
+// RUN: clang-scan-deps -compilation-database %t.cdb -j 1 | FileCheck %s
+
+#include 
+
+// CHECK: headerwithdirname_input.o
+// CHECK-NEXT: headerwithdirname_input.cpp
+// CHECK-NEXT: Inputs{{/|\\}}foodir


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r371759 - NFC, add missing cl::cat option category to clang-scan-deps options to ensure they show up in -help

2019-09-12 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Thu Sep 12 12:00:32 2019
New Revision: 371759

URL: http://llvm.org/viewvc/llvm-project?rev=371759=rev
Log:
NFC, add missing cl::cat option category to clang-scan-deps options to ensure 
they show up in -help

Modified:
cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp

Modified: cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp?rev=371759=371758=371759=diff
==
--- cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp (original)
+++ cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp Thu Sep 12 12:00:32 2019
@@ -150,13 +150,14 @@ static llvm::cl::opt ScanM
 clEnumValN(ScanningMode::CanonicalPreprocessing, "preprocess",
"The set of dependencies is computed by preprocessing the "
"unmodified source files")),
-llvm::cl::init(ScanningMode::MinimizedSourcePreprocessing));
+llvm::cl::init(ScanningMode::MinimizedSourcePreprocessing),
+llvm::cl::cat(DependencyScannerCategory));
 
 llvm::cl::opt
 NumThreads("j", llvm::cl::Optional,
llvm::cl::desc("Number of worker threads to use (default: use "
   "all concurrent threads)"),
-   llvm::cl::init(0));
+   llvm::cl::init(0), llvm::cl::cat(DependencyScannerCategory));
 
 llvm::cl::opt
 CompilationDB("compilation-database",


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r371751 - [clang-scan-deps] remove dots and dots dots from the reported file dependency paths

2019-09-12 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Thu Sep 12 11:03:24 2019
New Revision: 371751

URL: http://llvm.org/viewvc/llvm-project?rev=371751=rev
Log:
[clang-scan-deps] remove dots and dots dots from the reported file dependency 
paths

This resolves differences observed on LLVM + Clang when running the comparison 
between canonical
dependencies (full preprocessing, no file manager reused), and dependencies 
obtained
when the file manager was reused between the full preprocessing invocations.

Modified:
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
cfe/trunk/test/ClangScanDeps/Inputs/subframework_header_dir_symlink_cdb.json

Modified: cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp?rev=371751=371750=371751=diff
==
--- cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
(original)
+++ cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp Thu 
Sep 12 11:03:24 2019
@@ -30,8 +30,12 @@ public:
   : DependencyFileGenerator(*Opts), Opts(std::move(Opts)), C(C) {}
 
   void finishedMainFile(DiagnosticsEngine ) override {
-for (const auto  : getDependencies())
-  C.handleFileDependency(*Opts, File);
+llvm::SmallString<256> CanonPath;
+for (const auto  : getDependencies()) {
+  CanonPath = File;
+  llvm::sys::path::remove_dots(CanonPath, /*remove_dot_dot=*/true);
+  C.handleFileDependency(*Opts, CanonPath);
+}
   }
 
 private:

Modified: 
cfe/trunk/test/ClangScanDeps/Inputs/subframework_header_dir_symlink_cdb.json
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/ClangScanDeps/Inputs/subframework_header_dir_symlink_cdb.json?rev=371751=371750=371751=diff
==
--- 
cfe/trunk/test/ClangScanDeps/Inputs/subframework_header_dir_symlink_cdb.json 
(original)
+++ 
cfe/trunk/test/ClangScanDeps/Inputs/subframework_header_dir_symlink_cdb.json 
Thu Sep 12 11:03:24 2019
@@ -6,7 +6,7 @@
 },
 {
   "directory": "DIR",
-  "command": "clang -E DIR/subframework_header_dir_symlink_input2.m 
-FInputs/frameworks -iframework Inputs/frameworks_symlink",
+  "command": "clang -E DIR/subframework_header_dir_symlink_input2.m 
-FInputs/frameworks -iframework 
Inputs/frameworks_symlink/../frameworks_symlink",
   "file": "DIR/subframework_header_dir_symlink_input2.m"
 }
 ]


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r371664 - [clang-scan-deps] cast Result to ErrorOr> explicitly to avoid s390x-linux buildbot failure

2019-09-11 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Sep 11 14:00:13 2019
New Revision: 371664

URL: http://llvm.org/viewvc/llvm-project?rev=371664=rev
Log:
[clang-scan-deps] cast Result to ErrorOr> explicitly to 
avoid s390x-linux buildbot failure

Modified:
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp

Modified: 
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp?rev=371664=371663=371664=diff
==
--- cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
(original)
+++ cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
Wed Sep 11 14:00:13 2019
@@ -203,7 +203,8 @@ createFile(const CachedFileSystemEntry *
   if (!Entry->getPPSkippedRangeMapping().empty() && PPSkipMappings)
 (*PPSkipMappings)[Result->getBufferPtr()] =
 >getPPSkippedRangeMapping();
-  return Result;
+  return llvm::ErrorOr>(
+  std::unique_ptr(std::move(Result)));
 }
 
 } // end anonymous namespace


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r371656 - [clang-scan-deps] add skip excluded conditional preprocessor block preprocessing optimization

2019-09-11 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Sep 11 13:40:31 2019
New Revision: 371656

URL: http://llvm.org/viewvc/llvm-project?rev=371656=rev
Log:
[clang-scan-deps] add skip excluded conditional preprocessor block 
preprocessing optimization

This commit adds an optimization to clang-scan-deps and clang's preprocessor 
that skips excluded preprocessor
blocks by bumping the lexer pointer, and not lexing the tokens until reaching 
appropriate #else/#endif directive.
The skip positions and lexer offsets are computed when the file is minimized, 
directly from the minimized tokens.

On an 18-core iMacPro with macOS Catalina Beta I got 10-15% speed-up from this 
optimization when running clang-scan-deps on
the compilation database for a recent LLVM and Clang (3511 files).

Differential Revision: https://reviews.llvm.org/D67127

Added:

cfe/trunk/include/clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h
Modified:
cfe/trunk/include/clang/Lex/DependencyDirectivesSourceMinimizer.h
cfe/trunk/include/clang/Lex/Lexer.h
cfe/trunk/include/clang/Lex/Preprocessor.h
cfe/trunk/include/clang/Lex/PreprocessorOptions.h

cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h

cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningService.h

cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
cfe/trunk/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
cfe/trunk/lib/Lex/Lexer.cpp
cfe/trunk/lib/Lex/PPDirectives.cpp
cfe/trunk/lib/Lex/Preprocessor.cpp
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningService.cpp
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
cfe/trunk/test/ClangScanDeps/regular_cdb.cpp
cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp
cfe/trunk/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp

Modified: cfe/trunk/include/clang/Lex/DependencyDirectivesSourceMinimizer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/DependencyDirectivesSourceMinimizer.h?rev=371656=371655=371656=diff
==
--- cfe/trunk/include/clang/Lex/DependencyDirectivesSourceMinimizer.h (original)
+++ cfe/trunk/include/clang/Lex/DependencyDirectivesSourceMinimizer.h Wed Sep 
11 13:40:31 2019
@@ -66,6 +66,24 @@ struct Token {
   Token(TokenKind K, int Offset) : K(K), Offset(Offset) {}
 };
 
+/// Simplified token range to track the range of a potentially skippable PP
+/// directive.
+struct SkippedRange {
+  /// Offset into the output byte stream of where the skipped directive begins.
+  int Offset;
+
+  /// The number of bytes that can be skipped before the preprocessing must
+  /// resume.
+  int Length;
+};
+
+/// Computes the potential source ranges that can be skipped by the 
preprocessor
+/// when skipping a directive like #if, #ifdef or #elsif.
+///
+/// \returns false on success, true on error.
+bool computeSkippedRanges(ArrayRef Input,
+  llvm::SmallVectorImpl );
+
 } // end namespace minimize_source_to_dependency_directives
 
 /// Minimize the input down to the preprocessor directives that might have

Modified: cfe/trunk/include/clang/Lex/Lexer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/Lexer.h?rev=371656=371655=371656=diff
==
--- cfe/trunk/include/clang/Lex/Lexer.h (original)
+++ cfe/trunk/include/clang/Lex/Lexer.h Wed Sep 11 13:40:31 2019
@@ -265,6 +265,21 @@ public:
   /// Return the current location in the buffer.
   const char *getBufferLocation() const { return BufferPtr; }
 
+  /// Returns the current lexing offset.
+  unsigned getCurrentBufferOffset() {
+assert(BufferPtr >= BufferStart && "Invalid buffer state");
+return BufferPtr - BufferStart;
+  }
+
+  /// Skip over \p NumBytes bytes.
+  ///
+  /// If the skip is successful, the next token will be lexed from the new
+  /// offset. The lexer also assumes that we skipped to the start of the line.
+  ///
+  /// \returns true if the skip failed (new offset would have been past the
+  /// end of the buffer), false otherwise.
+  bool skipOver(unsigned NumBytes);
+
   /// Stringify - Convert the specified string into a C string by i) escaping
   /// '\\' and " characters and ii) replacing newline character(s) with "\\n".
   /// If Charify is true, this escapes the ' character instead of ".

Modified: cfe/trunk/include/clang/Lex/Preprocessor.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/Preprocessor.h?rev=371656=371655=371656=diff
==
--- cfe/trunk/include/clang/Lex/Preprocessor.h (original)
+++ cfe/trunk/include/clang/Lex/Preprocessor.h Wed Sep 11 13:40:31 2019
@@ -28,6 +28,7 @@
 #include 

r370562 - Introduce a DirectoryEntryRef that stores both a reference and an

2019-08-30 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Fri Aug 30 18:26:04 2019
New Revision: 370562

URL: http://llvm.org/viewvc/llvm-project?rev=370562=rev
Log:
Introduce a DirectoryEntryRef that stores both a reference and an
accessed name to the directory entry

This commit introduces a parallel API that returns a DirectoryEntryRef
to the FileManager, similar to the parallel FileEntryRef API. All
uses will have to be update in follow-up patches. The immediate use of the new 
API in this
patch fixes the issue where a file manager was reused in clang-scan-deps,
but reported an different file path whenever a framework lookup was done 
through a symlink.

Differential Revision: https://reviews.llvm.org/D67026

Modified:
cfe/trunk/include/clang/Basic/FileManager.h
cfe/trunk/include/clang/Lex/DirectoryLookup.h
cfe/trunk/lib/Basic/FileManager.cpp
cfe/trunk/lib/Frontend/InitHeaderSearch.cpp
cfe/trunk/lib/Lex/HeaderSearch.cpp
cfe/trunk/lib/Lex/PPDirectives.cpp
cfe/trunk/test/ClangScanDeps/Inputs/subframework_header_dir_symlink_cdb.json
cfe/trunk/test/ClangScanDeps/subframework_header_dir_symlink.m
cfe/trunk/unittests/Lex/HeaderSearchTest.cpp
cfe/trunk/unittests/Lex/PPCallbacksTest.cpp

Modified: cfe/trunk/include/clang/Basic/FileManager.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/FileManager.h?rev=370562=370561=370562=diff
==
--- cfe/trunk/include/clang/Basic/FileManager.h (original)
+++ cfe/trunk/include/clang/Basic/FileManager.h Fri Aug 30 18:26:04 2019
@@ -45,12 +45,31 @@ class FileSystemStatCache;
 class DirectoryEntry {
   friend class FileManager;
 
+  // FIXME: We should not be storing a directory entry name here.
   StringRef Name; // Name of the directory.
 
 public:
   StringRef getName() const { return Name; }
 };
 
+/// A reference to a \c DirectoryEntry  that includes the name of the directory
+/// as it was accessed by the FileManager's client.
+class DirectoryEntryRef {
+public:
+  const DirectoryEntry () const { return *Entry->getValue(); }
+
+  StringRef getName() const { return Entry->getKey(); }
+
+private:
+  friend class FileManager;
+
+  DirectoryEntryRef(
+  llvm::StringMapEntry> *Entry)
+  : Entry(Entry) {}
+
+  const llvm::StringMapEntry> *Entry;
+};
+
 /// Cached information about one file (either on disk
 /// or in the virtual file system).
 ///
@@ -259,6 +278,29 @@ public:
   /// virtual).
   ///
   /// This returns a \c std::error_code if there was an error reading the
+  /// directory. On success, returns the reference to the directory entry
+  /// together with the exact path that was used to access a file by a
+  /// particular call to getDirectoryRef.
+  ///
+  /// \param CacheFailure If true and the file does not exist, we'll cache
+  /// the failure to find this file.
+  llvm::Expected getDirectoryRef(StringRef DirName,
+bool CacheFailure = true);
+
+  /// Get a \c DirectoryEntryRef if it exists, without doing anything on error.
+  llvm::Optional
+  getOptionalDirectoryRef(StringRef DirName, bool CacheFailure = true) {
+return llvm::expectedToOptional(getDirectoryRef(DirName, CacheFailure));
+  }
+
+  /// Lookup, cache, and verify the specified directory (real or
+  /// virtual).
+  ///
+  /// This function is deprecated and will be removed at some point in the
+  /// future, new clients should use
+  ///  \c getDirectoryRef.
+  ///
+  /// This returns a \c std::error_code if there was an error reading the
   /// directory. If there is no error, the DirectoryEntry is guaranteed to be
   /// non-NULL.
   ///

Modified: cfe/trunk/include/clang/Lex/DirectoryLookup.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/DirectoryLookup.h?rev=370562=370561=370562=diff
==
--- cfe/trunk/include/clang/Lex/DirectoryLookup.h (original)
+++ cfe/trunk/include/clang/Lex/DirectoryLookup.h Fri Aug 30 18:26:04 2019
@@ -36,14 +36,17 @@ public:
 LT_HeaderMap
   };
 private:
-  union {  // This union is discriminated by isHeaderMap.
+  union DLU { // This union is discriminated by isHeaderMap.
 /// Dir - This is the actual directory that we're referring to for a normal
 /// directory or a framework.
-const DirectoryEntry *Dir;
+DirectoryEntryRef Dir;
 
 /// Map - This is the HeaderMap if this is a headermap lookup.
 ///
 const HeaderMap *Map;
+
+DLU(DirectoryEntryRef Dir) : Dir(Dir) {}
+DLU(const HeaderMap *Map) : Map(Map) {}
   } u;
 
   /// DirCharacteristic - The type of directory this is: this is an instance of
@@ -62,24 +65,18 @@ private:
   unsigned SearchedAllModuleMaps : 1;
 
 public:
-  /// DirectoryLookup ctor - Note that this ctor *does not take ownership* of
-  /// 'dir'.
-  DirectoryLookup(const DirectoryEntry *dir, SrcMgr::CharacteristicKind DT,
+  /// This ctor *does not take 

r370493 - [clang-scan-deps] NFC, remove outdated implementation comment

2019-08-30 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Fri Aug 30 10:34:22 2019
New Revision: 370493

URL: http://llvm.org/viewvc/llvm-project?rev=370493=rev
Log:
[clang-scan-deps] NFC, remove outdated implementation comment

There's no need to purge symlinked entries in the FileManager,
as the new FileEntryRef API allows us to compute dependencies more
accurately when the FileManager is reused.

Modified:
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp

Modified: cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp?rev=370493=370492=370493=diff
==
--- cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
(original)
+++ cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp Fri 
Aug 30 10:34:22 2019
@@ -87,7 +87,6 @@ public:
 
 // Use the dependency scanning optimized file system if we can.
 if (DepFS) {
-  // FIXME: Purge the symlink entries from the stat cache in the FM.
   const CompilerInvocation  = Compiler.getInvocation();
   // Add any filenames that were explicity passed in the build settings and
   // that might be opened, as we want to ensure we don't run source


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r370425 - [clang-scan-deps] NFC, refactor the DependencyScanningWorker to use a consumer

2019-08-29 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Thu Aug 29 18:25:57 2019
New Revision: 370425

URL: http://llvm.org/viewvc/llvm-project?rev=370425=rev
Log:
[clang-scan-deps] NFC, refactor the DependencyScanningWorker to use a consumer
to report the dependencies to the client

This will allow the scanner to report modular dependencies to the consumer.
This will also allow the scanner to accept regular cc1 clang invocations, e.g.
in an implementation of a libclang C API for clang-scan-deps, that I will add
follow-up patches for in the future.

Modified:

cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp

Modified: 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h?rev=370425=370424=370425=diff
==
--- 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h 
(original)
+++ 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h 
Thu Aug 29 18:25:57 2019
@@ -19,12 +19,25 @@
 #include 
 
 namespace clang {
+
+class DependencyOutputOptions;
+
 namespace tooling {
 namespace dependencies {
 
 class DependencyScanningService;
 class DependencyScanningWorkerFilesystem;
 
+class DependencyConsumer {
+public:
+  virtual ~DependencyConsumer() {}
+
+  virtual void handleFileDependency(const DependencyOutputOptions ,
+StringRef Filename) = 0;
+
+  // FIXME: Add support for reporting modular dependencies.
+};
+
 /// An individual dependency scanning worker that is able to run on its own
 /// thread.
 ///
@@ -35,15 +48,16 @@ class DependencyScanningWorker {
 public:
   DependencyScanningWorker(DependencyScanningService );
 
-  /// Print out the dependency information into a string using the dependency
-  /// file format that is specified in the options (-MD is the default) and
-  /// return it.
+  /// Run the dependency scanning tool for a given clang driver invocation (as
+  /// specified for the given Input in the CDB), and report the discovered
+  /// dependencies to the provided consumer.
   ///
   /// \returns A \c StringError with the diagnostic output if clang errors
-  /// occurred, dependency file contents otherwise.
-  llvm::Expected getDependencyFile(const std::string ,
-StringRef WorkingDirectory,
-const CompilationDatabase 
);
+  /// occurred, success otherwise.
+  llvm::Error computeDependencies(const std::string ,
+  StringRef WorkingDirectory,
+  const CompilationDatabase ,
+  DependencyConsumer );
 
 private:
   IntrusiveRefCntPtr DiagOpts;

Modified: cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp?rev=370425=370424=370425=diff
==
--- cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
(original)
+++ cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp Thu 
Aug 29 18:25:57 2019
@@ -21,21 +21,21 @@ using namespace dependencies;
 
 namespace {
 
-/// Prints out all of the gathered dependencies into a string.
-class DependencyPrinter : public DependencyFileGenerator {
+/// Forwards the gatherered dependencies to the consumer.
+class DependencyConsumerForwarder : public DependencyFileGenerator {
 public:
-  DependencyPrinter(std::unique_ptr Opts,
-std::string )
-  : DependencyFileGenerator(*Opts), Opts(std::move(Opts)), S(S) {}
+  DependencyConsumerForwarder(std::unique_ptr Opts,
+  DependencyConsumer )
+  : DependencyFileGenerator(*Opts), Opts(std::move(Opts)), C(C) {}
 
   void finishedMainFile(DiagnosticsEngine ) override {
-llvm::raw_string_ostream OS(S);
-outputDependencyFile(OS);
+for (const auto  : getDependencies())
+  C.handleFileDependency(*Opts, File);
   }
 
 private:
   std::unique_ptr Opts;
-  std::string 
+  DependencyConsumer 
 };
 
 /// A proxy file system that doesn't call `chdir` when changing the working
@@ -65,10 +65,9 @@ private:
 class DependencyScanningAction : public tooling::ToolAction {
 public:
   DependencyScanningAction(
-  StringRef WorkingDirectory, std::string ,
+  StringRef WorkingDirectory, DependencyConsumer ,
   llvm::IntrusiveRefCntPtr DepFS)
-  : WorkingDirectory(WorkingDirectory),
-DependencyFileContents(DependencyFileContents),
+  : WorkingDirectory(WorkingDirectory), Consumer(Consumer),
 

r370420 - [clang-scan-deps] reuse the file manager across invocations of

2019-08-29 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Thu Aug 29 15:56:38 2019
New Revision: 370420

URL: http://llvm.org/viewvc/llvm-project?rev=370420=rev
Log:
[clang-scan-deps] reuse the file manager across invocations of
the dependency scanner on a single worker thread

This behavior can be controlled using the new `-reuse-filemanager` 
clang-scan-deps
option. By default the file manager is reused.

The added test/ClangScanDeps/symlink.cpp is able to pass with
the reused filemanager after the related FileEntryRef changes
landed earlier. The test test/ClangScanDeps/subframework_header_dir_symlink.m
still fails when the file manager is reused (I run the FileCheck with not to
make it PASS). I will address this in a follow-up patch that improves
the DirectoryEntry name modelling in the FileManager.

Added:
cfe/trunk/test/ClangScanDeps/Inputs/subframework_header_dir_symlink_cdb.json
cfe/trunk/test/ClangScanDeps/Inputs/symlink_cdb.json
cfe/trunk/test/ClangScanDeps/subframework_header_dir_symlink.m
cfe/trunk/test/ClangScanDeps/symlink.cpp
Modified:

cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningService.h

cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
cfe/trunk/include/clang/Tooling/Tooling.h
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningService.cpp
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
cfe/trunk/lib/Tooling/Tooling.cpp
cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp

Modified: 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningService.h?rev=370420=370419=370420=diff
==
--- 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningService.h 
(original)
+++ 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningService.h 
Thu Aug 29 15:56:38 2019
@@ -34,16 +34,19 @@ enum class ScanningMode {
 /// the invidual dependency scanning workers.
 class DependencyScanningService {
 public:
-  DependencyScanningService(ScanningMode Mode);
+  DependencyScanningService(ScanningMode Mode, bool ReuseFileManager = true);
 
   ScanningMode getMode() const { return Mode; }
 
+  bool canReuseFileManager() const { return ReuseFileManager; }
+
   DependencyScanningFilesystemSharedCache () {
 return SharedCache;
   }
 
 private:
   const ScanningMode Mode;
+  const bool ReuseFileManager;
   /// The global file system cache.
   DependencyScanningFilesystemSharedCache SharedCache;
 };

Modified: 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h?rev=370420=370419=370420=diff
==
--- 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h 
(original)
+++ 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h 
Thu Aug 29 15:56:38 2019
@@ -54,6 +54,9 @@ private:
   /// dependencies. This filesystem persists accross multiple compiler
   /// invocations.
   llvm::IntrusiveRefCntPtr DepFS;
+  /// The file manager that is reused accross multiple invocations by this
+  /// worker. If null, the file manager will not be reused.
+  llvm::IntrusiveRefCntPtr Files;
 };
 
 } // end namespace dependencies

Modified: cfe/trunk/include/clang/Tooling/Tooling.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Tooling.h?rev=370420=370419=370420=diff
==
--- cfe/trunk/include/clang/Tooling/Tooling.h (original)
+++ cfe/trunk/include/clang/Tooling/Tooling.h Thu Aug 29 15:56:38 2019
@@ -349,12 +349,15 @@ public:
   /// clang modules.
   /// \param BaseFS VFS used for all underlying file accesses when running the
   /// tool.
+  /// \param Files The file manager to use for underlying file operations when
+  /// running the tool.
   ClangTool(const CompilationDatabase ,
 ArrayRef SourcePaths,
 std::shared_ptr PCHContainerOps =
 std::make_shared(),
 IntrusiveRefCntPtr BaseFS =
-llvm::vfs::getRealFileSystem());
+llvm::vfs::getRealFileSystem(),
+IntrusiveRefCntPtr Files = nullptr);
 
   ~ClangTool();
 

Modified: cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningService.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningService.cpp?rev=370420=370419=370420=diff
==
--- cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningService.cpp 
(original)
+++ 

[clang-tools-extra] r370096 - Remove clang-tidy-vs from clang-tools-extra (PR41791)

2019-08-27 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Tue Aug 27 11:36:08 2019
New Revision: 370096

URL: http://llvm.org/viewvc/llvm-project?rev=370096=rev
Log:
Remove clang-tidy-vs from clang-tools-extra (PR41791)

The clang-tidy-vs visual studio plugin in clang-tools-extra contains a
security vulnerability in the YamlDotNet package [1]. I posted to cfe-dev [2],
asking if there was anyone who was interested in updating the the plugin
to address the vulnerability. Reid mentioned that Zach (the original committer),
said that there's another plugin (Clang Power Tools) that provides clang-tidy 
support,
with additional extra features, so it would be ok to remove clang-tidy-vs.

This commit removes the plugin to address the security vulnerability, and adds
a section to the release notes that mentions that the plugin was removed, and
suggests to use Clang Power Tools.

Fixes PR 41791.

[1]: https://nvd.nist.gov/vuln/detail/CVE-2018-1000210
[2]: http://lists.llvm.org/pipermail/cfe-dev/2019-August/063196.html

Differential Revision: https://reviews.llvm.org/D66813

Removed:
clang-tools-extra/trunk/clang-tidy-vs/
Modified:
clang-tools-extra/trunk/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst

Modified: clang-tools-extra/trunk/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/CMakeLists.txt?rev=370096=370095=370096=diff
==
--- clang-tools-extra/trunk/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/CMakeLists.txt Tue Aug 27 11:36:08 2019
@@ -4,7 +4,6 @@ add_subdirectory(clang-apply-replacement
 add_subdirectory(clang-reorder-fields)
 add_subdirectory(modularize)
 add_subdirectory(clang-tidy)
-add_subdirectory(clang-tidy-vs)
 
 add_subdirectory(clang-change-namespace)
 add_subdirectory(clang-doc)

Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=370096=370095=370096=diff
==
--- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original)
+++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Tue Aug 27 11:36:08 2019
@@ -104,3 +104,11 @@ Improvements to pp-trace
 
 
 The improvements are...
+
+Clang-tidy visual studio plugin
+---
+
+The clang-tidy-vs plugin has been removed from clang, as
+it's no longer maintained. Users should migrate to
+`Clang Power Tools 
`_
+instead.


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r370093 - [driver][xray] fix the macOS support checker by supporting -macos

2019-08-27 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Tue Aug 27 11:26:36 2019
New Revision: 370093

URL: http://llvm.org/viewvc/llvm-project?rev=370093=rev
Log:
[driver][xray] fix the macOS support checker by supporting -macos
triple in addition to -darwin

The previous check incorrectly checked for macOS support by
allowing -darwin triples only, and -macos triple was not supported.

Differential Revision: https://reviews.llvm.org/D61758

Added:
cfe/trunk/test/Driver/XRay/xray-instrument-macos.c
Modified:
cfe/trunk/lib/Driver/XRayArgs.cpp

Modified: cfe/trunk/lib/Driver/XRayArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/XRayArgs.cpp?rev=370093=370092=370093=diff
==
--- cfe/trunk/lib/Driver/XRayArgs.cpp (original)
+++ cfe/trunk/lib/Driver/XRayArgs.cpp Tue Aug 27 11:26:36 2019
@@ -52,7 +52,7 @@ XRayArgs::XRayArgs(const ToolChain ,
 } else if (Triple.isOSFreeBSD() ||
Triple.isOSOpenBSD() ||
Triple.isOSNetBSD() ||
-   Triple.getOS() == llvm::Triple::Darwin) {
+   Triple.isMacOSX()) {
   if (Triple.getArch() != llvm::Triple::x86_64) {
 D.Diag(diag::err_drv_clang_unsupported)
 << (std::string(XRayInstrumentOption) + " on " + Triple.str());

Added: cfe/trunk/test/Driver/XRay/xray-instrument-macos.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/XRay/xray-instrument-macos.c?rev=370093=auto
==
--- cfe/trunk/test/Driver/XRay/xray-instrument-macos.c (added)
+++ cfe/trunk/test/Driver/XRay/xray-instrument-macos.c Tue Aug 27 11:26:36 2019
@@ -0,0 +1,4 @@
+// RUN: %clang -o /dev/null -v -fxray-instrument -target 
x86_64-apple-macos10.11 -c %s
+// RUN: %clang -o /dev/null -v -fxray-instrument -target x86_64-apple-darwin15 
-c %s
+// REQUIRES-ANY: x86_64, x86_64h
+typedef int a;


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r370081 - Use FileEntryRef for PPCallbacks::HasInclude

2019-08-27 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Tue Aug 27 10:32:42 2019
New Revision: 370081

URL: http://llvm.org/viewvc/llvm-project?rev=370081=rev
Log:
Use FileEntryRef for PPCallbacks::HasInclude

This fixes the issue where a filename dependendency was missing if the file that
was referenced with __has_include() was accessed through a symlink in an 
earlier run,
if the file manager was reused between runs.

Modified:
clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.cpp
clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.h

Modified: clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.cpp?rev=370081=370080=370081=diff
==
--- clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.cpp Tue 
Aug 27 10:32:42 2019
@@ -210,7 +210,7 @@ void ExpandModularHeadersPPCallbacks::Pr
   parseToLocation(Loc);
 }
 void ExpandModularHeadersPPCallbacks::HasInclude(SourceLocation Loc, StringRef,
- bool, const FileEntry *,
+ bool, Optional,
  SrcMgr::CharacteristicKind) {
   parseToLocation(Loc);
 }

Modified: clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.h?rev=370081=370080=370081=diff
==
--- clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.h 
(original)
+++ clang-tools-extra/trunk/clang-tidy/ExpandModularHeadersPPCallbacks.h Tue 
Aug 27 10:32:42 2019
@@ -83,7 +83,7 @@ private:
   void PragmaDiagnosticPop(SourceLocation Loc, StringRef) override;
   void PragmaDiagnostic(SourceLocation Loc, StringRef, diag::Severity,
 StringRef) override;
-  void HasInclude(SourceLocation Loc, StringRef, bool, const FileEntry *,
+  void HasInclude(SourceLocation Loc, StringRef, bool, Optional ,
   SrcMgr::CharacteristicKind) override;
   void PragmaOpenCLExtension(SourceLocation NameLoc, const IdentifierInfo *,
  SourceLocation StateLoc, unsigned) override;


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r370081 - Use FileEntryRef for PPCallbacks::HasInclude

2019-08-27 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Tue Aug 27 10:32:42 2019
New Revision: 370081

URL: http://llvm.org/viewvc/llvm-project?rev=370081=rev
Log:
Use FileEntryRef for PPCallbacks::HasInclude

This fixes the issue where a filename dependendency was missing if the file that
was referenced with __has_include() was accessed through a symlink in an 
earlier run,
if the file manager was reused between runs.

Modified:
cfe/trunk/include/clang/Lex/PPCallbacks.h
cfe/trunk/lib/Frontend/DependencyFile.cpp
cfe/trunk/lib/Lex/PPMacroExpansion.cpp
cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp

Modified: cfe/trunk/include/clang/Lex/PPCallbacks.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/PPCallbacks.h?rev=370081=370080=370081=diff
==
--- cfe/trunk/include/clang/Lex/PPCallbacks.h (original)
+++ cfe/trunk/include/clang/Lex/PPCallbacks.h Tue Aug 27 10:32:42 2019
@@ -307,7 +307,7 @@ public:
   /// Hook called when a '__has_include' or '__has_include_next' directive is
   /// read.
   virtual void HasInclude(SourceLocation Loc, StringRef FileName, bool 
IsAngled,
-  const FileEntry *File,
+  Optional File,
   SrcMgr::CharacteristicKind FileType) {}
 
   /// Hook called when a source range is skipped.
@@ -489,7 +489,7 @@ public:
   }
 
   void HasInclude(SourceLocation Loc, StringRef FileName, bool IsAngled,
-  const FileEntry *File,
+  Optional File,
   SrcMgr::CharacteristicKind FileType) override {
 First->HasInclude(Loc, FileName, IsAngled, File, FileType);
 Second->HasInclude(Loc, FileName, IsAngled, File, FileType);

Modified: cfe/trunk/lib/Frontend/DependencyFile.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/DependencyFile.cpp?rev=370081=370080=370081=diff
==
--- cfe/trunk/lib/Frontend/DependencyFile.cpp (original)
+++ cfe/trunk/lib/Frontend/DependencyFile.cpp Tue Aug 27 10:32:42 2019
@@ -83,7 +83,7 @@ struct DepCollectorPPCallbacks : public
   }
 
   void HasInclude(SourceLocation Loc, StringRef SpelledFilename, bool IsAngled,
-  const FileEntry *File,
+  Optional File,
   SrcMgr::CharacteristicKind FileType) override {
 if (!File)
   return;

Modified: cfe/trunk/lib/Lex/PPMacroExpansion.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPMacroExpansion.cpp?rev=370081=370080=370081=diff
==
--- cfe/trunk/lib/Lex/PPMacroExpansion.cpp (original)
+++ cfe/trunk/lib/Lex/PPMacroExpansion.cpp Tue Aug 27 10:32:42 2019
@@ -1219,8 +1219,7 @@ static bool EvaluateHasIncludeCommon(Tok
 if (File)
   FileType =
   PP.getHeaderSearchInfo().getFileDirFlavor(>getFileEntry());
-Callbacks->HasInclude(FilenameLoc, Filename, isAngled,
-  File ? >getFileEntry() : nullptr, FileType);
+Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);
   }
 
   // Get the result value.  A result of true means the file exists.

Modified: cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp?rev=370081=370080=370081=diff
==
--- cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp (original)
+++ cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp Tue Aug 27 10:32:42 
2019
@@ -161,5 +161,40 @@ TEST(DependencyScanner, ScanDepsReuseFil
   EXPECT_EQ(convert_to_slash(Deps[5]), "/root/header.h");
 }
 
+TEST(DependencyScanner, ScanDepsReuseFilemanagerHasInclude) {
+  std::vector Compilation = {"-c", "-E", "-MT", "test.cpp.o"};
+  StringRef CWD = "/root";
+  FixedCompilationDatabase CDB(CWD, Compilation);
+
+  auto VFS = new llvm::vfs::InMemoryFileSystem();
+  VFS->setCurrentWorkingDirectory(CWD);
+  auto Sept = llvm::sys::path::get_separator();
+  std::string HeaderPath = llvm::formatv("{0}root{0}header.h", Sept);
+  std::string SymlinkPath = llvm::formatv("{0}root{0}symlink.h", Sept);
+  std::string TestPath = llvm::formatv("{0}root{0}test.cpp", Sept);
+
+  VFS->addFile(HeaderPath, 0, llvm::MemoryBuffer::getMemBuffer("\n"));
+  VFS->addHardLink(SymlinkPath, HeaderPath);
+  VFS->addFile(
+  TestPath, 0,
+  llvm::MemoryBuffer::getMemBuffer("#if __has_include(\"header.h\") && "
+   
"__has_include(\"symlink.h\")\n#endif"));
+
+  ClangTool Tool(CDB, {"test.cpp", "test.cpp"},
+ std::make_shared(), VFS);
+  Tool.clearArgumentsAdjusters();
+  std::vector Deps;
+  TestDependencyScanningAction Action(Deps);
+  Tool.run();
+  using llvm::sys::path::convert_to_slash;
+  ASSERT_EQ(Deps.size(), 6u);
+  

[clang-tools-extra] r370004 - Fix clangd's IndexAction for FileSkipped API update

2019-08-26 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Mon Aug 26 18:36:00 2019
New Revision: 370004

URL: http://llvm.org/viewvc/llvm-project?rev=370004=rev
Log:
Fix clangd's IndexAction for FileSkipped API update

Modified:
clang-tools-extra/trunk/clangd/index/IndexAction.cpp

Modified: clang-tools-extra/trunk/clangd/index/IndexAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/IndexAction.cpp?rev=370004=370003=370004=diff
==
--- clang-tools-extra/trunk/clangd/index/IndexAction.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/IndexAction.cpp Mon Aug 26 18:36:00 
2019
@@ -103,10 +103,10 @@ public:
   }
 
   // Sanity check to ensure we have already populated a skipped file.
-  void FileSkipped(const FileEntry , const Token ,
+  void FileSkipped(const FileEntryRef , const Token ,
SrcMgr::CharacteristicKind FileType) override {
 #ifndef NDEBUG
-auto URI = toURI();
+auto URI = toURI(());
 if (!URI)
   return;
 auto I = IG.try_emplace(*URI);


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r369998 - Use FileEntryRef for PPCallbacks::FileSkipped

2019-08-26 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Mon Aug 26 18:03:25 2019
New Revision: 369998

URL: http://llvm.org/viewvc/llvm-project?rev=369998=rev
Log:
Use FileEntryRef for PPCallbacks::FileSkipped

This fixes the issue where a filename dependendency was missing if the file that
was skipped was included through a symlink in an earlier run, if the file
manager was reused between runs.

Modified:
cfe/trunk/include/clang/Lex/PPCallbacks.h
cfe/trunk/lib/Frontend/DependencyFile.cpp
cfe/trunk/lib/Frontend/Rewrite/InclusionRewriter.cpp
cfe/trunk/lib/Lex/PPDirectives.cpp
cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp

Modified: cfe/trunk/include/clang/Lex/PPCallbacks.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/PPCallbacks.h?rev=369998=369997=369998=diff
==
--- cfe/trunk/include/clang/Lex/PPCallbacks.h (original)
+++ cfe/trunk/include/clang/Lex/PPCallbacks.h Mon Aug 26 18:03:25 2019
@@ -57,10 +57,9 @@ public:
   /// \param FilenameTok The file name token in \#include "FileName" directive
   /// or macro expanded file name token from \#include MACRO(PARAMS) directive.
   /// Note that FilenameTok contains corresponding quotes/angles symbols.
-  virtual void FileSkipped(const FileEntry ,
+  virtual void FileSkipped(const FileEntryRef ,
const Token ,
-   SrcMgr::CharacteristicKind FileType) {
-  }
+   SrcMgr::CharacteristicKind FileType) {}
 
   /// Callback invoked whenever an inclusion directive results in a
   /// file-not-found error.
@@ -390,8 +389,7 @@ public:
 Second->FileChanged(Loc, Reason, FileType, PrevFID);
   }
 
-  void FileSkipped(const FileEntry ,
-   const Token ,
+  void FileSkipped(const FileEntryRef , const Token ,
SrcMgr::CharacteristicKind FileType) override {
 First->FileSkipped(SkippedFile, FilenameTok, FileType);
 Second->FileSkipped(SkippedFile, FilenameTok, FileType);

Modified: cfe/trunk/lib/Frontend/DependencyFile.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/DependencyFile.cpp?rev=369998=369997=369998=diff
==
--- cfe/trunk/lib/Frontend/DependencyFile.cpp (original)
+++ cfe/trunk/lib/Frontend/DependencyFile.cpp Mon Aug 26 18:03:25 2019
@@ -59,7 +59,7 @@ struct DepCollectorPPCallbacks : public
 /*IsModuleFile*/false, /*IsMissing*/false);
   }
 
-  void FileSkipped(const FileEntry , const Token ,
+  void FileSkipped(const FileEntryRef , const Token ,
SrcMgr::CharacteristicKind FileType) override {
 StringRef Filename =
 llvm::sys::path::remove_leading_dotslash(SkippedFile.getName());

Modified: cfe/trunk/lib/Frontend/Rewrite/InclusionRewriter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/Rewrite/InclusionRewriter.cpp?rev=369998=369997=369998=diff
==
--- cfe/trunk/lib/Frontend/Rewrite/InclusionRewriter.cpp (original)
+++ cfe/trunk/lib/Frontend/Rewrite/InclusionRewriter.cpp Mon Aug 26 18:03:25 
2019
@@ -70,7 +70,7 @@ private:
   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
FileID PrevFID) override;
-  void FileSkipped(const FileEntry , const Token ,
+  void FileSkipped(const FileEntryRef , const Token ,
SrcMgr::CharacteristicKind FileType) override;
   void InclusionDirective(SourceLocation HashLoc, const Token ,
   StringRef FileName, bool IsAngled,
@@ -169,8 +169,8 @@ void InclusionRewriter::FileChanged(Sour
 
 /// Called whenever an inclusion is skipped due to canonical header protection
 /// macros.
-void InclusionRewriter::FileSkipped(const FileEntry &/*SkippedFile*/,
-const Token &/*FilenameTok*/,
+void InclusionRewriter::FileSkipped(const FileEntryRef & /*SkippedFile*/,
+const Token & /*FilenameTok*/,
 SrcMgr::CharacteristicKind /*FileType*/) {
   assert(LastInclusionLocation.isValid() &&
  "A file, that wasn't found via an inclusion directive, was skipped");

Modified: cfe/trunk/lib/Lex/PPDirectives.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPDirectives.cpp?rev=369998=369997=369998=diff
==
--- cfe/trunk/lib/Lex/PPDirectives.cpp (original)
+++ cfe/trunk/lib/Lex/PPDirectives.cpp Mon Aug 26 18:03:25 2019
@@ -2029,7 +2029,7 @@ Preprocessor::ImportAction Preprocessor:
 RelativePath, Action == Import ? SuggestedModule.getModule() : nullptr,
 FileCharacter);
 if (Action == Skip && File)
-  

[clang-tools-extra] r369998 - Use FileEntryRef for PPCallbacks::FileSkipped

2019-08-26 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Mon Aug 26 18:03:25 2019
New Revision: 369998

URL: http://llvm.org/viewvc/llvm-project?rev=369998=rev
Log:
Use FileEntryRef for PPCallbacks::FileSkipped

This fixes the issue where a filename dependendency was missing if the file that
was skipped was included through a symlink in an earlier run, if the file
manager was reused between runs.

Modified:
clang-tools-extra/trunk/clangd/ClangdUnit.cpp
clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=369998=369997=369998=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Mon Aug 26 18:03:25 2019
@@ -268,7 +268,9 @@ private:
 FilenameTok.getEndLoc()),
   File, "SearchPath", "RelPath", /*Imported=*/nullptr, Inc.FileKind);
   if (File)
-Delegate->FileSkipped(*File, FilenameTok, Inc.FileKind);
+// FIXME: Use correctly named FileEntryRef.
+Delegate->FileSkipped(FileEntryRef(File->getName(), *File), 
FilenameTok,
+  Inc.FileKind);
   else {
 llvm::SmallString<1> UnusedRecovery;
 Delegate->FileNotFound(WrittenFilename, UnusedRecovery);

Modified: clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp?rev=369998=369997=369998=diff
==
--- clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp (original)
+++ clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp Mon Aug 26 18:03:25 
2019
@@ -112,11 +112,11 @@ void PPCallbacksTracker::FileChanged(Sou
 
 // Callback invoked whenever a source file is skipped as the result
 // of header guard optimization.
-void PPCallbacksTracker::FileSkipped(const FileEntry ,
+void PPCallbacksTracker::FileSkipped(const FileEntryRef ,
  const Token ,
  SrcMgr::CharacteristicKind FileType) {
   beginCallback("FileSkipped");
-  appendArgument("ParentFile", );
+  appendArgument("ParentFile", ());
   appendArgument("FilenameTok", FilenameTok);
   appendArgument("FileType", FileType, CharacteristicKindStrings);
 }

Modified: clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h?rev=369998=369997=369998=diff
==
--- clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h (original)
+++ clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h Mon Aug 26 18:03:25 
2019
@@ -89,7 +89,7 @@ public:
   void FileChanged(SourceLocation Loc, PPCallbacks::FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
FileID PrevFID = FileID()) override;
-  void FileSkipped(const FileEntry , const Token ,
+  void FileSkipped(const FileEntryRef , const Token ,
SrcMgr::CharacteristicKind FileType) override;
   bool FileNotFound(llvm::StringRef FileName,
 llvm::SmallVectorImpl ) override;


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r369956 - Fix gen-cdb-fragment test for Windows

2019-08-26 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Mon Aug 26 13:02:40 2019
New Revision: 369956

URL: http://llvm.org/viewvc/llvm-project?rev=369956=rev
Log:
Fix gen-cdb-fragment test for Windows

Windows bots didn't seem to like the empty argument, so I rewrote the test.

Modified:
cfe/trunk/test/Driver/gen-cdb-fragment.c

Modified: cfe/trunk/test/Driver/gen-cdb-fragment.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/gen-cdb-fragment.c?rev=369956=369955=369956=diff
==
--- cfe/trunk/test/Driver/gen-cdb-fragment.c (original)
+++ cfe/trunk/test/Driver/gen-cdb-fragment.c Mon Aug 26 13:02:40 2019
@@ -15,10 +15,10 @@
 // RUN: %clang -target x86_64-apple-macos10.15 -S %s -o -  
-gen-cdb-fragment-path %t.cdb
 // RUN: ls %t.cdb | FileCheck --check-prefix=CHECK-LS %s
 
-// Empty path is equivalent to '.'
+// Working directory arg is respected.
 // RUN: rm -rf %t.cdb
 // RUN: mkdir %t.cdb
-// RUN: %clang -target x86_64-apple-macos10.15 -working-directory %t.cdb -c %s 
-o -  -gen-cdb-fragment-path ""
+// RUN: %clang -target x86_64-apple-macos10.15 -working-directory %t.cdb -c %s 
-o -  -gen-cdb-fragment-path "."
 // RUN: ls %t.cdb | FileCheck --check-prefix=CHECK-LS %s
 // RUN: cat %t.cdb/*.json | FileCheck --check-prefix=CHECK-CWD %s
 // CHECK-CWD: "directory": "{{.*}}.cdb"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r369938 - [driver] add a new option `-gen-cdb-fragment-path` to emit

2019-08-26 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Mon Aug 26 10:59:41 2019
New Revision: 369938

URL: http://llvm.org/viewvc/llvm-project?rev=369938=rev
Log:
[driver] add a new option `-gen-cdb-fragment-path` to emit
a fragment of a compilation database for each compilation

This patch adds a new option called -gen-cdb-fragment-path to the driver,
which can be used to specify a directory path to which clang can emit a fragment
of a CDB for each compilation it needs to invoke.

This option emits the same CDB contents as -MJ, and will be ignored if -MJ is 
specified.

Differential Revision: https://reviews.llvm.org/D66555

Added:
cfe/trunk/test/Driver/gen-cdb-fragment.c
Modified:
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Driver/ToolChains/Clang.h

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=369938=369937=369938=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Mon Aug 26 10:59:41 2019
@@ -280,6 +280,8 @@ def arcmt_migrate_emit_arc_errors : Flag
   Flags<[CC1Option]>;
 def gen_reproducer: Flag<["-"], "gen-reproducer">, InternalDebugOpt,
   HelpText<"Auto-generates preprocessed source files and a reproduction 
script">;
+def gen_cdb_fragment_path: Separate<["-"], "gen-cdb-fragment-path">, 
InternalDebugOpt,
+  HelpText<"Emit a compilation database fragment to the specified directory">;
 
 def _migrate : Flag<["--"], "migrate">, Flags<[DriverOption]>,
   HelpText<"Run the migrator">;

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=369938=369937=369938=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Mon Aug 26 10:59:41 2019
@@ -2013,13 +2013,14 @@ void Clang::DumpCompilationDatabase(Comp
 CompilationDatabase = std::move(File);
   }
   auto  = *CompilationDatabase;
-  SmallString<128> Buf;
-  if (llvm::sys::fs::current_path(Buf))
-Buf = ".";
-  CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
+  auto CWD = D.getVFS().getCurrentWorkingDirectory();
+  if (!CWD)
+CWD = ".";
+  CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
   CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
+  SmallString<128> Buf;
   Buf = "-x";
   Buf += types::getTypeName(Input.getType());
   CDB << ", \"" << escape(Buf) << "\"";
@@ -2037,6 +2038,8 @@ void Clang::DumpCompilationDatabase(Comp
 // Skip writing dependency output and the compilation database itself.
 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
   continue;
+if (O.getID() == options::OPT_gen_cdb_fragment_path)
+  continue;
 // Skip inputs.
 if (O.getKind() == Option::InputClass)
   continue;
@@ -2051,6 +2054,40 @@ void Clang::DumpCompilationDatabase(Comp
   CDB << ", \"" << escape(Buf) << "\"]},\n";
 }
 
+void Clang::DumpCompilationDatabaseFragmentToDir(
+StringRef Dir, Compilation , StringRef Target, const InputInfo ,
+const InputInfo , const llvm::opt::ArgList ) const {
+  // If this is a dry run, do not create the compilation database file.
+  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
+return;
+
+  if (CompilationDatabase)
+DumpCompilationDatabase(C, "", Target, Output, Input, Args);
+
+  SmallString<256> Path = Dir;
+  const auto  = C.getDriver();
+  Driver.getVFS().makeAbsolute(Path);
+  auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
+  if (Err) {
+Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
+return;
+  }
+
+  llvm::sys::path::append(
+  Path,
+  Twine(llvm::sys::path::filename(Input.getFilename())) + "..json");
+  int FD;
+  SmallString<256> TempPath;
+  Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath);
+  if (Err) {
+Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
+return;
+  }
+  CompilationDatabase =
+  std::make_unique(FD, /*shouldClose=*/true);
+  DumpCompilationDatabase(C, "", Target, Output, Input, Args);
+}
+
 static void CollectArgsForIntegratedAssembler(Compilation ,
   const ArgList ,
   ArgStringList ,
@@ -3495,6 +3532,11 @@ void Clang::ConstructJob(Compilation ,
   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
 Args.ClaimAllArgs(options::OPT_MJ);
+  } else if (const Arg *GenCDBFragment =
+

r369832 - Re-enable DependencyScannerTest on windows with the right fixes

2019-08-23 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Fri Aug 23 18:53:40 2019
New Revision: 369832

URL: http://llvm.org/viewvc/llvm-project?rev=369832=rev
Log:
Re-enable DependencyScannerTest on windows with the right fixes

It should now pass.

Modified:
cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp

Modified: cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp?rev=369832=369831=369832=diff
==
--- cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp (original)
+++ cfe/trunk/unittests/Tooling/DependencyScannerTest.cpp Fri Aug 23 18:53:40 
2019
@@ -16,6 +16,7 @@
 #include "clang/Tooling/CompilationDatabase.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/TargetSelect.h"
@@ -26,8 +27,6 @@
 namespace clang {
 namespace tooling {
 
-#ifndef _WIN32
-
 namespace {
 
 /// Prints out all of the gathered dependencies into a string.
@@ -82,9 +81,14 @@ TEST(DependencyScanner, ScanDepsReuseFil
 
   auto VFS = new llvm::vfs::InMemoryFileSystem();
   VFS->setCurrentWorkingDirectory(CWD);
-  VFS->addFile("/root/header.h", 0, llvm::MemoryBuffer::getMemBuffer("\n"));
-  VFS->addHardLink("/root/symlink.h", "/root/header.h");
-  VFS->addFile("/root/test.cpp", 0,
+  auto Sept = llvm::sys::path::get_separator();
+  std::string HeaderPath = llvm::formatv("{0}root{0}header.h", Sept);
+  std::string SymlinkPath = llvm::formatv("{0}root{0}symlink.h", Sept);
+  std::string TestPath = llvm::formatv("{0}root{0}test.cpp", Sept);
+
+  VFS->addFile(HeaderPath, 0, llvm::MemoryBuffer::getMemBuffer("\n"));
+  VFS->addHardLink(SymlinkPath, HeaderPath);
+  VFS->addFile(TestPath, 0,
llvm::MemoryBuffer::getMemBuffer(
"#include \"symlink.h\"\n#include \"header.h\"\n"));
 
@@ -94,11 +98,12 @@ TEST(DependencyScanner, ScanDepsReuseFil
   std::vector Deps;
   TestDependencyScanningAction Action(Deps);
   Tool.run();
+  using llvm::sys::path::convert_to_slash;
   // The first invocation should return dependencies in order of access.
   ASSERT_EQ(Deps.size(), 3u);
-  EXPECT_EQ(Deps[0], "/root/test.cpp");
-  EXPECT_EQ(Deps[1], "/root/symlink.h");
-  EXPECT_EQ(Deps[2], "/root/header.h");
+  EXPECT_EQ(convert_to_slash(Deps[0]), "/root/test.cpp");
+  EXPECT_EQ(convert_to_slash(Deps[1]), "/root/symlink.h");
+  EXPECT_EQ(convert_to_slash(Deps[2]), "/root/header.h");
 
   // The file manager should still have two FileEntries, as one file is a
   // hardlink.
@@ -109,14 +114,12 @@ TEST(DependencyScanner, ScanDepsReuseFil
   Tool.run();
   // The second invocation should have the same order of dependencies.
   ASSERT_EQ(Deps.size(), 3u);
-  EXPECT_EQ(Deps[0], "/root/test.cpp");
-  EXPECT_EQ(Deps[1], "/root/symlink.h");
-  EXPECT_EQ(Deps[2], "/root/header.h");
+  EXPECT_EQ(convert_to_slash(Deps[0]), "/root/test.cpp");
+  EXPECT_EQ(convert_to_slash(Deps[1]), "/root/symlink.h");
+  EXPECT_EQ(convert_to_slash(Deps[2]), "/root/header.h");
 
   EXPECT_EQ(Files.getNumUniqueRealFiles(), 2u);
 }
 
-#endif
-
 } // end namespace tooling
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   4   5   6   7   >