[PATCH] D59481: [clangd] Count number of references while merging RefSlabs inside FileIndex

2019-05-09 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 198770.
kadircet marked 7 inline comments as done.
kadircet added a comment.

- Address comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59481/new/

https://reviews.llvm.org/D59481

Files:
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/FileIndex.h
  clang-tools-extra/clangd/index/IndexAction.cpp
  clang-tools-extra/clangd/indexer/IndexerMain.cpp
  clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
  clang-tools-extra/clangd/unittests/FileIndexTests.cpp

Index: clang-tools-extra/clangd/unittests/FileIndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/FileIndexTests.cpp
+++ clang-tools-extra/clangd/unittests/FileIndexTests.cpp
@@ -45,6 +45,7 @@
   return llvm::StringRef(arg.Definition.FileURI) == U;
 }
 MATCHER_P(QName, N, "") { return (arg.Scope + arg.Name).str() == N; }
+MATCHER_P(NumReferences, N, "") { return arg.References == N; }
 
 namespace clang {
 namespace clangd {
@@ -81,7 +82,7 @@
   FileSymbols FS;
   EXPECT_THAT(runFuzzyFind(*FS.buildIndex(IndexType::Light), ""), IsEmpty());
 
-  FS.update("f1", numSlab(1, 3), refSlab(SymbolID("1"), "f1.cc"));
+  FS.update("f1", numSlab(1, 3), refSlab(SymbolID("1"), "f1.cc"), false);
   EXPECT_THAT(runFuzzyFind(*FS.buildIndex(IndexType::Light), ""),
   UnorderedElementsAre(QName("1"), QName("2"), QName("3")));
   EXPECT_THAT(getRefs(*FS.buildIndex(IndexType::Light), SymbolID("1")),
@@ -90,8 +91,8 @@
 
 TEST(FileSymbolsTest, Overlap) {
   FileSymbols FS;
-  FS.update("f1", numSlab(1, 3), nullptr);
-  FS.update("f2", numSlab(3, 5), nullptr);
+  FS.update("f1", numSlab(1, 3), nullptr, false);
+  FS.update("f2", numSlab(3, 5), nullptr, false);
   for (auto Type : {IndexType::Light, IndexType::Heavy})
 EXPECT_THAT(runFuzzyFind(*FS.buildIndex(Type), ""),
 UnorderedElementsAre(QName("1"), QName("2"), QName("3"),
@@ -110,8 +111,8 @@
   auto X2 = symbol("x");
   X2.Definition.FileURI = "file:///x2";
 
-  FS.update("f1", OneSymboSlab(X1), nullptr);
-  FS.update("f2", OneSymboSlab(X2), nullptr);
+  FS.update("f1", OneSymboSlab(X1), nullptr, false);
+  FS.update("f2", OneSymboSlab(X2), nullptr, false);
   for (auto Type : {IndexType::Light, IndexType::Heavy})
 EXPECT_THAT(
 runFuzzyFind(*FS.buildIndex(Type, DuplicateHandling::Merge), "x"),
@@ -123,14 +124,14 @@
   FileSymbols FS;
 
   SymbolID ID("1");
-  FS.update("f1", numSlab(1, 3), refSlab(ID, "f1.cc"));
+  FS.update("f1", numSlab(1, 3), refSlab(ID, "f1.cc"), false);
 
   auto Symbols = FS.buildIndex(IndexType::Light);
   EXPECT_THAT(runFuzzyFind(*Symbols, ""),
   UnorderedElementsAre(QName("1"), QName("2"), QName("3")));
   EXPECT_THAT(getRefs(*Symbols, ID), RefsAre({FileURI("f1.cc")}));
 
-  FS.update("f1", nullptr, nullptr);
+  FS.update("f1", nullptr, nullptr, false);
   auto Empty = FS.buildIndex(IndexType::Light);
   EXPECT_THAT(runFuzzyFind(*Empty, ""), IsEmpty());
   EXPECT_THAT(getRefs(*Empty, ID), ElementsAre());
@@ -366,6 +367,33 @@
   RefsAre({RefRange(Main.range())}));
 }
 
+TEST(FileSymbolsTest, CountReferencesNoRefSlabs) {
+  FileSymbols FS;
+  FS.update("f1", numSlab(1, 3), nullptr, true);
+  FS.update("f2", numSlab(1, 3), nullptr, false);
+  EXPECT_THAT(
+  runFuzzyFind(*FS.buildIndex(IndexType::Light, DuplicateHandling::Merge),
+   ""),
+  UnorderedElementsAre(AllOf(QName("1"), NumReferences(0u)),
+   AllOf(QName("2"), NumReferences(0u)),
+   AllOf(QName("3"), NumReferences(0u;
+}
+
+TEST(FileSymbolsTest, CountReferencesWithRefSlabs) {
+  FileSymbols FS;
+  FS.update("f1cpp", numSlab(1, 3), refSlab(SymbolID("1"), "f1.cpp"), true);
+  FS.update("f1h", numSlab(1, 3), refSlab(SymbolID("1"), "f1.h"), false);
+  FS.update("f2cpp", numSlab(1, 3), refSlab(SymbolID("2"), "f2.cpp"), true);
+  FS.update("f2h", numSlab(1, 3), refSlab(SymbolID("2"), "f2.h"), false);
+  FS.update("f3cpp", numSlab(1, 3), refSlab(SymbolID("3"), "f3.cpp"), true);
+  FS.update("f3h", numSlab(1, 3), refSlab(SymbolID("3"), "f3.h"), false);
+  EXPECT_THAT(
+  runFuzzyFind(*FS.buildIndex(IndexType::Light, DuplicateHandling::Merge),
+   ""),
+  UnorderedElementsAre(AllOf(QName("1"), NumReferences(1u)),
+   AllOf(QName("2"), NumReferences(1u)),
+   AllOf(QName("3"), NumReferences(1u;
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
+++ clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
@@ -32,6 +32,7 @@
   return !arg.IsTU && !arg.URI.empty() && arg.Digest

[PATCH] D41911: [clangd] Include scanner that finds compile commands for headers.

2019-05-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added a comment.

Context here, this patch is over a year old and predates the work on 
heuristically picking a compile command from another file in the CDB.

I don't think anyone has concrete plans to revive this, the heuristics work 
well enough and often enough. I should probably have abandoned this patch, 
sorry for the time lost in detailed comments.

However there's certainly some value in indexing the include graph and/or 
determining main-file/header pairs.
e.g. to improve switchsourceheader, to enable cross-file refactorings like 
"out-line implementation". And maybe to improve compile command accuracy too.

This patch was pretty narrowly tailored at getting compile commands quickly, if 
we developed this approach it should probably be more general purpose, part of 
the index, and maybe take symbol declaration/definition into account rather 
than just #includes.




Comment at: clangd/IncludeScanner.cpp:131
+  IgnoringDiagConsumer IgnoreDiags;
+  // XXX the VFS working directory is global state, this is unsafe.
+  Cmd.VFS->setCurrentWorkingDirectory(Cmd.Directory);

klimek wrote:
> I assume that's a note to you that you want to change this?
This has since been fixed, it's no longer global state :-)



Comment at: clangd/IncludeScanner.cpp:159
+  // When reusing flags, we add an explicit `-x cpp` to override the extension.
+  // TODO: copying CompilerInvocation would avoid this, and is more robust.
+  if (std::find(Cmd.CommandLine.begin(), Cmd.CommandLine.end(), "-x") ==

klimek wrote:
> Wondering why we can't use one of the tooling abstractions here...
As far as I can tell, the only abstraction Tooling offers here is 
CompileCommand, the only way to robustly manipulate it is through the Driver 
(the semantics here are too subtle for brute-force string manipulation). 
InterpolatingCompilationDatabase does this, but doesn't expose the primitives 
publicly. It could if there was a need.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D41911/new/

https://reviews.llvm.org/D41911



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


[PATCH] D60827: [rename] Deduplicate symbol occurrences

2019-05-09 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet requested changes to this revision.
kadircet added a comment.
This revision now requires changes to proceed.

Note that the bug has been fixed with D61596  
incidentally


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60827/new/

https://reviews.llvm.org/D60827



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


[PATCH] D61566: Fix for bug 41747: AST Printer doesn't print nested name specifier for out of scope record definitions

2019-05-09 Thread Stepan Dyatkovskiy via Phabricator via cfe-commits
dyatkovskiy updated this revision to Diff 198771.
dyatkovskiy added a comment.

Patch updates per review remarks


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61566/new/

https://reviews.llvm.org/D61566

Files:
  clang/lib/AST/DeclPrinter.cpp
  clang/test/AST/ast-print-record-decl.c


Index: clang/test/AST/ast-print-record-decl.c
===
--- clang/test/AST/ast-print-record-decl.c
+++ clang/test/AST/ast-print-record-decl.c
@@ -289,3 +289,21 @@
 
 // A tag decl group in the tag decl's own member list is exercised in
 // defSelfRef above.
+
+#ifdef __cplusplus
+// PRINT-CXX-LABEL: outOfRecordDef
+void outOfRecordDef () {
+
+  // PRINT-CXX-NEXT: struct DeclEnclosing {
+  // PRINT-CXX-NEXT: struct DeclMember;
+  // PRINT-CXX-NEXT: };
+  struct DeclEnclosing {
+struct DeclMember;
+  };
+
+  // PRINT-CXX-NEXT: struct DeclEnclosing::DeclMember {
+  // PRINT-CXX-NEXT: };
+  struct DeclEnclosing::DeclMember {
+  };
+}
+#endif
Index: clang/lib/AST/DeclPrinter.cpp
===
--- clang/lib/AST/DeclPrinter.cpp
+++ clang/lib/AST/DeclPrinter.cpp
@@ -953,7 +953,12 @@
   prettyPrintAttributes(D);
 
   if (D->getIdentifier()) {
-Out << ' ' << *D;
+Out << ' ';
+
+if (const NestedNameSpecifier *Q = D->getQualifier())
+  Q->print(Out, Policy);
+
+Out << *D;
 
 if (auto S = dyn_cast(D))
   printTemplateArguments(S->getTemplateArgs(), S->getTemplateParameters());


Index: clang/test/AST/ast-print-record-decl.c
===
--- clang/test/AST/ast-print-record-decl.c
+++ clang/test/AST/ast-print-record-decl.c
@@ -289,3 +289,21 @@
 
 // A tag decl group in the tag decl's own member list is exercised in
 // defSelfRef above.
+
+#ifdef __cplusplus
+// PRINT-CXX-LABEL: outOfRecordDef
+void outOfRecordDef () {
+
+  // PRINT-CXX-NEXT: struct DeclEnclosing {
+  // PRINT-CXX-NEXT: struct DeclMember;
+  // PRINT-CXX-NEXT: };
+  struct DeclEnclosing {
+struct DeclMember;
+  };
+
+  // PRINT-CXX-NEXT: struct DeclEnclosing::DeclMember {
+  // PRINT-CXX-NEXT: };
+  struct DeclEnclosing::DeclMember {
+  };
+}
+#endif
Index: clang/lib/AST/DeclPrinter.cpp
===
--- clang/lib/AST/DeclPrinter.cpp
+++ clang/lib/AST/DeclPrinter.cpp
@@ -953,7 +953,12 @@
   prettyPrintAttributes(D);
 
   if (D->getIdentifier()) {
-Out << ' ' << *D;
+Out << ' ';
+
+if (const NestedNameSpecifier *Q = D->getQualifier())
+  Q->print(Out, Policy);
+
+Out << *D;
 
 if (auto S = dyn_cast(D))
   printTemplateArguments(S->getTemplateArgs(), S->getTemplateParameters());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61717: Fix arm_neon.h to be clean under -fno-lax-vector-conversions.

2019-05-09 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer accepted this revision.
SjoerdMeijer added a comment.
This revision is now accepted and ready to land.

Looks okay to me.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61717/new/

https://reviews.llvm.org/D61717



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


[PATCH] D59481: [clangd] Count number of references while merging RefSlabs inside FileIndex

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang-tools-extra/clangd/index/FileIndex.cpp:101
 FileToRefs.erase(Path);
-  else
-FileToRefs[Path] = std::move(Refs);
+  else {
+RefSlabAndCountReferences Item;

NIT: maybe simplify to the following?
```
if (!Refs) {
  FileToRefs.erase(Path);
  return;
}
...
```

up to you.



Comment at: clang-tools-extra/clangd/index/FileIndex.h:63
   /// If either is nullptr, corresponding data for \p Path will be removed.
+  /// If CountReferences is true, Refs will be used for counting References
+  /// during merging.

NIT: use `\p Refs`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59481/new/

https://reviews.llvm.org/D59481



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


[PATCH] D61488: [OpenCL] Make global ctor init function a kernel

2019-05-09 Thread Kévin Petit via Phabricator via cfe-commits
kpet accepted this revision.
kpet added a comment.
This revision is now accepted and ready to land.

The comments could use a bit more polishing but nothing that justifies making 
another iteration IMHO. LGTM!


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61488/new/

https://reviews.llvm.org/D61488



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


[PATCH] D61639: Add Triple::isSPIR() to simplify code

2019-05-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL360323: [SPIR] Simplified target checking. (authored by 
stulova, committed by ).
Herald added a subscriber: kristina.

Changed prior to commit:
  https://reviews.llvm.org/D61639?vs=198429&id=198780#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61639/new/

https://reviews.llvm.org/D61639

Files:
  llvm/trunk/include/llvm/ADT/Triple.h


Index: llvm/trunk/include/llvm/ADT/Triple.h
===
--- llvm/trunk/include/llvm/ADT/Triple.h
+++ llvm/trunk/include/llvm/ADT/Triple.h
@@ -671,6 +671,11 @@
getEnvironment() == Triple::MuslEABIHF;
   }
 
+  /// Tests whether the target is SPIR (32- or 64-bit).
+  bool isSPIR() const {
+return getArch() == Triple::spir || getArch() == Triple::spir64;
+  }
+
   /// Tests whether the target is NVPTX (32- or 64-bit).
   bool isNVPTX() const {
 return getArch() == Triple::nvptx || getArch() == Triple::nvptx64;


Index: llvm/trunk/include/llvm/ADT/Triple.h
===
--- llvm/trunk/include/llvm/ADT/Triple.h
+++ llvm/trunk/include/llvm/ADT/Triple.h
@@ -671,6 +671,11 @@
getEnvironment() == Triple::MuslEABIHF;
   }
 
+  /// Tests whether the target is SPIR (32- or 64-bit).
+  bool isSPIR() const {
+return getArch() == Triple::spir || getArch() == Triple::spir64;
+  }
+
   /// Tests whether the target is NVPTX (32- or 64-bit).
   bool isNVPTX() const {
 return getArch() == Triple::nvptx || getArch() == Triple::nvptx64;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r360324 - [ARM] Fix the extensions implied by a cpu name

2019-05-09 Thread Diogo N. Sampaio via cfe-commits
Author: dnsampaio
Date: Thu May  9 03:24:36 2019
New Revision: 360324

URL: http://llvm.org/viewvc/llvm-project?rev=360324&view=rev
Log:
[ARM] Fix the extensions implied by a cpu name

Summary:
When using `clang -mcpu=CPUNAME+FEATURELIST`,
the implied features defined by CPUNAME are
not obtained, as the entire string is passed.
This fixes that by spiting the cpuname
string in the first `+`, if any.

For example, when using
```clang -### --target=arm-arm-none-eabi -march=armv7-a -mcpu=cortex-a8+nocrc```
the intrinsic
```"target-feature" "+dsp"```
implied by `cortex-a8` is missing.

Reviewers: keith.walker.arm, DavidSpickett, carwil

Reviewed By: DavidSpickett

Subscribers: javed.absar, kristof.beyls, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Arch/ARM.cpp
cfe/trunk/test/Driver/arm-cortex-cpus.c

Modified: cfe/trunk/lib/Driver/ToolChains/Arch/ARM.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Arch/ARM.cpp?rev=360324&r1=360323&r2=360324&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Arch/ARM.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Arch/ARM.cpp Thu May  9 03:24:36 2019
@@ -88,6 +88,7 @@ static bool DecodeARMFeatures(const Driv
 
 static void DecodeARMFeaturesFromCPU(const Driver &D, StringRef CPU,
  std::vector &Features) {
+  CPU = CPU.split("+").first;
   if (CPU != "generic") {
 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
 unsigned Extension = llvm::ARM::getDefaultExtensions(CPU, ArchKind);
@@ -350,11 +351,9 @@ void arm::getARMTargetFeatures(const Too
   D.Diag(clang::diag::warn_drv_unused_argument)
   << CPUArg->getAsString(Args);
 CPUName = StringRef(WaCPU->getValue()).substr(6);
-checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
-  } else if (CPUArg) {
+CPUArg = WaCPU;
+  } else if (CPUArg)
 CPUName = CPUArg->getValue();
-checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
-  }
 
   // Add CPU features for generic CPUs
   if (CPUName == "native") {
@@ -367,6 +366,8 @@ void arm::getARMTargetFeatures(const Too
 DecodeARMFeaturesFromCPU(D, CPUName, Features);
   }
 
+  if (CPUArg)
+checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
   // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
   const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
   if (WaFPU) {

Modified: cfe/trunk/test/Driver/arm-cortex-cpus.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/arm-cortex-cpus.c?rev=360324&r1=360323&r2=360324&view=diff
==
--- cfe/trunk/test/Driver/arm-cortex-cpus.c (original)
+++ cfe/trunk/test/Driver/arm-cortex-cpus.c Thu May  9 03:24:36 2019
@@ -340,30 +340,31 @@
 // RUN: %clang -target armv8a-linux-eabi -mcpu=cortex-a53+fp16 -### -c %s 2>&1 
| FileCheck --check-prefix CHECK-CORTEX-A53-FP16 %s
 // RUN: %clang -target armv8a-linux-eabi -mcpu=cortex-a53+nofp16 -### -c %s 
2>&1 | FileCheck --check-prefix CHECK-CORTEX-A53-NOFP16 %s
 // CHECK-CORTEX-A53-FP16: "-cc1" {{.*}}"-target-cpu" "cortex-a53" 
{{.*}}"-target-feature" "+fullfp16"
-// CHECK-CORTEX-A53-FP16-NOT: "-target-feature" "{{[+-]}}fp16fml"
-// CHECK-CORTEX-A53-NOFP16: "-cc1" {{.*}}"-target-cpu" "cortex-a53" 
{{.*}}"-target-feature" "-fullfp16" "-target-feature" "-fp16fml"
+// CHECK-CORTEX-A53-FP16-NOT: "-target-feature" "+fp16fml"
+// CHECK-CORTEX-A53-NOFP16-NOT: "+fullfp16"
+// CHECK-CORTEX-A53-NOFP16-NOT: "+fp16fml"
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8-a -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8A-NOFP16FML %s
-// CHECK-V8A-NOFP16FML-NOT: "-target-feature" "{{[+-]}}fp16fml"
-// CHECK-V8A-NOFP16FML-NOT: "-target-feature" "{{[+-]}}fullfp16"
+// CHECK-V8A-NOFP16FML-NOT: "-target-feature" "+fp16fml"
+// CHECK-V8A-NOFP16FML-NOT: "-target-feature" "+fullfp16"
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8-a+fp16 -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V8A-FP16 %s
-// CHECK-V8A-FP16-NOT: "-target-feature" "{{[+-]}}fp16fml"
+// CHECK-V8A-FP16-NOT: "-target-feature" "+fp16fml"
 // CHECK-V8A-FP16: "-target-feature" "+fullfp16"
-// CHECK-V8A-FP16-NOT: "-target-feature" "{{[+-]}}fp16fml"
+// CHECK-V8A-FP16-NOT: "-target-feature" "+fp16fml"
 // CHECK-V8A-FP16-SAME: {{$}}
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8-a+fp16fml -### -c %s 
2>&1 | FileCheck -check-prefix=CHECK-V8A-FP16FML %s
 // CHECK-V8A-FP16FML: "-target-feature" "+fp16fml" "-target-feature" 
"+fullfp16"
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8.2-a -### -c %s 2>&1 | 
FileCheck -check-prefix=CHECK-V82A-NOFP16FML %s
-// CHECK-V82A-NOFP16FML-NOT: "-target-feature" "{{[+-]}}fp16fml"
-// CHECK-V82A-NOFP16FML-NOT: "-target-feature" "{{[+-]}}fullfp16"
+// CHECK-V82A-NOFP1

[PATCH] D61668: [ARM] Fix the extensions implied by a cpu name

2019-05-09 Thread Diogo N. Sampaio via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL360324: [ARM] Fix the extensions implied by a cpu name 
(authored by dnsampaio, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61668/new/

https://reviews.llvm.org/D61668

Files:
  cfe/trunk/lib/Driver/ToolChains/Arch/ARM.cpp
  cfe/trunk/test/Driver/arm-cortex-cpus.c

Index: cfe/trunk/lib/Driver/ToolChains/Arch/ARM.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Arch/ARM.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -88,6 +88,7 @@
 
 static void DecodeARMFeaturesFromCPU(const Driver &D, StringRef CPU,
  std::vector &Features) {
+  CPU = CPU.split("+").first;
   if (CPU != "generic") {
 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
 unsigned Extension = llvm::ARM::getDefaultExtensions(CPU, ArchKind);
@@ -350,11 +351,9 @@
   D.Diag(clang::diag::warn_drv_unused_argument)
   << CPUArg->getAsString(Args);
 CPUName = StringRef(WaCPU->getValue()).substr(6);
-checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
-  } else if (CPUArg) {
+CPUArg = WaCPU;
+  } else if (CPUArg)
 CPUName = CPUArg->getValue();
-checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
-  }
 
   // Add CPU features for generic CPUs
   if (CPUName == "native") {
@@ -367,6 +366,8 @@
 DecodeARMFeaturesFromCPU(D, CPUName, Features);
   }
 
+  if (CPUArg)
+checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
   // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
   const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
   if (WaFPU) {
Index: cfe/trunk/test/Driver/arm-cortex-cpus.c
===
--- cfe/trunk/test/Driver/arm-cortex-cpus.c
+++ cfe/trunk/test/Driver/arm-cortex-cpus.c
@@ -340,30 +340,31 @@
 // RUN: %clang -target armv8a-linux-eabi -mcpu=cortex-a53+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-CORTEX-A53-FP16 %s
 // RUN: %clang -target armv8a-linux-eabi -mcpu=cortex-a53+nofp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-CORTEX-A53-NOFP16 %s
 // CHECK-CORTEX-A53-FP16: "-cc1" {{.*}}"-target-cpu" "cortex-a53" {{.*}}"-target-feature" "+fullfp16"
-// CHECK-CORTEX-A53-FP16-NOT: "-target-feature" "{{[+-]}}fp16fml"
-// CHECK-CORTEX-A53-NOFP16: "-cc1" {{.*}}"-target-cpu" "cortex-a53" {{.*}}"-target-feature" "-fullfp16" "-target-feature" "-fp16fml"
+// CHECK-CORTEX-A53-FP16-NOT: "-target-feature" "+fp16fml"
+// CHECK-CORTEX-A53-NOFP16-NOT: "+fullfp16"
+// CHECK-CORTEX-A53-NOFP16-NOT: "+fp16fml"
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-NOFP16FML %s
-// CHECK-V8A-NOFP16FML-NOT: "-target-feature" "{{[+-]}}fp16fml"
-// CHECK-V8A-NOFP16FML-NOT: "-target-feature" "{{[+-]}}fullfp16"
+// CHECK-V8A-NOFP16FML-NOT: "-target-feature" "+fp16fml"
+// CHECK-V8A-NOFP16FML-NOT: "-target-feature" "+fullfp16"
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8-a+fp16 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-FP16 %s
-// CHECK-V8A-FP16-NOT: "-target-feature" "{{[+-]}}fp16fml"
+// CHECK-V8A-FP16-NOT: "-target-feature" "+fp16fml"
 // CHECK-V8A-FP16: "-target-feature" "+fullfp16"
-// CHECK-V8A-FP16-NOT: "-target-feature" "{{[+-]}}fp16fml"
+// CHECK-V8A-FP16-NOT: "-target-feature" "+fp16fml"
 // CHECK-V8A-FP16-SAME: {{$}}
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8-a+fp16fml -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V8A-FP16FML %s
 // CHECK-V8A-FP16FML: "-target-feature" "+fp16fml" "-target-feature" "+fullfp16"
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8.2-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V82A-NOFP16FML %s
-// CHECK-V82A-NOFP16FML-NOT: "-target-feature" "{{[+-]}}fp16fml"
-// CHECK-V82A-NOFP16FML-NOT: "-target-feature" "{{[+-]}}fullfp16"
+// CHECK-V82A-NOFP16FML-NOT: "-target-feature" "+fp16fml"
+// CHECK-V82A-NOFP16FML-NOT: "-target-feature" "+fullfp16"
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8.2-a+fp16 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V82A-FP16 %s
-// CHECK-V82A-FP16-NOT: "-target-feature" "{{[+-]}}fp16fml"
+// CHECK-V82A-FP16-NOT: "-target-feature" "+fp16fml"
 // CHECK-V82A-FP16: "-target-feature" "+fullfp16"
-// CHECK-V82A-FP16-NOT: "-target-feature" "{{[+-]}}fp16fml"
+// CHECK-V82A-FP16-NOT: "-target-feature" "+fp16fml"
 // CHECK-V82A-FP16-SAME: {{$}}
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8.2-a+fp16fml -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V82A-FP16FML %s
@@ -382,13 +383,13 @@
 // CHECK-V82A-NOFP16-FP16FML: "-target-feature" "+fp16fml" "-target-feature" "+fullfp16"
 
 // RUN: %clang -target armv8a-linux-eabi -march=armv8.3-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V83A-NO

r360325 - [SPIR] Simplified target checking.

2019-05-09 Thread Anastasia Stulova via cfe-commits
Author: stulova
Date: Thu May  9 03:25:45 2019
New Revision: 360325

URL: http://llvm.org/viewvc/llvm-project?rev=360325&view=rev
Log:
[SPIR] Simplified target checking.

Switched to Triple::isSPIR() helper to simplify code.

Patch by kpet (Kevin Petit)!

Differential revision: https://reviews.llvm.org/D61639


Modified:
cfe/trunk/lib/CodeGen/CodeGenModule.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/lib/Frontend/InitPreprocessor.cpp

Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=360325&r1=360324&r2=360325&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Thu May  9 03:25:45 2019
@@ -539,8 +539,7 @@ void CodeGenModule::Release() {
   if (LangOpts.OpenCL) {
 EmitOpenCLMetadata();
 // Emit SPIR version.
-if (getTriple().getArch() == llvm::Triple::spir ||
-getTriple().getArch() == llvm::Triple::spir64) {
+if (getTriple().isSPIR()) {
   // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
   // opencl.spir.version named metadata.
   llvm::Metadata *SPIRVerElts[] = {

Modified: cfe/trunk/lib/Frontend/CompilerInvocation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInvocation.cpp?rev=360325&r1=360324&r2=360325&view=diff
==
--- cfe/trunk/lib/Frontend/CompilerInvocation.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInvocation.cpp Thu May  9 03:25:45 2019
@@ -3349,10 +3349,8 @@ bool CompilerInvocation::CreateFromArgs(
   Res.getFrontendOpts().ProgramAction);
 
   // Turn on -Wspir-compat for SPIR target.
-  auto Arch = T.getArch();
-  if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64) {
+  if (T.isSPIR())
 Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
-  }
 
   // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
   if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&

Modified: cfe/trunk/lib/Frontend/InitPreprocessor.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/InitPreprocessor.cpp?rev=360325&r1=360324&r2=360325&view=diff
==
--- cfe/trunk/lib/Frontend/InitPreprocessor.cpp (original)
+++ cfe/trunk/lib/Frontend/InitPreprocessor.cpp Thu May  9 03:25:45 2019
@@ -1072,8 +1072,7 @@ static void InitializePredefinedMacros(c
 Builder.defineMacro(#Ext);
 #include "clang/Basic/OpenCLExtensions.def"
 
-auto Arch = TI.getTriple().getArch();
-if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64)
+if (TI.getTriple().isSPIR())
   Builder.defineMacro("__IMAGE_SUPPORT__");
   }
 


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


r360326 - Revert "[OPENMP]Fix PR41767: diagnose DSA for variables in clauses with default(none)."

2019-05-09 Thread Roman Lebedev via cfe-commits
Author: lebedevri
Date: Thu May  9 03:47:45 2019
New Revision: 360326

URL: http://llvm.org/viewvc/llvm-project?rev=360326&view=rev
Log:
Revert "[OPENMP]Fix PR41767: diagnose DSA for variables in clauses with 
default(none)."

This implementation isn't sound as per the standard.
It erroneously diagnoses e.g. the following case:
```
$ cat test.cpp
void f(int n) {
 #pragma omp parallel default(none) if(n)
;
}
```
```
$ ./bin/clang -fopenmp test.cpp
test.cpp:2:40: error: variable 'n' must have explicitly specified data sharing 
attributes
 #pragma omp parallel default(none) if(n)
   ^
test.cpp:2:31: note: explicit data sharing attribute requested here
 #pragma omp parallel default(none) if(n)
  ^
1 error generated.
```

As per OpenMP Application Programming Interface Version 5.0 November 2018:
* 2.19.4.1default Clause
  The default clause explicitly determines the data-sharing attributes of
  variables that are referenced *in a parallel, teams, or task generating
  construct and would otherwise be implicitly determined
  (see Section 2.19.1.1 on page 270).
* 2.6.1 Determining the Number of Threads for a parallel Region
  Using a variable in an if or num_threads clause expression of a parallel
  construct causes an implicit reference to the variable in all enclosing
  constructs. The if clause expression and the num_threads clause expression
  are evaluated in the context outside of the parallel construct,

This reverts commit r360073.

Modified:
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_ast_print.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_simd_ast_print.cpp
cfe/trunk/test/OpenMP/parallel_for_ast_print.cpp
cfe/trunk/test/OpenMP/parallel_for_schedule_messages.cpp
cfe/trunk/test/OpenMP/target_parallel_for_ast_print.cpp
cfe/trunk/test/OpenMP/target_parallel_for_simd_ast_print.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_if_messages.cpp

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=360326&r1=360325&r2=360326&view=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Thu May  9 03:47:45 2019
@@ -750,8 +750,7 @@ bool isImplicitTaskingRegion(OpenMPDirec
 }
 
 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
-  return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
- DKind == OMPD_unknown;
+  return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 
DKind == OMPD_unknown;
 }
 
 } // namespace
@@ -2561,17 +2560,9 @@ public:
 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
   return;
 if (auto *VD = dyn_cast(E->getDecl())) {
-  // Check the datasharing rules for the expressions in the clauses.
-  if (!CS) {
-if (auto *CED = dyn_cast(VD))
-  if (!CED->hasAttr()) {
-Visit(CED->getInit());
-return;
-  }
-  }
   VD = VD->getCanonicalDecl();
   // Skip internally declared variables.
-  if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
+  if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
 return;
 
   DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
@@ -2582,7 +2573,7 @@ public:
   // Skip internally declared static variables.
   llvm::Optional Res =
   OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
-  if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
+  if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
   (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
 return;
 
@@ -4195,90 +4186,6 @@ StmtResult Sema::ActOnOpenMPExecutableDi
 
   ErrorFound = Res.isInvalid() || ErrorFound;
 
-  // Check variables in the clauses if default(none) was specified.
-  if (DSAStack->getDefaultDSA() == DSA_none) {
-DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
-for (OMPClause *C : Clauses) {
-  switch (C->getClauseKind()) {
-  case OMPC_num_threads:
-  case OMPC_dist_schedule:
-// Do not analyse if no parent teams directive.
-if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
-  break;
-continue;
-  case OMPC_if:
-if ((isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
- cast(C)->getNameModifier() != OMPD_target) ||
-isOpenMPParallelDirective(DSAStack->getCurrentDirective()))
-  break;
-continue;
-  case OMPC_schedule:
-break;
-  case OMPC_ordered:
-  case OMPC_device:
-  case OMPC_num_teams:
-  case OMPC_thread_limit:
-  case OMPC_priority:
-  case OMPC_grainsize:
-  case OMPC_num_tasks:
-  case OMPC_hint:
-  c

r360327 - Revert "[OPENMP]Fix PR41768: check DSA for globals with `default(none)` clauses."

2019-05-09 Thread Roman Lebedev via cfe-commits
Author: lebedevri
Date: Thu May  9 03:48:13 2019
New Revision: 360327

URL: http://llvm.org/viewvc/llvm-project?rev=360327&view=rev
Log:
Revert "[OPENMP]Fix PR41768: check DSA for globals with `default(none)` 
clauses."

This has introduced (exposed?) a crash in clang sema,
that does not happen without this patch.
I'll followup in the original bugreport and commit with reproducer.

This reverts commit r360061.

Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_default_messages.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_messages.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_simd_default_messages.cpp
cfe/trunk/test/OpenMP/parallel_default_messages.cpp
cfe/trunk/test/OpenMP/parallel_for_default_messages.cpp
cfe/trunk/test/OpenMP/parallel_for_messages.cpp
cfe/trunk/test/OpenMP/parallel_for_simd_default_messages.cpp
cfe/trunk/test/OpenMP/parallel_for_simd_messages.cpp
cfe/trunk/test/OpenMP/parallel_messages.cpp
cfe/trunk/test/OpenMP/parallel_sections_default_messages.cpp
cfe/trunk/test/OpenMP/parallel_sections_messages.cpp
cfe/trunk/test/OpenMP/report_default_DSA.cpp
cfe/trunk/test/OpenMP/target_parallel_default_messages.cpp
cfe/trunk/test/OpenMP/target_parallel_for_default_messages.cpp
cfe/trunk/test/OpenMP/target_parallel_for_messages.cpp
cfe/trunk/test/OpenMP/target_parallel_for_simd_default_messages.cpp
cfe/trunk/test/OpenMP/target_parallel_for_simd_messages.cpp
cfe/trunk/test/OpenMP/target_teams_default_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_default_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_messages.cpp

cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_default_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_messages.cpp

cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_simd_default_messages.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_simd_messages.cpp
cfe/trunk/test/OpenMP/target_teams_messages.cpp
cfe/trunk/test/OpenMP/task_default_messages.cpp
cfe/trunk/test/OpenMP/task_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/task_messages.cpp
cfe/trunk/test/OpenMP/teams_default_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_default_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_parallel_for_default_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_parallel_for_messages.cpp

cfe/trunk/test/OpenMP/teams_distribute_parallel_for_simd_default_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_parallel_for_simd_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_simd_default_messages.cpp
cfe/trunk/test/OpenMP/teams_distribute_simd_messages.cpp
cfe/trunk/test/OpenMP/teams_messages.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=360327&r1=360326&r2=360327&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Thu May  9 03:48:13 
2019
@@ -8821,8 +8821,6 @@ def err_omp_threadprivate_incomplete_typ
   "threadprivate variable with incomplete type %0">;
 def err_omp_no_dsa_for_variable : Error<
   "variable %0 must have explicitly specified data sharing attributes">;
-def note_omp_default_dsa_none : Note<
-  "explicit data sharing attribute requested here">;
 def err_omp_wrong_dsa : Error<
   "%0 variable cannot be %1">;
 def err_omp_variably_modified_type_not_supported : Error<

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=360327&r1=360326&r2=360327&view=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Thu May  9 03:48:13 2019
@@ -1777,15 +1777,10 @@ VarDecl *Sema::isOpenMPCapturedDecl(Valu
 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
 if (DVarPrivate.CKind != OMPC_unknown && 
isOpenMPPrivate(DVarPrivate.CKind))
   return VD ? VD : cast(DVarPrivate.PrivateCopy->getDecl());
-if (VD && DSAStack->getDefaultDSA() == DSA_none)
-  return VD;
 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
[](OpenMPDirectiveKind) { return true; },
DSAStack->isClauseParsingMode());
-// The variable is not private or it is the variable in the directive with
-// default(none) clause and not used in any clause.
-if (DVarPrivate.CKind != OMPC_unknown ||
-(VD && DSAStack->getDefaultDSA() == DSA_none))
+if (DVarPrivate.CKind != OMPC_unknown)
   return VD ? VD : cast(DVarPriva

[PATCH] D61722: Prototype of RecoveryExpr. Here, it's emitted when overload resolution fails.

2019-05-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D61722

Files:
  include/clang/AST/Expr.h
  include/clang/AST/RecursiveASTVisitor.h
  include/clang/AST/Stmt.h
  include/clang/Basic/StmtNodes.td
  include/clang/Serialization/ASTBitCodes.h
  lib/AST/Expr.cpp
  lib/AST/ExprClassification.cpp
  lib/AST/ExprConstant.cpp
  lib/AST/ItaniumMangle.cpp
  lib/AST/Stmt.cpp
  lib/AST/StmtPrinter.cpp
  lib/AST/StmtProfile.cpp
  lib/Sema/SemaExceptionSpec.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaOverload.cpp
  lib/Sema/TreeTransform.h
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  test/SemaCXX/enable_if.cpp
  test/SemaTemplate/instantiate-init.cpp
  tools/libclang/CXCursor.cpp

Index: tools/libclang/CXCursor.cpp
===
--- tools/libclang/CXCursor.cpp
+++ tools/libclang/CXCursor.cpp
@@ -288,6 +288,7 @@
   case Stmt::ObjCDictionaryLiteralClass:
   case Stmt::ObjCBoxedExprClass:
   case Stmt::ObjCSubscriptRefExprClass:
+  case Stmt::RecoveryExprClass:
 K = CXCursor_UnexposedExpr;
 break;
 
Index: test/SemaTemplate/instantiate-init.cpp
===
--- test/SemaTemplate/instantiate-init.cpp
+++ test/SemaTemplate/instantiate-init.cpp
@@ -100,9 +100,9 @@
 integral_c<1> ic1 = array_lengthof(Description::data);
 (void)sizeof(array_lengthof(Description::data));
 
-sizeof(array_lengthof( // expected-error{{no matching function for call to 'array_lengthof'}}
-  Description::data // expected-note{{in instantiation of static data member 'PR7985::Description::data' requested here}}
-  ));
+(void)sizeof(array_lengthof( // expected-error{{no matching function for call to 'array_lengthof'}}
+Description::data // expected-note{{in instantiation of static data member 'PR7985::Description::data' requested here}}
+));
 
 array_lengthof(Description::data); // expected-error{{no matching function for call to 'array_lengthof'}}
   }
Index: test/SemaCXX/enable_if.cpp
===
--- test/SemaCXX/enable_if.cpp
+++ test/SemaCXX/enable_if.cpp
@@ -1,535 +1,9 @@
 // RUN: %clang_cc1 -std=c++11 -verify %s
 
-typedef int (*fp)(int);
-int surrogate(int);
-struct Incomplete;  // expected-note{{forward declaration of 'Incomplete'}} \
-// expected-note {{forward declaration of 'Incomplete'}}
-
-struct X {
-  X() = default;  // expected-note{{candidate constructor not viable: requires 0 arguments, but 1 was provided}}
-  X(const X&) = default;  // expected-note{{candidate constructor not viable: no known conversion from 'bool' to 'const X' for 1st argument}}
-  X(bool b) __attribute__((enable_if(b, "chosen when 'b' is true")));  // expected-note{{candidate disabled: chosen when 'b' is true}}
-
-  void f(int n) __attribute__((enable_if(n == 0, "chosen when 'n' is zero")));
-  void f(int n) __attribute__((enable_if(n == 1, "chosen when 'n' is one")));  // expected-note{{member declaration nearly matches}} expected-note 2{{candidate disabled: chosen when 'n' is one}}
-
-  void g(int n) __attribute__((enable_if(n == 0, "chosen when 'n' is zero")));  // expected-note{{candidate disabled: chosen when 'n' is zero}}
-
-  void h(int n, int m = 0) __attribute__((enable_if(m == 0, "chosen when 'm' is zero")));  // expected-note{{candidate disabled: chosen when 'm' is zero}}
-
-  static void s(int n) __attribute__((enable_if(n == 0, "chosen when 'n' is zero")));  // expected-note2{{candidate disabled: chosen when 'n' is zero}}
-
-  void conflict(int n) __attribute__((enable_if(n+n == 10, "chosen when 'n' is five")));  // expected-note{{candidate function}}
-  void conflict(int n) __attribute__((enable_if(n*2 == 10, "chosen when 'n' is five")));  // expected-note{{candidate function}}
-
-  void hidden_by_argument_conversion(Incomplete n, int m = 0) __attribute__((enable_if(m == 10, "chosen when 'm' is ten")));
-  Incomplete hidden_by_incomplete_return_value(int n = 0) __attribute__((enable_if(n == 10, "chosen when 'n' is ten"))); // expected-note{{'hidden_by_incomplete_return_value' declared here}}
-
-  operator long() __attribute__((enable_if(true, "chosen on your platform")));
-  operator int() __attribute__((enable_if(false, "chosen on other platform")));
-
-  operator fp() __attribute__((enable_if(false, "never enabled"))) { return surrogate; }  // expected-note{{conversion candidate of type 'int (*)(int)'}}  // FIXME: the message is not displayed
-};
-
-void X::f(int n) __attribute__((enable_if(n == 0, "chosen when 'n' is zero")))  // expected-note{{member declaration nearly matches}} expected-note 2{{candidate disabled: chosen when 'n' is zero}}
-{
-}
-
-void X::f(int n) __attribute__((enable_if(n == 2, "chose

[PATCH] D61488: [OpenCL] Make global ctor init function a kernel

2019-05-09 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D61488#1496154 , @kpet wrote:

> The comments could use a bit more polishing but nothing that justifies making 
> another iteration IMHO. LGTM!


Sure, feel free to put up a patch if you like. :)

Thanks!


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61488/new/

https://reviews.llvm.org/D61488



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


[PATCH] D60934: [clang] adding explicit(bool) from c++2a

2019-05-09 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: cfe/trunk/lib/Parse/ParseDecl.cpp:3939
+ "both or neither of isAlreadyConsumed and 
"
+ "RangeEnd needs to be set");
+DS.SetRangeEnd(isAlreadyConsumed ? RangeEnd : Tok.getLocation());

@Tyker @rsmith We're seeing -Wparentheses warnings because of this - please can 
you take a look? The logic looks a little dodgy for a both/neither assertion as 
well.

http://lab.llvm.org:8011/builders/clang-ppc64be-linux-lnt/builds/27322/steps/build%20stage%201/logs/warnings%20%281%29


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60934/new/

https://reviews.llvm.org/D60934



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


[PATCH] D50993: [clangd] Increase stack size of the new threads on macOS

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

We should definitely land this.

@Dmitry.Kozhevnikov, you don't have commit access, right? Should we land these 
two revisions for you?


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D50993/new/

https://reviews.llvm.org/D50993



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


[PATCH] D61722: Prototype of RecoveryExpr. Here, it's emitted when overload resolution fails.

2019-05-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 198786.
sammccall added a comment.

Fix serialization maybe.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61722/new/

https://reviews.llvm.org/D61722

Files:
  include/clang/AST/Expr.h
  include/clang/AST/RecursiveASTVisitor.h
  include/clang/AST/Stmt.h
  include/clang/Basic/StmtNodes.td
  include/clang/Serialization/ASTBitCodes.h
  lib/AST/Expr.cpp
  lib/AST/ExprClassification.cpp
  lib/AST/ExprConstant.cpp
  lib/AST/ItaniumMangle.cpp
  lib/AST/Stmt.cpp
  lib/AST/StmtPrinter.cpp
  lib/AST/StmtProfile.cpp
  lib/Sema/SemaExceptionSpec.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaOverload.cpp
  lib/Sema/TreeTransform.h
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  test/SemaCXX/enable_if.cpp
  test/SemaTemplate/instantiate-init.cpp
  tools/libclang/CXCursor.cpp

Index: tools/libclang/CXCursor.cpp
===
--- tools/libclang/CXCursor.cpp
+++ tools/libclang/CXCursor.cpp
@@ -288,6 +288,7 @@
   case Stmt::ObjCDictionaryLiteralClass:
   case Stmt::ObjCBoxedExprClass:
   case Stmt::ObjCSubscriptRefExprClass:
+  case Stmt::RecoveryExprClass:
 K = CXCursor_UnexposedExpr;
 break;
 
Index: test/SemaTemplate/instantiate-init.cpp
===
--- test/SemaTemplate/instantiate-init.cpp
+++ test/SemaTemplate/instantiate-init.cpp
@@ -100,9 +100,9 @@
 integral_c<1> ic1 = array_lengthof(Description::data);
 (void)sizeof(array_lengthof(Description::data));
 
-sizeof(array_lengthof( // expected-error{{no matching function for call to 'array_lengthof'}}
-  Description::data // expected-note{{in instantiation of static data member 'PR7985::Description::data' requested here}}
-  ));
+(void)sizeof(array_lengthof( // expected-error{{no matching function for call to 'array_lengthof'}}
+Description::data // expected-note{{in instantiation of static data member 'PR7985::Description::data' requested here}}
+));
 
 array_lengthof(Description::data); // expected-error{{no matching function for call to 'array_lengthof'}}
   }
Index: test/SemaCXX/enable_if.cpp
===
--- test/SemaCXX/enable_if.cpp
+++ test/SemaCXX/enable_if.cpp
@@ -1,535 +1,9 @@
 // RUN: %clang_cc1 -std=c++11 -verify %s
 
-typedef int (*fp)(int);
-int surrogate(int);
-struct Incomplete;  // expected-note{{forward declaration of 'Incomplete'}} \
-// expected-note {{forward declaration of 'Incomplete'}}
-
-struct X {
-  X() = default;  // expected-note{{candidate constructor not viable: requires 0 arguments, but 1 was provided}}
-  X(const X&) = default;  // expected-note{{candidate constructor not viable: no known conversion from 'bool' to 'const X' for 1st argument}}
-  X(bool b) __attribute__((enable_if(b, "chosen when 'b' is true")));  // expected-note{{candidate disabled: chosen when 'b' is true}}
-
-  void f(int n) __attribute__((enable_if(n == 0, "chosen when 'n' is zero")));
-  void f(int n) __attribute__((enable_if(n == 1, "chosen when 'n' is one")));  // expected-note{{member declaration nearly matches}} expected-note 2{{candidate disabled: chosen when 'n' is one}}
-
-  void g(int n) __attribute__((enable_if(n == 0, "chosen when 'n' is zero")));  // expected-note{{candidate disabled: chosen when 'n' is zero}}
-
-  void h(int n, int m = 0) __attribute__((enable_if(m == 0, "chosen when 'm' is zero")));  // expected-note{{candidate disabled: chosen when 'm' is zero}}
-
-  static void s(int n) __attribute__((enable_if(n == 0, "chosen when 'n' is zero")));  // expected-note2{{candidate disabled: chosen when 'n' is zero}}
-
-  void conflict(int n) __attribute__((enable_if(n+n == 10, "chosen when 'n' is five")));  // expected-note{{candidate function}}
-  void conflict(int n) __attribute__((enable_if(n*2 == 10, "chosen when 'n' is five")));  // expected-note{{candidate function}}
-
-  void hidden_by_argument_conversion(Incomplete n, int m = 0) __attribute__((enable_if(m == 10, "chosen when 'm' is ten")));
-  Incomplete hidden_by_incomplete_return_value(int n = 0) __attribute__((enable_if(n == 10, "chosen when 'n' is ten"))); // expected-note{{'hidden_by_incomplete_return_value' declared here}}
-
-  operator long() __attribute__((enable_if(true, "chosen on your platform")));
-  operator int() __attribute__((enable_if(false, "chosen on other platform")));
-
-  operator fp() __attribute__((enable_if(false, "never enabled"))) { return surrogate; }  // expected-note{{conversion candidate of type 'int (*)(int)'}}  // FIXME: the message is not displayed
-};
-
-void X::f(int n) __attribute__((enable_if(n == 0, "chosen when 'n' is zero")))  // expected-note{{member declaration nearly matches}} expected-note 2{{candidate disabled: chosen when 'n' is zero}}
-

r360329 - [FIX] Change test to read file instead

2019-05-09 Thread Diogo N. Sampaio via cfe-commits
Author: dnsampaio
Date: Thu May  9 04:23:00 2019
New Revision: 360329

URL: http://llvm.org/viewvc/llvm-project?rev=360329&view=rev
Log:
[FIX] Change test to read file instead

This should fix the test file failing in
windows by reading the file it self instead
of stdin, from 543913c3b41f

Modified:
cfe/trunk/test/Driver/arm-cortex-cpus.c

Modified: cfe/trunk/test/Driver/arm-cortex-cpus.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/arm-cortex-cpus.c?rev=360329&r1=360328&r2=360329&view=diff
==
--- cfe/trunk/test/Driver/arm-cortex-cpus.c (original)
+++ cfe/trunk/test/Driver/arm-cortex-cpus.c Thu May  9 04:23:00 2019
@@ -856,5 +856,5 @@
 // CHECK-CASE-INSENSITIVE-V6T2-THUMB: "-cc1"{{.*}} "-triple" "thumbv6t2-{{.*}} 
"-target-cpu" "arm1156t2-s"
 
 // == Check that the correct PROCESSOR features are added when 
used -mcpu=PROCESSOR+FEATURESLIST
-// RUN: %clang -### --target=arm-arm-none-eabi -march=armv7-a 
-mcpu=cortex-a8+nocrc -x c -S -o - - <<< "" 2>&1 | FileCheck 
-check-prefix=A8FEATURES %s
+// RUN: %clang -### --target=arm-arm-none-eabi -march=armv7-a 
-mcpu=cortex-a8+nocrc -c %s 2>&1 | FileCheck -check-prefix=A8FEATURES %s
 // A8FEATURES: "-target-feature" "+dsp"


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


[PATCH] D61724: [clangd] Use AsyncTaskRunner in BackgroundIndex instead of std::thread

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: kadircet.
Herald added subscribers: jfb, arphaman, jkorous, MaskRay.
Herald added a project: clang.

To unify the way we create threads in clangd.
This should simplify landing D50993 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D61724

Files:
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/Background.h


Index: clang-tools-extra/clangd/index/Background.h
===
--- clang-tools-extra/clangd/index/Background.h
+++ clang-tools-extra/clangd/index/Background.h
@@ -146,7 +146,7 @@
   std::condition_variable QueueCV;
   bool ShouldStop = false;
   std::deque> Queue;
-  std::vector ThreadPool; // FIXME: Abstract this away.
+  AsyncTaskRunner ThreadPool;
   GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
 
Index: clang-tools-extra/clangd/index/Background.cpp
===
--- clang-tools-extra/clangd/index/Background.cpp
+++ clang-tools-extra/clangd/index/Background.cpp
@@ -148,19 +148,20 @@
   })) {
   assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
   assert(this->IndexStorageFactory && "Storage factory can not be null!");
-  while (ThreadPoolSize--)
-ThreadPool.emplace_back([this] { run(); });
+  for (unsigned I = 1; I <= ThreadPoolSize; ++I) {
+ThreadPool.runAsync("background-worker-" + llvm::Twine(I),
+[this] { run(); });
+  }
   if (BuildIndexPeriodMs > 0) {
 log("BackgroundIndex: build symbol index periodically every {0} ms.",
 BuildIndexPeriodMs);
-ThreadPool.emplace_back([this] { buildIndex(); });
+ThreadPool.runAsync("background-index-builder", [this] { buildIndex(); });
   }
 }
 
 BackgroundIndex::~BackgroundIndex() {
   stop();
-  for (auto &Thread : ThreadPool)
-Thread.join();
+  ThreadPool.wait();
 }
 
 void BackgroundIndex::stop() {


Index: clang-tools-extra/clangd/index/Background.h
===
--- clang-tools-extra/clangd/index/Background.h
+++ clang-tools-extra/clangd/index/Background.h
@@ -146,7 +146,7 @@
   std::condition_variable QueueCV;
   bool ShouldStop = false;
   std::deque> Queue;
-  std::vector ThreadPool; // FIXME: Abstract this away.
+  AsyncTaskRunner ThreadPool;
   GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
 
Index: clang-tools-extra/clangd/index/Background.cpp
===
--- clang-tools-extra/clangd/index/Background.cpp
+++ clang-tools-extra/clangd/index/Background.cpp
@@ -148,19 +148,20 @@
   })) {
   assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
   assert(this->IndexStorageFactory && "Storage factory can not be null!");
-  while (ThreadPoolSize--)
-ThreadPool.emplace_back([this] { run(); });
+  for (unsigned I = 1; I <= ThreadPoolSize; ++I) {
+ThreadPool.runAsync("background-worker-" + llvm::Twine(I),
+[this] { run(); });
+  }
   if (BuildIndexPeriodMs > 0) {
 log("BackgroundIndex: build symbol index periodically every {0} ms.",
 BuildIndexPeriodMs);
-ThreadPool.emplace_back([this] { buildIndex(); });
+ThreadPool.runAsync("background-index-builder", [this] { buildIndex(); });
   }
 }
 
 BackgroundIndex::~BackgroundIndex() {
   stop();
-  for (auto &Thread : ThreadPool)
-Thread.join();
+  ThreadPool.wait();
 }
 
 void BackgroundIndex::stop() {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D50993: [clangd] Increase stack size of the new threads on macOS

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

D61724  refactors `BackgroundIndexer` to use 
`AsyncTaskRunner`. 
So by the time this lands, it should cover all places where threads are created 
in clangd.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D50993/new/

https://reviews.llvm.org/D50993



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


[PATCH] D60507: [clang-tidy] new check: bugprone-unhandled-self-assignment

2019-05-09 Thread Tamás Zolnai via Phabricator via cfe-commits
ztamas updated this revision to Diff 198787.
ztamas added a comment.

Changed "might not" to "does not" in the warning message.
Added the requested test case with the swapped template arguments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60507/new/

https://reviews.llvm.org/D60507

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-unhandled-self-assignment.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/bugprone-unhandled-self-assignment.cpp

Index: clang-tools-extra/test/clang-tidy/bugprone-unhandled-self-assignment.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/bugprone-unhandled-self-assignment.cpp
@@ -0,0 +1,579 @@
+// RUN: %check_clang_tidy %s bugprone-unhandled-self-assignment %t
+
+namespace std {
+
+template 
+void swap(T x, T y) {
+}
+
+template 
+T &&move(T x) {
+}
+
+template 
+class unique_ptr {
+};
+
+template 
+class shared_ptr {
+};
+
+template 
+class weak_ptr {
+};
+
+template 
+class auto_ptr {
+};
+
+} // namespace std
+
+void assert(int expression){};
+
+///
+/// Test cases correctly caught by the check.
+
+class PtrField {
+public:
+  PtrField &operator=(const PtrField &object);
+
+private:
+  int *p;
+};
+
+PtrField &PtrField::operator=(const PtrField &object) {
+  // CHECK-MESSAGES: [[@LINE-1]]:21: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+  // ...
+  return *this;
+}
+
+// Class with an inline operator definition.
+class InlineDefinition {
+public:
+  InlineDefinition &operator=(const InlineDefinition &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:21: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  int *p;
+};
+
+class UniquePtrField {
+public:
+  UniquePtrField &operator=(const UniquePtrField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:19: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  std::unique_ptr p;
+};
+
+class SharedPtrField {
+public:
+  SharedPtrField &operator=(const SharedPtrField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:19: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  std::shared_ptr p;
+};
+
+class WeakPtrField {
+public:
+  WeakPtrField &operator=(const WeakPtrField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:17: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  std::weak_ptr p;
+};
+
+class AutoPtrField {
+public:
+  AutoPtrField &operator=(const AutoPtrField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:17: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  std::auto_ptr p;
+};
+
+// Class with C array field.
+class CArrayField {
+public:
+  CArrayField &operator=(const CArrayField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:16: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  int array[256];
+};
+
+// Make sure to not ignore cases when the operator definition calls
+// a copy constructor of another class.
+class CopyConstruct {
+public:
+  CopyConstruct &operator=(const CopyConstruct &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:18: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+WeakPtrField a;
+WeakPtrField b(a);
+// ...
+return *this;
+  }
+
+private:
+  int *p;
+};
+
+// Make sure to not ignore cases when the operator definition calls
+// a copy assignment operator of another class.
+class AssignOperator {
+public:
+  AssignOperator &operator=(const AssignOperator &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:19: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+a.operator=(object.a);
+// ...
+return *this;
+  }
+
+private:
+  int *p;
+  WeakPtrField a;
+};
+
+class NotSelfCheck {
+public:
+  NotSelfCheck &operator=(const NotSelfCheck &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:17: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+if (&object == this->doSomething()

[PATCH] D60507: [clang-tidy] new check: bugprone-unhandled-self-assignment

2019-05-09 Thread Tamás Zolnai via Phabricator via cfe-commits
ztamas updated this revision to Diff 198789.
ztamas added a comment.

copy operator -> copy assignment operator


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60507/new/

https://reviews.llvm.org/D60507

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-unhandled-self-assignment.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/bugprone-unhandled-self-assignment.cpp

Index: clang-tools-extra/test/clang-tidy/bugprone-unhandled-self-assignment.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/bugprone-unhandled-self-assignment.cpp
@@ -0,0 +1,579 @@
+// RUN: %check_clang_tidy %s bugprone-unhandled-self-assignment %t
+
+namespace std {
+
+template 
+void swap(T x, T y) {
+}
+
+template 
+T &&move(T x) {
+}
+
+template 
+class unique_ptr {
+};
+
+template 
+class shared_ptr {
+};
+
+template 
+class weak_ptr {
+};
+
+template 
+class auto_ptr {
+};
+
+} // namespace std
+
+void assert(int expression){};
+
+///
+/// Test cases correctly caught by the check.
+
+class PtrField {
+public:
+  PtrField &operator=(const PtrField &object);
+
+private:
+  int *p;
+};
+
+PtrField &PtrField::operator=(const PtrField &object) {
+  // CHECK-MESSAGES: [[@LINE-1]]:21: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+  // ...
+  return *this;
+}
+
+// Class with an inline operator definition.
+class InlineDefinition {
+public:
+  InlineDefinition &operator=(const InlineDefinition &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:21: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  int *p;
+};
+
+class UniquePtrField {
+public:
+  UniquePtrField &operator=(const UniquePtrField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:19: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  std::unique_ptr p;
+};
+
+class SharedPtrField {
+public:
+  SharedPtrField &operator=(const SharedPtrField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:19: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  std::shared_ptr p;
+};
+
+class WeakPtrField {
+public:
+  WeakPtrField &operator=(const WeakPtrField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:17: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  std::weak_ptr p;
+};
+
+class AutoPtrField {
+public:
+  AutoPtrField &operator=(const AutoPtrField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:17: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  std::auto_ptr p;
+};
+
+// Class with C array field.
+class CArrayField {
+public:
+  CArrayField &operator=(const CArrayField &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:16: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+// ...
+return *this;
+  }
+
+private:
+  int array[256];
+};
+
+// Make sure to not ignore cases when the operator definition calls
+// a copy constructor of another class.
+class CopyConstruct {
+public:
+  CopyConstruct &operator=(const CopyConstruct &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:18: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+WeakPtrField a;
+WeakPtrField b(a);
+// ...
+return *this;
+  }
+
+private:
+  int *p;
+};
+
+// Make sure to not ignore cases when the operator definition calls
+// a copy assignment operator of another class.
+class AssignOperator {
+public:
+  AssignOperator &operator=(const AssignOperator &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:19: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+a.operator=(object.a);
+// ...
+return *this;
+  }
+
+private:
+  int *p;
+  WeakPtrField a;
+};
+
+class NotSelfCheck {
+public:
+  NotSelfCheck &operator=(const NotSelfCheck &object) {
+// CHECK-MESSAGES: [[@LINE-1]]:17: warning: operator=() does not handle self-assignment properly [bugprone-unhandled-self-assignment]
+if (&object == this->doSomething()) {
+  // ...
+}
+return *this;
+  }
+
+  void *doSomething() {
+re

[PATCH] D61724: [clangd] Use AsyncTaskRunner in BackgroundIndex instead of std::thread

2019-05-09 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang-tools-extra/clangd/index/Background.cpp:152
+  for (unsigned I = 1; I <= ThreadPoolSize; ++I) {
+ThreadPool.runAsync("background-worker-" + llvm::Twine(I),
+[this] { run(); });

NIT: why not count from zero :P



Comment at: clang-tools-extra/clangd/index/Background.cpp:164
   stop();
-  for (auto &Thread : ThreadPool)
-Thread.join();
+  ThreadPool.wait();
 }

Destructor of `AsyncTaskRunner` already does that


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61724/new/

https://reviews.llvm.org/D61724



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


[PATCH] D60507: [clang-tidy] new check: bugprone-unhandled-self-assignment

2019-05-09 Thread Tamás Zolnai via Phabricator via cfe-commits
ztamas added a comment.

> I definitely want to see the diagnostic text changed away from "might be" -- 
> that's too noncommittal for my tastes. I'd also like to see the additional 
> test case (I suspect it will just work out of the box, but if it doesn't, it 
> would be good to know about it). The CERT alias is a bit more of a grey area 
> -- I'd like to insist on it being added because it's trivial, it improves the 
> behavior of this check by introducing an option some users will want, and 
> checks conforming to coding standards are always more compelling than one-off 
> checks. However, you seem very resistant to that and I don't want to add to 
> your work load if you are opposed to doing it, so I don't insist on the 
> change.

During LibreOffice development, I'm socialized to keep a patch as small as 
possible. Versioning history can be more "clean" with smaller patches. For 
example, it's easier to find and fix regressions
with bisecting. Also smaller patches make the review process faster, etc. 
That's why I'm trying to separate what is absolutely necessary to include and 
what can be cut off from this patch.

I changed the warning message and I added the requested test case. This test 
case is ignored by the check as expected.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60507/new/

https://reviews.llvm.org/D60507



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


[PATCH] D53072: [clang-format] Create a new tool for IDEs based on clang-format

2019-05-09 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

@ilya-biryukov
I don't really care how it's used from the tool side. I'm also fine to have a 
new option in clang-format itself. That's why this review is here - to ask for 
opinions. It's easy to remove that "ide" part from this patch and just add an 
option for clang-format instead.
Do you have any other remarks/concerns apart from that?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D53072/new/

https://reviews.llvm.org/D53072



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


r360330 - [OpenCL] Switched CXX mode to be derived from C++17

2019-05-09 Thread Anastasia Stulova via cfe-commits
Author: stulova
Date: Thu May  9 04:55:24 2019
New Revision: 360330

URL: http://llvm.org/viewvc/llvm-project?rev=360330&view=rev
Log:
[OpenCL] Switched CXX mode to be derived from C++17

Differential revision: https://reviews.llvm.org/D61506


Modified:
cfe/trunk/include/clang/Frontend/LangStandards.def
cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl

Modified: cfe/trunk/include/clang/Frontend/LangStandards.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/LangStandards.def?rev=360330&r1=360329&r2=360330&view=diff
==
--- cfe/trunk/include/clang/Frontend/LangStandards.def (original)
+++ cfe/trunk/include/clang/Frontend/LangStandards.def Thu May  9 04:55:24 2019
@@ -159,7 +159,8 @@ LANGSTANDARD(opencl20, "cl2.0",
  LineComment | C99 | Digraphs | HexFloat | OpenCL)
 LANGSTANDARD(openclcpp, "c++",
  OpenCL, "OpenCL C++ 1.0",
- LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | Digraphs | 
OpenCL)
+ LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus17 
|
+ Digraphs | HexFloat | OpenCL)
 
 LANGSTANDARD_ALIAS_DEPR(opencl10, "CL")
 LANGSTANDARD_ALIAS_DEPR(opencl11, "CL1.1")

Modified: cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl?rev=360330&r1=360329&r2=360330&view=diff
==
--- cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl (original)
+++ cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl Thu May  9 04:55:24 
2019
@@ -112,15 +112,9 @@ __kernel void test__global() {
 // IMPL: call void @llvm.memcpy.p4i8.p4i8.i32(i8 addrspace(4)* 
{{.*}}[[C2GENVOID]], i8 addrspace(4)* {{.*}}[[C1GENVOID]]
 
 // Test the address space of 'this' when invoking the operator+
-// COMMON: [[C3GEN:%[0-9]+]] = addrspacecast %class.C* %c3 to %class.C 
addrspace(4)*
 // COMMON: [[C1GEN:%[0-9]+]] = addrspacecast %class.C* %c1 to %class.C 
addrspace(4)*
 // COMMON: [[C2GEN:%[0-9]+]] = addrspacecast %class.C* %c2 to %class.C 
addrspace(4)*
-// COMMON: call void @_ZNU3AS41CplERU3AS4KS_(%class.C* sret %ref.tmp, %class.C 
addrspace(4)* [[C1GEN]], %class.C addrspace(4)* dereferenceable(4) [[C2GEN]])
-// COMMON: [[REFGEN:%[0-9]+]] = addrspacecast %class.C* %ref.tmp to %class.C 
addrspace(4)*
-// EXPL: call void @_ZNU3AS41CC1EOU3AS4S_(%class.C addrspace(4)* [[C3GEN]], 
%class.C addrspace(4)* dereferenceable(4) [[REFGEN]])
-// IMPL: [[C3VOID:%[0-9]+]] = bitcast %class.C* %c3 to i8*
-// IMPL: [[REFGENVOID:%[0-9]+]] = bitcast %class.C addrspace(4)* [[REFGEN]] to 
i8 addrspace(4)*
-// IMPL: call void @llvm.memcpy.p0i8.p4i8.i32(i8* {{.*}}[[C3VOID]], i8 
addrspace(4)* {{.*}}[[REFGENVOID]]
+// COMMON: call void @_ZNU3AS41CplERU3AS4KS_(%class.C* sret %c3, %class.C 
addrspace(4)* [[C1GEN]], %class.C addrspace(4)* dereferenceable(4) [[C2GEN]])
 
 // Test the address space of 'this' when invoking the move constructor
 // COMMON: [[C4GEN:%[0-9]+]] = addrspacecast %class.C* %c4 to %class.C 
addrspace(4)*


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


[PATCH] D61724: [clangd] Use AsyncTaskRunner in BackgroundIndex instead of std::thread

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 198791.
ilya-biryukov marked 4 inline comments as done.
ilya-biryukov added a comment.

- Count from 0.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61724/new/

https://reviews.llvm.org/D61724

Files:
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/Background.h


Index: clang-tools-extra/clangd/index/Background.h
===
--- clang-tools-extra/clangd/index/Background.h
+++ clang-tools-extra/clangd/index/Background.h
@@ -146,7 +146,7 @@
   std::condition_variable QueueCV;
   bool ShouldStop = false;
   std::deque> Queue;
-  std::vector ThreadPool; // FIXME: Abstract this away.
+  AsyncTaskRunner ThreadPool;
   GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
 
Index: clang-tools-extra/clangd/index/Background.cpp
===
--- clang-tools-extra/clangd/index/Background.cpp
+++ clang-tools-extra/clangd/index/Background.cpp
@@ -148,19 +148,20 @@
   })) {
   assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
   assert(this->IndexStorageFactory && "Storage factory can not be null!");
-  while (ThreadPoolSize--)
-ThreadPool.emplace_back([this] { run(); });
+  for (unsigned I = 0; I < ThreadPoolSize; ++I) {
+ThreadPool.runAsync("background-worker-" + llvm::Twine(I + 1),
+[this] { run(); });
+  }
   if (BuildIndexPeriodMs > 0) {
 log("BackgroundIndex: build symbol index periodically every {0} ms.",
 BuildIndexPeriodMs);
-ThreadPool.emplace_back([this] { buildIndex(); });
+ThreadPool.runAsync("background-index-builder", [this] { buildIndex(); });
   }
 }
 
 BackgroundIndex::~BackgroundIndex() {
   stop();
-  for (auto &Thread : ThreadPool)
-Thread.join();
+  ThreadPool.wait();
 }
 
 void BackgroundIndex::stop() {


Index: clang-tools-extra/clangd/index/Background.h
===
--- clang-tools-extra/clangd/index/Background.h
+++ clang-tools-extra/clangd/index/Background.h
@@ -146,7 +146,7 @@
   std::condition_variable QueueCV;
   bool ShouldStop = false;
   std::deque> Queue;
-  std::vector ThreadPool; // FIXME: Abstract this away.
+  AsyncTaskRunner ThreadPool;
   GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
 
Index: clang-tools-extra/clangd/index/Background.cpp
===
--- clang-tools-extra/clangd/index/Background.cpp
+++ clang-tools-extra/clangd/index/Background.cpp
@@ -148,19 +148,20 @@
   })) {
   assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
   assert(this->IndexStorageFactory && "Storage factory can not be null!");
-  while (ThreadPoolSize--)
-ThreadPool.emplace_back([this] { run(); });
+  for (unsigned I = 0; I < ThreadPoolSize; ++I) {
+ThreadPool.runAsync("background-worker-" + llvm::Twine(I + 1),
+[this] { run(); });
+  }
   if (BuildIndexPeriodMs > 0) {
 log("BackgroundIndex: build symbol index periodically every {0} ms.",
 BuildIndexPeriodMs);
-ThreadPool.emplace_back([this] { buildIndex(); });
+ThreadPool.runAsync("background-index-builder", [this] { buildIndex(); });
   }
 }
 
 BackgroundIndex::~BackgroundIndex() {
   stop();
-  for (auto &Thread : ThreadPool)
-Thread.join();
+  ThreadPool.wait();
 }
 
 void BackgroundIndex::stop() {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61724: [clangd] Use AsyncTaskRunner in BackgroundIndex instead of std::thread

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/index/Background.cpp:152
+  for (unsigned I = 1; I <= ThreadPoolSize; ++I) {
+ThreadPool.runAsync("background-worker-" + llvm::Twine(I),
+[this] { run(); });

kadircet wrote:
> NIT: why not count from zero :P
Done. The worker numbers still start with 1, sorry about that :-)



Comment at: clang-tools-extra/clangd/index/Background.cpp:164
   stop();
-  for (auto &Thread : ThreadPool)
-Thread.join();
+  ThreadPool.wait();
 }

kadircet wrote:
> Destructor of `AsyncTaskRunner` already does that
Yeah, but then we'll have to ensure the `AsyncTaskRunner` is the last member 
(I've been bitten by this before).
Having an explicit call to `wait()` in the destructor is bulletproof.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61724/new/

https://reviews.llvm.org/D61724



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


[PATCH] D61506: [OpenCL] Switch to C++17

2019-05-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL360330: [OpenCL] Switched CXX mode to be derived from C++17 
(authored by stulova, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D61506?vs=198627&id=198792#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61506/new/

https://reviews.llvm.org/D61506

Files:
  cfe/trunk/include/clang/Frontend/LangStandards.def
  cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl


Index: cfe/trunk/include/clang/Frontend/LangStandards.def
===
--- cfe/trunk/include/clang/Frontend/LangStandards.def
+++ cfe/trunk/include/clang/Frontend/LangStandards.def
@@ -159,7 +159,8 @@
  LineComment | C99 | Digraphs | HexFloat | OpenCL)
 LANGSTANDARD(openclcpp, "c++",
  OpenCL, "OpenCL C++ 1.0",
- LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | Digraphs | 
OpenCL)
+ LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus17 
|
+ Digraphs | HexFloat | OpenCL)
 
 LANGSTANDARD_ALIAS_DEPR(opencl10, "CL")
 LANGSTANDARD_ALIAS_DEPR(opencl11, "CL1.1")
Index: cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl
===
--- cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl
+++ cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl
@@ -112,15 +112,9 @@
 // IMPL: call void @llvm.memcpy.p4i8.p4i8.i32(i8 addrspace(4)* 
{{.*}}[[C2GENVOID]], i8 addrspace(4)* {{.*}}[[C1GENVOID]]
 
 // Test the address space of 'this' when invoking the operator+
-// COMMON: [[C3GEN:%[0-9]+]] = addrspacecast %class.C* %c3 to %class.C 
addrspace(4)*
 // COMMON: [[C1GEN:%[0-9]+]] = addrspacecast %class.C* %c1 to %class.C 
addrspace(4)*
 // COMMON: [[C2GEN:%[0-9]+]] = addrspacecast %class.C* %c2 to %class.C 
addrspace(4)*
-// COMMON: call void @_ZNU3AS41CplERU3AS4KS_(%class.C* sret %ref.tmp, %class.C 
addrspace(4)* [[C1GEN]], %class.C addrspace(4)* dereferenceable(4) [[C2GEN]])
-// COMMON: [[REFGEN:%[0-9]+]] = addrspacecast %class.C* %ref.tmp to %class.C 
addrspace(4)*
-// EXPL: call void @_ZNU3AS41CC1EOU3AS4S_(%class.C addrspace(4)* [[C3GEN]], 
%class.C addrspace(4)* dereferenceable(4) [[REFGEN]])
-// IMPL: [[C3VOID:%[0-9]+]] = bitcast %class.C* %c3 to i8*
-// IMPL: [[REFGENVOID:%[0-9]+]] = bitcast %class.C addrspace(4)* [[REFGEN]] to 
i8 addrspace(4)*
-// IMPL: call void @llvm.memcpy.p0i8.p4i8.i32(i8* {{.*}}[[C3VOID]], i8 
addrspace(4)* {{.*}}[[REFGENVOID]]
+// COMMON: call void @_ZNU3AS41CplERU3AS4KS_(%class.C* sret %c3, %class.C 
addrspace(4)* [[C1GEN]], %class.C addrspace(4)* dereferenceable(4) [[C2GEN]])
 
 // Test the address space of 'this' when invoking the move constructor
 // COMMON: [[C4GEN:%[0-9]+]] = addrspacecast %class.C* %c4 to %class.C 
addrspace(4)*


Index: cfe/trunk/include/clang/Frontend/LangStandards.def
===
--- cfe/trunk/include/clang/Frontend/LangStandards.def
+++ cfe/trunk/include/clang/Frontend/LangStandards.def
@@ -159,7 +159,8 @@
  LineComment | C99 | Digraphs | HexFloat | OpenCL)
 LANGSTANDARD(openclcpp, "c++",
  OpenCL, "OpenCL C++ 1.0",
- LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | Digraphs | OpenCL)
+ LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus17 |
+ Digraphs | HexFloat | OpenCL)
 
 LANGSTANDARD_ALIAS_DEPR(opencl10, "CL")
 LANGSTANDARD_ALIAS_DEPR(opencl11, "CL1.1")
Index: cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl
===
--- cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl
+++ cfe/trunk/test/CodeGenOpenCLCXX/addrspace-of-this.cl
@@ -112,15 +112,9 @@
 // IMPL: call void @llvm.memcpy.p4i8.p4i8.i32(i8 addrspace(4)* {{.*}}[[C2GENVOID]], i8 addrspace(4)* {{.*}}[[C1GENVOID]]
 
 // Test the address space of 'this' when invoking the operator+
-// COMMON: [[C3GEN:%[0-9]+]] = addrspacecast %class.C* %c3 to %class.C addrspace(4)*
 // COMMON: [[C1GEN:%[0-9]+]] = addrspacecast %class.C* %c1 to %class.C addrspace(4)*
 // COMMON: [[C2GEN:%[0-9]+]] = addrspacecast %class.C* %c2 to %class.C addrspace(4)*
-// COMMON: call void @_ZNU3AS41CplERU3AS4KS_(%class.C* sret %ref.tmp, %class.C addrspace(4)* [[C1GEN]], %class.C addrspace(4)* dereferenceable(4) [[C2GEN]])
-// COMMON: [[REFGEN:%[0-9]+]] = addrspacecast %class.C* %ref.tmp to %class.C addrspace(4)*
-// EXPL: call void @_ZNU3AS41CC1EOU3AS4S_(%class.C addrspace(4)* [[C3GEN]], %class.C addrspace(4)* dereferenceable(4) [[REFGEN]])
-// IMPL: [[C3VOID:%[0-9]+]] = bitcast %class.C* %c3 to i8*
-// IMPL: [[REFGENVOID:%[0-9]+]] = bitcast %class.C addrspace(4)* [[REFGEN]] to i8 addrspace(4)*
-// IMPL: call void @llvm.memcpy.p0i8.p4i8.i32(i8* {{.*}}[[C3VOID]], i8 addrspace(4)* {{.*}}[[REF

[PATCH] D61724: [clangd] Use AsyncTaskRunner in BackgroundIndex instead of std::thread

2019-05-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL360332: [clangd] Use AsyncTaskRunner in BackgroundIndex 
instead of std::thread (authored by ibiryukov, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D61724?vs=198791&id=198795#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61724/new/

https://reviews.llvm.org/D61724

Files:
  clang-tools-extra/trunk/clangd/index/Background.cpp
  clang-tools-extra/trunk/clangd/index/Background.h


Index: clang-tools-extra/trunk/clangd/index/Background.h
===
--- clang-tools-extra/trunk/clangd/index/Background.h
+++ clang-tools-extra/trunk/clangd/index/Background.h
@@ -146,7 +146,7 @@
   std::condition_variable QueueCV;
   bool ShouldStop = false;
   std::deque> Queue;
-  std::vector ThreadPool; // FIXME: Abstract this away.
+  AsyncTaskRunner ThreadPool;
   GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
 
Index: clang-tools-extra/trunk/clangd/index/Background.cpp
===
--- clang-tools-extra/trunk/clangd/index/Background.cpp
+++ clang-tools-extra/trunk/clangd/index/Background.cpp
@@ -148,19 +148,20 @@
   })) {
   assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
   assert(this->IndexStorageFactory && "Storage factory can not be null!");
-  while (ThreadPoolSize--)
-ThreadPool.emplace_back([this] { run(); });
+  for (unsigned I = 0; I < ThreadPoolSize; ++I) {
+ThreadPool.runAsync("background-worker-" + llvm::Twine(I + 1),
+[this] { run(); });
+  }
   if (BuildIndexPeriodMs > 0) {
 log("BackgroundIndex: build symbol index periodically every {0} ms.",
 BuildIndexPeriodMs);
-ThreadPool.emplace_back([this] { buildIndex(); });
+ThreadPool.runAsync("background-index-builder", [this] { buildIndex(); });
   }
 }
 
 BackgroundIndex::~BackgroundIndex() {
   stop();
-  for (auto &Thread : ThreadPool)
-Thread.join();
+  ThreadPool.wait();
 }
 
 void BackgroundIndex::stop() {


Index: clang-tools-extra/trunk/clangd/index/Background.h
===
--- clang-tools-extra/trunk/clangd/index/Background.h
+++ clang-tools-extra/trunk/clangd/index/Background.h
@@ -146,7 +146,7 @@
   std::condition_variable QueueCV;
   bool ShouldStop = false;
   std::deque> Queue;
-  std::vector ThreadPool; // FIXME: Abstract this away.
+  AsyncTaskRunner ThreadPool;
   GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
 
Index: clang-tools-extra/trunk/clangd/index/Background.cpp
===
--- clang-tools-extra/trunk/clangd/index/Background.cpp
+++ clang-tools-extra/trunk/clangd/index/Background.cpp
@@ -148,19 +148,20 @@
   })) {
   assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
   assert(this->IndexStorageFactory && "Storage factory can not be null!");
-  while (ThreadPoolSize--)
-ThreadPool.emplace_back([this] { run(); });
+  for (unsigned I = 0; I < ThreadPoolSize; ++I) {
+ThreadPool.runAsync("background-worker-" + llvm::Twine(I + 1),
+[this] { run(); });
+  }
   if (BuildIndexPeriodMs > 0) {
 log("BackgroundIndex: build symbol index periodically every {0} ms.",
 BuildIndexPeriodMs);
-ThreadPool.emplace_back([this] { buildIndex(); });
+ThreadPool.runAsync("background-index-builder", [this] { buildIndex(); });
   }
 }
 
 BackgroundIndex::~BackgroundIndex() {
   stop();
-  for (auto &Thread : ThreadPool)
-Thread.join();
+  ThreadPool.wait();
 }
 
 void BackgroundIndex::stop() {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61566: Fix for bug 41747: AST Printer doesn't print nested name specifier for out of scope record definitions

2019-05-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM!


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61566/new/

https://reviews.llvm.org/D61566



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


[clang-tools-extra] r360332 - [clangd] Use AsyncTaskRunner in BackgroundIndex instead of std::thread

2019-05-09 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Thu May  9 05:04:07 2019
New Revision: 360332

URL: http://llvm.org/viewvc/llvm-project?rev=360332&view=rev
Log:
[clangd] Use AsyncTaskRunner in BackgroundIndex instead of std::thread

Summary:
To unify the way we create threads in clangd.
This should simplify landing D50993.

Reviewers: kadircet

Reviewed By: kadircet

Subscribers: MaskRay, jkorous, arphaman, jfb, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/index/Background.cpp
clang-tools-extra/trunk/clangd/index/Background.h

Modified: clang-tools-extra/trunk/clangd/index/Background.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Background.cpp?rev=360332&r1=360331&r2=360332&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Background.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Background.cpp Thu May  9 05:04:07 2019
@@ -148,19 +148,20 @@ BackgroundIndex::BackgroundIndex(
   })) {
   assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
   assert(this->IndexStorageFactory && "Storage factory can not be null!");
-  while (ThreadPoolSize--)
-ThreadPool.emplace_back([this] { run(); });
+  for (unsigned I = 0; I < ThreadPoolSize; ++I) {
+ThreadPool.runAsync("background-worker-" + llvm::Twine(I + 1),
+[this] { run(); });
+  }
   if (BuildIndexPeriodMs > 0) {
 log("BackgroundIndex: build symbol index periodically every {0} ms.",
 BuildIndexPeriodMs);
-ThreadPool.emplace_back([this] { buildIndex(); });
+ThreadPool.runAsync("background-index-builder", [this] { buildIndex(); });
   }
 }
 
 BackgroundIndex::~BackgroundIndex() {
   stop();
-  for (auto &Thread : ThreadPool)
-Thread.join();
+  ThreadPool.wait();
 }
 
 void BackgroundIndex::stop() {

Modified: clang-tools-extra/trunk/clangd/index/Background.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Background.h?rev=360332&r1=360331&r2=360332&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Background.h (original)
+++ clang-tools-extra/trunk/clangd/index/Background.h Thu May  9 05:04:07 2019
@@ -146,7 +146,7 @@ private:
   std::condition_variable QueueCV;
   bool ShouldStop = false;
   std::deque> Queue;
-  std::vector ThreadPool; // FIXME: Abstract this away.
+  AsyncTaskRunner ThreadPool;
   GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
 


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


[PATCH] D53072: [clang-format] Create a new tool for IDEs based on clang-format

2019-05-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

My feedback would be:

- I definitely think more control over preserving line breaks would be useful. 
Actually preserving *blank* lines is an important property. If you see D60605 
, there are a lot of cases where clang-format 
wants to delete the line you just added. Maybe we can make 
`MaxEmptyLinesToKeep: 999` work in more cases.
- I'm not convinced you need/want to preserve *all* line breaks, isn't it just 
one? (where the user pressed enter)
- It's unclear why "extraformattingoptions" is needed, rather than just the 
usual formatting options, or some other parameter. It would be nice to avoid a 
new library entry point (overload) if possible.
- as far as command-line interface goes, this definitely feels more like a flag 
than a new tool


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D53072/new/

https://reviews.llvm.org/D53072



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


r360333 - Fix gcc compilation warning in an assert [NFC]

2019-05-09 Thread Mikael Holmen via cfe-commits
Author: uabelho
Date: Thu May  9 05:11:57 2019
New Revision: 360333

URL: http://llvm.org/viewvc/llvm-project?rev=360333&view=rev
Log:
Fix gcc compilation warning in an assert [NFC]

Without this, gcc (7.4) complains with

../tools/clang/lib/Parse/ParseDecl.cpp:3937:63: error: suggest parentheses 
around '&&' within '||' [-Werror=parentheses]
 assert(!isAlreadyConsumed || RangeEnd != SourceLocation() &&
  ~^~
  "both or neither of isAlreadyConsumed and 
"
  
~~~
  "RangeEnd needs to be set");
  ~

Modified:
cfe/trunk/lib/Parse/ParseDecl.cpp

Modified: cfe/trunk/lib/Parse/ParseDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseDecl.cpp?rev=360333&r1=360332&r2=360333&view=diff
==
--- cfe/trunk/lib/Parse/ParseDecl.cpp (original)
+++ cfe/trunk/lib/Parse/ParseDecl.cpp Thu May  9 05:11:57 2019
@@ -3934,7 +3934,7 @@ void Parser::ParseDeclarationSpecifiers(
   continue;
 }
 
-assert(!isAlreadyConsumed || RangeEnd != SourceLocation() &&
+assert((!isAlreadyConsumed || RangeEnd != SourceLocation()) &&
  "both or neither of isAlreadyConsumed and 
"
  "RangeEnd needs to be set");
 DS.SetRangeEnd(isAlreadyConsumed ? RangeEnd : Tok.getLocation());


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


[clang-tools-extra] r360334 - Fix gcc compilation warning in test case [NFC]

2019-05-09 Thread Mikael Holmen via cfe-commits
Author: uabelho
Date: Thu May  9 05:12:35 2019
New Revision: 360334

URL: http://llvm.org/viewvc/llvm-project?rev=360334&view=rev
Log:
Fix gcc compilation warning in test case [NFC]

Without this, gcc (7.4) complains with

../tools/clang/tools/extra/clangd/unittests/PrintASTTests.cpp:99:28: error: ISO 
C++11 requires at least one argument for the "..." in a variadic macro [-Werror]
 })));
^

Modified:
clang-tools-extra/trunk/clangd/unittests/PrintASTTests.cpp

Modified: clang-tools-extra/trunk/clangd/unittests/PrintASTTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/PrintASTTests.cpp?rev=360334&r1=360333&r2=360334&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/PrintASTTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/PrintASTTests.cpp Thu May  9 
05:12:35 2019
@@ -96,7 +96,7 @@ INSTANTIATE_TEST_CASE_P(ASTUtilsTests, A
   struct Bar { friend class Foo; };
   template <> struct ^Foo {};)cpp",
 {""}},
-})));
+})),);
 } // namespace
 } // namespace clangd
 } // namespace clang


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


[clang-tools-extra] r360336 - [clangd] Fix a TSAN warning in TUSchedulerTests

2019-05-09 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Thu May  9 05:21:28 2019
New Revision: 360336

URL: http://llvm.org/viewvc/llvm-project?rev=360336&view=rev
Log:
[clangd] Fix a TSAN warning in TUSchedulerTests

Modified:
clang-tools-extra/trunk/clangd/unittests/TUSchedulerTests.cpp

Modified: clang-tools-extra/trunk/clangd/unittests/TUSchedulerTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/TUSchedulerTests.cpp?rev=360336&r1=360335&r2=360336&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/TUSchedulerTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/TUSchedulerTests.cpp Thu May  9 
05:21:28 2019
@@ -673,10 +673,14 @@ TEST_F(TUSchedulerTests, TUStatus) {
   AllStatus.push_back(Status);
 }
 
-std::vector AllStatus;
+std::vector allStatus() {
+  std::lock_guard Lock(Mutex);
+  return AllStatus;
+}
 
   private:
 std::mutex Mutex;
+std::vector AllStatus;
   } CaptureTUStatus;
   MockFSProvider FS;
   MockCompilationDatabase CDB;
@@ -693,7 +697,7 @@ TEST_F(TUSchedulerTests, TUStatus) {
 
   ASSERT_TRUE(Server.blockUntilIdleForTest());
 
-  EXPECT_THAT(CaptureTUStatus.AllStatus,
+  EXPECT_THAT(CaptureTUStatus.allStatus(),
   ElementsAre(
   // Statuses of "Update" action.
   TUState(TUAction::RunningAction, "Update"),


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


[PATCH] D60456: [RISCV][WIP/RFC] Hard float ABI support

2019-05-09 Thread Alex Bradbury via Phabricator via cfe-commits
asb updated this revision to Diff 198797.
asb marked 3 inline comments as done.
asb added a comment.

Update:

- Expanded and improved tests
- Set ABI defines
- Remove errant TODO
- Use alignTo

Still to do:

- Review and test bitfield handling (which is likely incomplete)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60456/new/

https://reviews.llvm.org/D60456

Files:
  clang/lib/Basic/Targets/RISCV.cpp
  clang/lib/Basic/Targets/RISCV.h
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/riscv32-ilp32-ilp32f-abi.c
  clang/test/CodeGen/riscv32-ilp32-ilp32f-ilp32d-abi.c
  clang/test/CodeGen/riscv32-ilp32d-abi.c
  clang/test/CodeGen/riscv32-ilp32f-abi.c
  clang/test/CodeGen/riscv32-ilp32f-ilp32d-abi.c
  clang/test/CodeGen/riscv64-lp64-lp64f-abi.c
  clang/test/CodeGen/riscv64-lp64-lp64f-lp64d-abi.c
  clang/test/CodeGen/riscv64-lp64d-abi.c
  clang/test/CodeGen/riscv64-lp64f-lp64d-abi.c

Index: clang/test/CodeGen/riscv64-lp64f-lp64d-abi.c
===
--- /dev/null
+++ clang/test/CodeGen/riscv64-lp64f-lp64d-abi.c
@@ -0,0 +1,222 @@
+// RUN: %clang_cc1 -triple riscv64 -target-feature +f -target-abi lp64f -emit-llvm %s -o - \
+// RUN: | FileCheck %s
+// RUN: %clang_cc1 -triple riscv64 -target-feature +d -target-abi lp64d -emit-llvm %s -o - \
+// RUN: | FileCheck %s
+
+#include 
+
+// Verify that the tracking of used GPRs and FPRs works correctly by checking
+// that small integers are sign/zero extended when passed in registers.
+
+// Floats are passed in FPRs, so argument 'i' will be passed zero-extended
+// because it will be passed in a GPR.
+
+// CHECK: define void @f_fpr_tracking(float %a, float %b, float %c, float %d, float %e, float %f, float %g, float %h, i8 zeroext %i)
+void f_fpr_tracking(float a, float b, float c, float d, float e, float f,
+float g, float h, uint8_t i) {}
+
+// Check that fp, fp+fp, and int+fp structs are lowered correctly. These will
+// be passed in FPR, FPR+FPR, or GPR+FPR regs if sufficient registers are
+// available the widths are <= XLEN and FLEN, and should be expanded to
+// separate arguments in IR. They are passed by the same rules for returns,
+// but will be lowered to simple two-element structs if necessary (as LLVM IR
+// functions cannot return multiple values).
+
+// A struct containing just one floating-point real is passed as though it
+// were a standalone floating-point real.
+
+struct float_s { float f; };
+
+// CHECK: define void @f_float_s_arg(float)
+void f_float_s_arg(struct float_s a) {}
+
+// CHECK: define float @f_ret_float_s()
+struct float_s f_ret_float_s() {
+  return (struct float_s){1.0};
+}
+
+// Check that structs containing two float values (FLEN <= width) are expanded
+// provided sufficient FPRs are available.
+
+struct float_float_s { float f; float g; };
+
+// CHECK: define void @f_float_float_s_arg(float, float)
+void f_float_float_s_arg(struct float_float_s a) {}
+
+// CHECK: define { float, float } @f_ret_float_float_s()
+struct float_float_s f_ret_float_float_s() {
+  return (struct float_float_s){1.0, 2.0};
+}
+
+// CHECK: define void @f_float_float_s_arg_insufficient_fprs(float %a, float %b, float %c, float %d, float %e, float %f, float %g, i64 %h.coerce)
+void f_float_float_s_arg_insufficient_fprs(float a, float b, float c, float d,
+float e, float f, float g, struct float_float_s h) {}
+
+// Check that structs containing int+float values are expanded, provided
+// sufficient FPRs and GPRs are available. The integer components are neither
+// sign or zero-extended.
+
+struct float_int8_s { float f; int8_t i; };
+struct float_uint8_s { float f; uint8_t i; };
+struct float_int32_s { float f; int32_t i; };
+struct float_int64_s { float f; int64_t i; };
+
+// CHECK: define void @f_float_int8_s_arg(float, i8)
+void f_float_int8_s_arg(struct float_int8_s a) {}
+
+// CHECK: define { float, i8 } @f_ret_float_int8_s()
+struct float_int8_s f_ret_float_int8_s() {
+  return (struct float_int8_s){1.0, 2};
+}
+
+// CHECK: define void @f_float_uint8_s_arg(float, i8)
+void f_float_uint8_s_arg(struct float_uint8_s a) {}
+
+// CHECK: define { float, i8 } @f_ret_float_uint8_s()
+struct float_uint8_s f_ret_float_uint8_s() {
+  return (struct float_uint8_s){1.0, 2};
+}
+
+// CHECK: define void @f_float_int32_s_arg(float, i32)
+void f_float_int32_s_arg(struct float_int32_s a) {}
+
+// CHECK: define { float, i32 } @f_ret_float_int32_s()
+struct float_int32_s f_ret_float_int32_s() {
+  return (struct float_int32_s){1.0, 2};
+}
+
+// CHECK: define void @f_float_int64_s_arg(float, i64)
+void f_float_int64_s_arg(struct float_int64_s a) {}
+
+// CHECK: define { float, i64 } @f_ret_float_int64_s()
+struct float_int64_s f_ret_float_int64_s() {
+  return (struct float_int64_s){1.0, 2};
+}
+
+// CHECK: define void @f_float_int8_s_arg_insufficient_gprs(i32 signext %a, i32 signext %b, i32 signext %c, i32 signext %d, i32 signext %e, i32 signext %f, i32 signext %g, i32 signe

[PATCH] D53866: [Preamble] Stop circular inclusion of main file when building preamble

2019-05-09 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik marked an inline comment as done.
nik added inline comments.



Comment at: lib/Basic/SourceManager.cpp:1594
 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
-if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) 
{
+if (MainFile && *SourceFileName == 
llvm::sys::path::filename(MainFile->getName())) {
   SourceFileUID = getActualFileUID(SourceFile);

ilya-biryukov wrote:
> Can this actually be`null`? 
The comment for OrigEntry states that it might be null:

/// Reference to the file entry representing this ContentCache.
///
/// This reference does not own the FileEntry object.
///
/// It is possible for this to be NULL if the ContentCache encapsulates
/// an imaginary text buffer.
const FileEntry *OrigEntry;

Note also that further down in this function, a null check for 
MainContentCache->OrigEntry is done, so I believe that this was just forgotten 
here (since there is also no assert) and we are the first one running into this 
with the introduced call to SourceMgr.translateFile(File).

I've tried to understand why we end up with a nullptr here, but this goes 
beyond me in the time I've taken for this. What I've observed is that module 
code path (LibclangReparseTest.ReparseWithModule vs 
LibclangReparseTest.Reparse) creates at least a MemoryBuffer more (in 
ModuleMap::parseModuleMapFile; possibly the one referred with "imaginary text 
buffer" from the comment) and I suspect this to be somehow related with the 
OrigEntry nullptr.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D53866/new/

https://reviews.llvm.org/D53866



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


[PATCH] D53866: [Preamble] Stop circular inclusion of main file when building preamble

2019-05-09 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik updated this revision to Diff 198799.
nik added a comment.

Moved the MainFile / MainContentCache->OrigEntry check a bit further up, for
consistency with the same test further down in SourceManager::translateFile().


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D53866/new/

https://reviews.llvm.org/D53866

Files:
  include/clang/Basic/DiagnosticLexKinds.td
  lib/Basic/SourceManager.cpp
  lib/Lex/PPDirectives.cpp
  test/Index/preamble-cyclic-include.cpp


Index: test/Index/preamble-cyclic-include.cpp
===
--- /dev/null
+++ test/Index/preamble-cyclic-include.cpp
@@ -0,0 +1,9 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test 
-test-annotate-tokens=%s:5:1:10:1 %s 2>&1 | FileCheck %s
+// CHECK-NOT: error: unterminated conditional directive
+// CHECK-NOT: Skipping: [4:1 - 8:7]
+// CHECK: error: main file cannot be included recursively when building a 
preamble
+#ifndef A_H
+#define A_H
+#  include "preamble-cyclic-include.cpp"
+int bar();
+#endif
Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1871,6 +1871,18 @@
 return {ImportAction::None};
   }
 
+  // Check for circular inclusion of the main file.
+  // We can't generate a consistent preamble with regard to the conditional
+  // stack if the main file is included again as due to the preamble bounds
+  // some directives (e.g. #endif of a header guard) will never be seen.
+  // Since this will lead to confusing errors, avoid the inclusion.
+  if (File && PreambleConditionalStack.isRecording() &&
+  SourceMgr.translateFile(File) == SourceMgr.getMainFileID()) {
+Diag(FilenameTok.getLocation(),
+ diag::err_pp_including_mainfile_for_preamble);
+return {ImportAction::None};
+  }
+
   // Should we enter the source file? Set to Skip if either the source file is
   // known to have no effect beyond its effect on module visibility -- that is,
   // if it's got an include guard that is already defined, set to Import if it
Index: lib/Basic/SourceManager.cpp
===
--- lib/Basic/SourceManager.cpp
+++ lib/Basic/SourceManager.cpp
@@ -1582,7 +1582,7 @@
 if (MainSLoc.isFile()) {
   const ContentCache *MainContentCache
 = MainSLoc.getFile().getContentCache();
-  if (!MainContentCache) {
+  if (!MainContentCache || !MainContentCache->OrigEntry) {
 // Can't do anything
   } else if (MainContentCache->OrigEntry == SourceFile) {
 FirstFID = MainFileID;
Index: include/clang/Basic/DiagnosticLexKinds.td
===
--- include/clang/Basic/DiagnosticLexKinds.td
+++ include/clang/Basic/DiagnosticLexKinds.td
@@ -426,6 +426,8 @@
   "did not find header '%0' in framework '%1' (loaded from '%2')">;
 def err_pp_error_opening_file : Error<
   "error opening file '%0': %1">, DefaultFatal;
+def err_pp_including_mainfile_for_preamble : Error<
+  "main file cannot be included recursively when building a preamble">;
 def err_pp_empty_filename : Error<"empty filename">;
 def err_pp_include_too_deep : Error<"#include nested too deeply">;
 def err_pp_expects_filename : Error<"expected \"FILENAME\" or ">;


Index: test/Index/preamble-cyclic-include.cpp
===
--- /dev/null
+++ test/Index/preamble-cyclic-include.cpp
@@ -0,0 +1,9 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-annotate-tokens=%s:5:1:10:1 %s 2>&1 | FileCheck %s
+// CHECK-NOT: error: unterminated conditional directive
+// CHECK-NOT: Skipping: [4:1 - 8:7]
+// CHECK: error: main file cannot be included recursively when building a preamble
+#ifndef A_H
+#define A_H
+#  include "preamble-cyclic-include.cpp"
+int bar();
+#endif
Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1871,6 +1871,18 @@
 return {ImportAction::None};
   }
 
+  // Check for circular inclusion of the main file.
+  // We can't generate a consistent preamble with regard to the conditional
+  // stack if the main file is included again as due to the preamble bounds
+  // some directives (e.g. #endif of a header guard) will never be seen.
+  // Since this will lead to confusing errors, avoid the inclusion.
+  if (File && PreambleConditionalStack.isRecording() &&
+  SourceMgr.translateFile(File) == SourceMgr.getMainFileID()) {
+Diag(FilenameTok.getLocation(),
+ diag::err_pp_including_mainfile_for_preamble);
+return {ImportAction::None};
+  }
+
   // Should we enter the source file? Set to Skip if either the source file is
   // known to have no effect beyond its effect on module visibility -- that is,
   // if it's got an include guard that is already defined, set to Import if it
In

[PATCH] D24892: [clang-tidy] Add option "LiteralInitializers" to cppcoreguidelines-pro-type-member-init

2019-05-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM




Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp:361
+  case BuiltinType::Float:
+return " = 0.0F";
+  case BuiltinType::Double:

We may not have to care about this for this version of the patch, but I believe 
we have other checks with options to add literal suffixes in lowercase vs 
uppercase form. We should try to honor that the same way we're honoring using 
assignment vs braces.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D24892/new/

https://reviews.llvm.org/D24892



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


[PATCH] D60456: [RISCV][WIP/RFC] Hard float ABI support

2019-05-09 Thread Alex Bradbury via Phabricator via cfe-commits
asb added inline comments.



Comment at: lib/CodeGen/TargetInfo.cpp:9223
+
+  bool IsInt = Ty->isIntegralOrEnumerationType();
+  bool IsFloat = Ty->isRealFloatingType();

rjmccall wrote:
> Should this include pointers?  Pointers are often interchangeably with 
> integers by ABIs.
> 
> The same question also applies to C++ references and data-member-pointer 
> types, and maybe others that I'm not thinking of.
The ABI doesn't consider pointers and integers interchangeable in this case. An 
"integer" is indeed an integer.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60456/new/

https://reviews.llvm.org/D60456



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


Re: r360073 - [OPENMP]Fix PR41767: diagnose DSA for variables in clauses with

2019-05-09 Thread Roman Lebedev via cfe-commits
... and i had to revert this & the other commit. Sorry :(
This implementation isn't sound as per the standard.
It erroneously diagnoses e.g. the following case:
```
$ cat test.cpp
void f(int n) {
 #pragma omp parallel default(none) if(n)
;
}
```
```
$ ./bin/clang -fopenmp test.cpp
test.cpp:2:40: error: variable 'n' must have explicitly specified data
sharing attributes
 #pragma omp parallel default(none) if(n)
   ^
test.cpp:2:31: note: explicit data sharing attribute requested here
 #pragma omp parallel default(none) if(n)
  ^
1 error generated.
```

As per OpenMP Application Programming Interface Version 5.0 November 2018:
* 2.19.4.1default Clause
  The default clause explicitly determines the data-sharing attributes of
  variables that are referenced *in a parallel, teams, or task generating
  construct and would otherwise be implicitly determined
  (see Section 2.19.1.1 on page 270).
* 2.6.1 Determining the Number of Threads for a parallel Region
  Using a variable in an if or num_threads clause expression of a parallel
  construct causes an implicit reference to the variable in all enclosing
  constructs. The if clause expression and the num_threads clause expression
  are evaluated in the context outside of the parallel construct,

Roman.

On Mon, May 6, 2019 at 11:06 PM Roman Lebedev  wrote:
>
> Thank you!
>
> On Mon, May 6, 2019 at 11:05 PM Alexey Bataev via cfe-commits
>  wrote:
> >
> > Author: abataev
> > Date: Mon May  6 13:07:20 2019
> > New Revision: 360073
> >
> > URL: http://llvm.org/viewvc/llvm-project?rev=360073&view=rev
> > Log:
> > [OPENMP]Fix PR41767: diagnose DSA for variables in clauses with
> > default(none).
> >
> > If the combined directive has default(none) clause and has clauses for
> > inner directive that reference some variables, for which data-sharing
> > attributes are not specified, the error messages should be emitted for
> > such variables.
> >
> > Modified:
> > cfe/trunk/lib/Sema/SemaOpenMP.cpp
> > cfe/trunk/test/OpenMP/distribute_parallel_for_ast_print.cpp
> > cfe/trunk/test/OpenMP/distribute_parallel_for_simd_ast_print.cpp
> > cfe/trunk/test/OpenMP/parallel_for_ast_print.cpp
> > cfe/trunk/test/OpenMP/parallel_for_schedule_messages.cpp
> > cfe/trunk/test/OpenMP/target_parallel_for_ast_print.cpp
> > cfe/trunk/test/OpenMP/target_parallel_for_simd_ast_print.cpp
> > 
> > cfe/trunk/test/OpenMP/target_teams_distribute_parallel_for_if_messages.cpp
> >
> > Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
> > URL: 
> > http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=360073&r1=360072&r2=360073&view=diff
> > ==
> > --- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
> > +++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Mon May  6 13:07:20 2019
> > @@ -750,7 +750,8 @@ bool isImplicitTaskingRegion(OpenMPDirec
> >  }
> >
> >  bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
> > -  return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) 
> > || DKind == OMPD_unknown;
> > +  return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) 
> > ||
> > + DKind == OMPD_unknown;
> >  }
> >
> >  } // namespace
> > @@ -2560,9 +2561,17 @@ public:
> >  E->containsUnexpandedParameterPack() || 
> > E->isInstantiationDependent())
> >return;
> >  if (auto *VD = dyn_cast(E->getDecl())) {
> > +  // Check the datasharing rules for the expressions in the clauses.
> > +  if (!CS) {
> > +if (auto *CED = dyn_cast(VD))
> > +  if (!CED->hasAttr()) {
> > +Visit(CED->getInit());
> > +return;
> > +  }
> > +  }
> >VD = VD->getCanonicalDecl();
> >// Skip internally declared variables.
> > -  if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
> > +  if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
> >  return;
> >
> >DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, 
> > /*FromParent=*/false);
> > @@ -2573,7 +2582,7 @@ public:
> >// Skip internally declared static variables.
> >llvm::Optional Res =
> >OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
> > -  if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
> > +  if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
> >(!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
> >  return;
> >
> > @@ -4186,6 +4195,90 @@ StmtResult Sema::ActOnOpenMPExecutableDi
> >
> >ErrorFound = Res.isInvalid() || ErrorFound;
> >
> > +  // Check variables in the clauses if default(none) was specified.
> > +  if (DSAStack->getDefaultDSA() == DSA_none) {
> > +DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
> > +for (OMPClause *C : Clauses) {
> > +  switch (C->getClauseKind()) {
> > +  case OMPC_num_threads:
> > + 

[PATCH] D56160: [clang-tidy] modernize-use-trailing-return-type check

2019-05-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D56160#1495847 , @bernhardmgruber 
wrote:

> @aaron.ballman and @JonasToth: Thank you for the patience and all the 
> feedback! It means a great deal to me to have a patch accepted here!


You're very welcome! Do you need one of us to commit this on your behalf, or do 
you already have commit privileges?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D56160/new/

https://reviews.llvm.org/D56160



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


[PATCH] D60507: [clang-tidy] new check: bugprone-unhandled-self-assignment

2019-05-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60507/new/

https://reviews.llvm.org/D60507



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


[PATCH] D60274: [ELF] Implement Dependent Libraries Feature

2019-05-09 Thread Rui Ueyama via Phabricator via cfe-commits
ruiu accepted this revision.
ruiu added a comment.
This revision is now accepted and ready to land.

LGTM


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60274/new/

https://reviews.llvm.org/D60274



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


[PATCH] D56160: [clang-tidy] modernize-use-trailing-return-type check

2019-05-09 Thread Bernhard Manfred Gruber via Phabricator via cfe-commits
bernhardmgruber marked 2 inline comments as done.
bernhardmgruber added a comment.

@aaron.ballman I do not have commit privileges and I would be very thankful, if 
you could commit this patch for me! Thank you!




Comment at: clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp:203
+  if (ContainsQualifiers + ContainsSpecifiers + ContainsSomethingElse > 1)
+return {};
+

aaron.ballman wrote:
> bernhardmgruber wrote:
> > aaron.ballman wrote:
> > > This should return `llvm::None`
> > I always wondered what the point of `llvm::None`, `std::nullopt` or 
> > `boost::none` is. When I write `return {};` it looks like i return an empty 
> > shell, exactly how I picture an empty optional in my head. That is why I 
> > prefer it this way. I will change it of course for this patch, but would 
> > you mind giving me a short reason, why `llvm::None` is preferable here?
> AFAIK, there's no functional difference between the two and it's more a 
> matter of consistency. Multiple different types can have the notion of a null 
> state, and this allows you to consistently specify that null state across 
> types in an explicit way.
> 
> I suppose there might also be a very slight argument for clarity in that a 
> user reading the code with `{}` could be confused into thinking that is 
> default constructing the contained type rather than creating an empty 
> optional object.
Thank you for the explanation! I see the point of being more explicit.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D56160/new/

https://reviews.llvm.org/D56160



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


[PATCH] D56160: [clang-tidy] modernize-use-trailing-return-type check

2019-05-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp:203
+  if (ContainsQualifiers + ContainsSpecifiers + ContainsSomethingElse > 1)
+return {};
+

bernhardmgruber wrote:
> aaron.ballman wrote:
> > This should return `llvm::None`
> I always wondered what the point of `llvm::None`, `std::nullopt` or 
> `boost::none` is. When I write `return {};` it looks like i return an empty 
> shell, exactly how I picture an empty optional in my head. That is why I 
> prefer it this way. I will change it of course for this patch, but would you 
> mind giving me a short reason, why `llvm::None` is preferable here?
AFAIK, there's no functional difference between the two and it's more a matter 
of consistency. Multiple different types can have the notion of a null state, 
and this allows you to consistently specify that null state across types in an 
explicit way.

I suppose there might also be a very slight argument for clarity in that a user 
reading the code with `{}` could be confused into thinking that is default 
constructing the contained type rather than creating an empty optional object.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D56160/new/

https://reviews.llvm.org/D56160



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


[PATCH] D53866: [Preamble] Stop circular inclusion of main file when building preamble

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: lib/Basic/SourceManager.cpp:1594
 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
-if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) 
{
+if (MainFile && *SourceFileName == 
llvm::sys::path::filename(MainFile->getName())) {
   SourceFileUID = getActualFileUID(SourceFile);

nik wrote:
> ilya-biryukov wrote:
> > Can this actually be`null`? 
> The comment for OrigEntry states that it might be null:
> 
> /// Reference to the file entry representing this ContentCache.
> ///
> /// This reference does not own the FileEntry object.
> ///
> /// It is possible for this to be NULL if the ContentCache encapsulates
> /// an imaginary text buffer.
> const FileEntry *OrigEntry;
> 
> Note also that further down in this function, a null check for 
> MainContentCache->OrigEntry is done, so I believe that this was just 
> forgotten here (since there is also no assert) and we are the first one 
> running into this with the introduced call to SourceMgr.translateFile(File).
> 
> I've tried to understand why we end up with a nullptr here, but this goes 
> beyond me in the time I've taken for this. What I've observed is that module 
> code path (LibclangReparseTest.ReparseWithModule vs 
> LibclangReparseTest.Reparse) creates at least a MemoryBuffer more (in 
> ModuleMap::parseModuleMapFile; possibly the one referred with "imaginary text 
> buffer" from the comment) and I suspect this to be somehow related with the 
> OrigEntry nullptr.
Should we check for equality of `MainContentCache->ContentsEntry` in that case? 
I guess this is what should be set for "imaginary" files.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D53866/new/

https://reviews.llvm.org/D53866



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


[PATCH] D61497: [clangd] Introduce a structured hover response

2019-05-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

comments on interface again, will take another pass at implementation




Comment at: clang-tools-extra/clangd/XRefs.h:65
+  /// Fully qualiffied name for the scope containing the Sym.
+  std::string Scope;
+  std::string ParentScope;

kadircet wrote:
> sammccall wrote:
> > what's the difference between Scope and ParentScope?
> > Can we give them more obvious names, or a comment?
> > (The current comment doesn't really say anything)
> We've been using Name and Scope to represent two parts of qualified names 
> across the codebase.
> Comment was unfortunately misplaced :/ LMK if you have any other choices for 
> the name
Yes, but here you've got three concepts: name/scope/parentscope (now called 
containedin?). And this covers lots of cases that our existing Name/Scope 
doesn't really (there are lots of symbols we don't index).

It wasn't a rhetorical question, I can't suggest better names because I don't 
know what they are.

My suggestion would be to split into namespace scope/local scope/name, such 
that Name has no `::`, `NamespaceScope` has exactly the (non-inline) enclosing 
namespaces, and   `NamespaceScope + LocalScope + Name == QName`.

So for a local in a class member, `NamespaceScope == "clang::clangd""`, 
`LocalScope == "SymbolCollector::consume::` and `Name = Symbols`. Or just `Name 
= Symbols` and the others are blank, depending on how we choose to display 
locals.



Comment at: clang-tools-extra/clangd/XRefs.h:53
+/// Contains detailed information about a Symbol. Especially useful when
+/// generating hover responses. It is not serialized so that embedding clients
+/// can choose to serialize it w.r.t their UI capabilities.

I'm having trouble following the "serialized" sentence. Maybe "It can be 
rendered as a hover panel, or embedding clients can use the structured 
information to provide their own UI"?



Comment at: clang-tools-extra/clangd/XRefs.h:76
+  /// - None for deduced types, e.g "auto", "decltype" keywords.
+  llvm::Optional ContainedIn;
+  SymbolKind Kind;

This seems overlapping/non-orthogonal with scope. It doesn't let us render a 
member as `ClassName::method` for instance.
If we really need "In function x::Y" rather than "in x::Y", we could add a 
member "ImmediateScopeKind" or something. But I'm not sure we do.



Comment at: clang-tools-extra/clangd/XRefs.h:89
+  llvm::Optional> Parameters;
+  /// Set for all template declarations(function, class, variable).
+  llvm::Optional> TemplateParameters;

nit: just "templates"?

(e.g. if we hover over a call to std::swap, we might be showing the 
instantiation rather than the declaration?)



Comment at: clang-tools-extra/clangd/XRefs.h:93
+  /// Lower to LSP struct.
+  Hover render() const;
+};

Even if this struct ends up containing the range, it might be more obvious to 
have render() produce the `MarkupContent` only, leaving the caller to pull out 
the range themselves.

Converting the range isn't closely related to rendering, and I think for 
cleanest layering/testing you want to return `FormattedString` after rL360151 
(which doesn't have a `Hover` equivalent).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61497/new/

https://reviews.llvm.org/D61497



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


[PATCH] D41005: Reuse preamble even if an unsaved file does not exist

2019-05-09 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik updated this revision to Diff 198809.
nik added a comment.

Addressed inline comments.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D41005/new/

https://reviews.llvm.org/D41005

Files:
  include/clang/Frontend/ASTUnit.h
  lib/Frontend/ASTUnit.cpp
  lib/Frontend/PrecompiledPreamble.cpp
  unittests/Frontend/PCHPreambleTest.cpp

Index: unittests/Frontend/PCHPreambleTest.cpp
===
--- unittests/Frontend/PCHPreambleTest.cpp
+++ unittests/Frontend/PCHPreambleTest.cpp
@@ -52,7 +52,10 @@
   FileSystemOptions FSOpts;
 
 public:
-  void SetUp() override {
+  void SetUp() override { ResetVFS(); }
+  void TearDown() override {}
+
+  void ResetVFS() {
 VFS = new ReadCountingInMemoryFileSystem();
 // We need the working directory to be set to something absolute,
 // otherwise it ends up being inadvertently set to the current
@@ -63,9 +66,6 @@
 VFS->setCurrentWorkingDirectory("//./");
   }
 
-  void TearDown() override {
-  }
-
   void AddFile(const std::string &Filename, const std::string &Contents) {
 ::time_t now;
 ::time(&now);
@@ -123,6 +123,72 @@
   }
 };
 
+TEST_F(PCHPreambleTest, ReparseReusesPreambleWithUnsavedFileNotExistingOnDisk) {
+  std::string Header1 = "//./header1.h";
+  std::string MainName = "//./main.cpp";
+  AddFile(MainName, R"cpp(
+#include "//./header1.h"
+int main() { return ZERO; }
+)cpp");
+  RemapFile(Header1, "#define ZERO 0\n");
+
+  // Parse with header file provided as unsaved file, which does not exist on
+  // disk.
+  std::unique_ptr AST(ParseAST(MainName));
+  ASSERT_TRUE(AST.get());
+  ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  // Reparse and check that the preamble was reused.
+  ASSERT_TRUE(ReparseAST(AST));
+  ASSERT_EQ(AST->getPreambleCounterForTests(), 1U);
+}
+
+TEST_F(PCHPreambleTest, ReparseReusesPreambleAfterUnsavedFileWasCreatedOnDisk) {
+  std::string Header1 = "//./header1.h";
+  std::string MainName = "//./main.cpp";
+  AddFile(MainName, R"cpp(
+#include "//./header1.h"
+int main() { return ZERO; }
+)cpp");
+  RemapFile(Header1, "#define ZERO 0\n");
+
+  // Parse with header file provided as unsaved file, which does not exist on
+  // disk.
+  std::unique_ptr AST(ParseAST(MainName));
+  ASSERT_TRUE(AST.get());
+  ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  // Create the unsaved file also on disk and check that preamble was reused.
+  AddFile(Header1, "#define ZERO 0\n");
+  ASSERT_TRUE(ReparseAST(AST));
+  ASSERT_EQ(AST->getPreambleCounterForTests(), 1U);
+}
+
+TEST_F(PCHPreambleTest,
+   ReparseReusesPreambleAfterUnsavedFileWasRemovedFromDisk) {
+  std::string Header1 = "//./foo/header1.h";
+  std::string MainName = "//./main.cpp";
+  std::string MainFileContent = R"cpp(
+#include "//./foo/header1.h"
+int main() { return ZERO; }
+)cpp";
+  AddFile(MainName, MainFileContent);
+  AddFile(Header1, "#define ZERO 0\n");
+  RemapFile(Header1, "#define ZERO 0\n");
+
+  // Parse with header file provided as unsaved file, which exists on disk.
+  std::unique_ptr AST(ParseAST(MainName));
+  ASSERT_TRUE(AST.get());
+  ASSERT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+  ASSERT_EQ(AST->getPreambleCounterForTests(), 1U);
+
+  // Remove the unsaved file from disk and check that the preamble was reused.
+  ResetVFS();
+  AddFile(MainName, MainFileContent);
+  ASSERT_TRUE(ReparseAST(AST));
+  ASSERT_EQ(AST->getPreambleCounterForTests(), 1U);
+}
+
 TEST_F(PCHPreambleTest, ReparseWithOverriddenFileDoesNotInvalidatePreamble) {
   std::string Header1 = "//./header1.h";
   std::string Header2 = "//./header2.h";
Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -454,20 +454,33 @@
 Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
   }
 
+  // OverridenFileBuffers tracks only the files not found in VFS.
+  llvm::StringMap OverridenFileBuffers;
   for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
-llvm::vfs::Status Status;
-if (!moveOnNoError(VFS->status(RB.first), Status))
-  return false;
-
-OverriddenFiles[Status.getUniqueID()] =
+const PrecompiledPreamble::PreambleFileHash PreambleHash =
 PreambleFileHash::createForMemoryBuffer(RB.second);
+llvm::vfs::Status Status;
+if (moveOnNoError(VFS->status(RB.first), Status))
+  OverriddenFiles[Status.getUniqueID()] = PreambleHash;
+else
+  OverridenFileBuffers[RB.first] = PreambleHash;
   }
 
   // Check whether anything has changed.
   for (const auto &F : FilesInPreamble) {
+auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
+if (OverridenFileBuffer != OverridenFileBuffers.end()) {
+  // The file's buffer was remapped and the file was not found in VFS.
+  // Check whether it matches up with the previous mapping.
+ 

[PATCH] D61729: [docs] Fix example for Allman brace breaking style

2019-05-09 Thread Gerriet Backer via Phabricator via cfe-commits
gerriet created this revision.
gerriet added reviewers: jkorous, llvm-commits.
Herald added subscribers: cfe-commits, dexonsmith.
Herald added a project: clang.

Commit 3fd4a968ad80 
 by 
@jkorous was wrongfully rolled back. Opening braces need to be on separate 
lines for Allman style.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D61729

Files:
  clang/docs/ClangFormatStyleOptions.rst


Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -1059,19 +1059,28 @@
 
 .. code-block:: c++
 
-  try {
+  try 
+  {
 foo();
   }
-  catch () {
+  catch () 
+  {
   }
   void foo() { bar(); }
-  class foo {
+  class foo 
+  {
   };
-  if (foo()) {
+  if (foo()) 
+  {
   }
-  else {
+  else 
+  {
   }
-  enum X : int { A, B };
+  enum X : int 
+  { 
+A, 
+B 
+  };
 
   * ``BS_GNU`` (in configuration: ``GNU``)
 Always break before braces and add an extra level of indentation to


Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -1059,19 +1059,28 @@
 
 .. code-block:: c++
 
-  try {
+  try 
+  {
 foo();
   }
-  catch () {
+  catch () 
+  {
   }
   void foo() { bar(); }
-  class foo {
+  class foo 
+  {
   };
-  if (foo()) {
+  if (foo()) 
+  {
   }
-  else {
+  else 
+  {
   }
-  enum X : int { A, B };
+  enum X : int 
+  { 
+A, 
+B 
+  };
 
   * ``BS_GNU`` (in configuration: ``GNU``)
 Always break before braces and add an extra level of indentation to
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61335: [LibTooling] Add support to Transformer for composing rules as an ordered choice.

2019-05-09 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 198811.
ymandel added a comment.

Folded CompositeRewriteRule into RewriteRule and added examples to comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61335/new/

https://reviews.llvm.org/D61335

Files:
  clang/include/clang/Tooling/Refactoring/Transformer.h
  clang/lib/Tooling/Refactoring/Transformer.cpp
  clang/unittests/Tooling/TransformerTest.cpp

Index: clang/unittests/Tooling/TransformerTest.cpp
===
--- clang/unittests/Tooling/TransformerTest.cpp
+++ clang/unittests/Tooling/TransformerTest.cpp
@@ -116,7 +116,8 @@
 };
   }
 
-  void testRule(RewriteRule Rule, StringRef Input, StringRef Expected) {
+  template 
+  void testRule(R Rule, StringRef Input, StringRef Expected) {
 Transformer T(std::move(Rule), consumer());
 T.registerMatchers(&MatchFinder);
 compareSnippets(Expected, rewrite(Input));
@@ -147,7 +148,7 @@
  .bind(StringExpr)),
   callee(cxxMethodDecl(hasName("c_str")),
   change("REPLACED"));
-  R.Explanation = text("Use size() method directly on string.");
+  R.Cases[0].Explanation = text("Use size() method directly on string.");
   return R;
 }
 
@@ -375,6 +376,92 @@
Input, Expected);
 }
 
+TEST_F(TransformerTest, OrderedRuleUnrelated) {
+  StringRef Flag = "flag";
+  RewriteRule FlagRule = makeRule(
+  cxxMemberCallExpr(on(expr(hasType(cxxRecordDecl(
+hasName("proto::ProtoCommandLineFlag"
+   .bind(Flag)),
+unless(callee(cxxMethodDecl(hasName("GetProto"),
+  change(Flag, "PROTO"));
+
+  std::string Input = R"cc(
+proto::ProtoCommandLineFlag flag;
+int x = flag.foo();
+int y = flag.GetProto().foo();
+int f(string s) { return strlen(s.c_str()); }
+  )cc";
+  std::string Expected = R"cc(
+proto::ProtoCommandLineFlag flag;
+int x = PROTO.foo();
+int y = flag.GetProto().foo();
+int f(string s) { return REPLACED; }
+  )cc";
+
+  testRule(makeOrderedRule({ruleStrlenSize(), FlagRule}), Input, Expected);
+}
+
+// Version of ruleStrlenSizeAny that inserts a method with a different name than
+// ruleStrlenSize, so we can tell their effect apart.
+RewriteRule ruleStrlenSizeDistinct() {
+  StringRef S;
+  return makeRule(
+  callExpr(callee(functionDecl(hasName("strlen"))),
+   hasArgument(0, cxxMemberCallExpr(
+  on(expr().bind(S)),
+  callee(cxxMethodDecl(hasName("c_str")),
+  change("DISTINCT"));
+}
+
+TEST_F(TransformerTest, OrderedRuleRelated) {
+  std::string Input = R"cc(
+namespace foo {
+struct mystring {
+  char* c_str();
+};
+int f(mystring s) { return strlen(s.c_str()); }
+}  // namespace foo
+int g(string s) { return strlen(s.c_str()); }
+  )cc";
+  std::string Expected = R"cc(
+namespace foo {
+struct mystring {
+  char* c_str();
+};
+int f(mystring s) { return DISTINCT; }
+}  // namespace foo
+int g(string s) { return REPLACED; }
+  )cc";
+
+  testRule(makeOrderedRule({ruleStrlenSize(), ruleStrlenSizeDistinct()}), Input,
+   Expected);
+}
+
+// Change the order of the rules to get a different result.
+TEST_F(TransformerTest, OrderedRuleRelatedSwapped) {
+  std::string Input = R"cc(
+namespace foo {
+struct mystring {
+  char* c_str();
+};
+int f(mystring s) { return strlen(s.c_str()); }
+}  // namespace foo
+int g(string s) { return strlen(s.c_str()); }
+  )cc";
+  std::string Expected = R"cc(
+namespace foo {
+struct mystring {
+  char* c_str();
+};
+int f(mystring s) { return DISTINCT; }
+}  // namespace foo
+int g(string s) { return DISTINCT; }
+  )cc";
+
+  testRule(makeOrderedRule({ruleStrlenSizeDistinct(), ruleStrlenSize()}), Input,
+   Expected);
+}
+
 //
 // Negative tests (where we expect no transformation to occur).
 //
Index: clang/lib/Tooling/Refactoring/Transformer.cpp
===
--- clang/lib/Tooling/Refactoring/Transformer.cpp
+++ clang/lib/Tooling/Refactoring/Transformer.cpp
@@ -28,6 +28,7 @@
 using namespace tooling;
 
 using ast_matchers::MatchFinder;
+using ast_matchers::internal::DynTypedMatcher;
 using ast_type_traits::ASTNodeKind;
 using ast_type_traits::DynTypedNode;
 using llvm::Error;
@@ -171,18 +172,112 @@
   return Transformations;
 }
 
-RewriteRule tooling::makeRule(ast_matchers::internal::DynTypedMatcher M,
+RewriteRule tooling::makeRule(DynTypedMatcher M,
   SmallVector Edits) {
+  return RewriteRule{
+  {RewriteRule::Case{std::move(M), std::move(Edits), nullptr}}};
+}
+
+// Determines whether A is higher than B in the class hierarchy.
+static bool isHigher(ASTNodeK

r360342 - [OpenCL] Make global ctor init function a kernel

2019-05-09 Thread Anastasia Stulova via cfe-commits
Author: stulova
Date: Thu May  9 06:55:44 2019
New Revision: 360342

URL: http://llvm.org/viewvc/llvm-project?rev=360342&view=rev
Log:
[OpenCL] Make global ctor init function a kernel

We need to be able to enqueue internal function that initializes
global constructors on the host side. Therefore it has to be
converted to a kernel.

This change factors out common logic for adding kernel metadata
and moves it from CodeGenFunction to CodeGenModule in order to
make it accessible for the extra use case.

Differential revision: https://reviews.llvm.org/D61488


Added:
cfe/trunk/test/CodeGenOpenCLCXX/global_init.cl
Modified:
cfe/trunk/lib/CodeGen/CGDeclCXX.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
cfe/trunk/lib/CodeGen/CodeGenModule.cpp
cfe/trunk/lib/CodeGen/CodeGenModule.h

Modified: cfe/trunk/lib/CodeGen/CGDeclCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDeclCXX.cpp?rev=360342&r1=360341&r2=360342&view=diff
==
--- cfe/trunk/lib/CodeGen/CGDeclCXX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDeclCXX.cpp Thu May  9 06:55:44 2019
@@ -580,6 +580,19 @@ CodeGenModule::EmitCXXGlobalInitFunc() {
   CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
   AddGlobalCtor(Fn);
 
+  // In OpenCL global init functions must be converted to kernels in order to
+  // be able to launch them from the host.
+  // FIXME: Some more work might be needed to handle destructors correctly.
+  // Current initialization function makes use of function pointers callbacks.
+  // We can't support function pointers especially between host and device.
+  // However it seems global destruction has little meaning without any
+  // dynamic resource allocation on the device and program scope variables are
+  // destroyed by the runtime when program is released.
+  if (getLangOpts().OpenCL) {
+GenOpenCLArgMetadata(Fn);
+Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
+  }
+
   CXXGlobalInits.clear();
 }
 

Modified: cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenFunction.cpp?rev=360342&r1=360341&r2=360342&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenFunction.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenFunction.cpp Thu May  9 06:55:44 2019
@@ -536,205 +536,6 @@ CodeGenFunction::DecodeAddrUsedInPrologu
 "decoded_addr");
 }
 
-static void removeImageAccessQualifier(std::string& TyName) {
-  std::string ReadOnlyQual("__read_only");
-  std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
-  if (ReadOnlyPos != std::string::npos)
-// "+ 1" for the space after access qualifier.
-TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
-  else {
-std::string WriteOnlyQual("__write_only");
-std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
-if (WriteOnlyPos != std::string::npos)
-  TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
-else {
-  std::string ReadWriteQual("__read_write");
-  std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
-  if (ReadWritePos != std::string::npos)
-TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
-}
-  }
-}
-
-// Returns the address space id that should be produced to the
-// kernel_arg_addr_space metadata. This is always fixed to the ids
-// as specified in the SPIR 2.0 specification in order to differentiate
-// for example in clGetKernelArgInfo() implementation between the address
-// spaces with targets without unique mapping to the OpenCL address spaces
-// (basically all single AS CPUs).
-static unsigned ArgInfoAddressSpace(LangAS AS) {
-  switch (AS) {
-  case LangAS::opencl_global:   return 1;
-  case LangAS::opencl_constant: return 2;
-  case LangAS::opencl_local:return 3;
-  case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
-  default:
-return 0; // Assume private.
-  }
-}
-
-// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
-// information in the program executable. The argument information stored
-// includes the argument name, its type, the address and access qualifiers 
used.
-static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
- CodeGenModule &CGM, llvm::LLVMContext 
&Context,
- CGBuilderTy &Builder, ASTContext &ASTCtx) {
-  // Create MDNodes that represent the kernel arg metadata.
-  // Each MDNode is a list in the form of "key", N number of values which is
-  // the same number of values as their are kernel arguments.
-
-  const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
-
-  // MDNode for the kernel argument address space qualifiers.
-  SmallVector addressQuals;
-
-  // MDNode for the kernel argument access qualifiers (images only).
-  SmallVector access

[PATCH] D61488: [OpenCL] Make global ctor init function a kernel

2019-05-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL360342: [OpenCL] Make global ctor init function a kernel 
(authored by stulova, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D61488?vs=198678&id=198814#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61488/new/

https://reviews.llvm.org/D61488

Files:
  cfe/trunk/lib/CodeGen/CGDeclCXX.cpp
  cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
  cfe/trunk/lib/CodeGen/CodeGenModule.cpp
  cfe/trunk/lib/CodeGen/CodeGenModule.h
  cfe/trunk/test/CodeGenOpenCLCXX/global_init.cl

Index: cfe/trunk/test/CodeGenOpenCLCXX/global_init.cl
===
--- cfe/trunk/test/CodeGenOpenCLCXX/global_init.cl
+++ cfe/trunk/test/CodeGenOpenCLCXX/global_init.cl
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 %s -triple spir -cl-std=c++ -emit-llvm -O0 -o - | FileCheck %s
+
+struct S {
+  S() {}
+};
+
+S s;
+
+//CHECK: define internal spir_kernel void @_GLOBAL__sub_I_{{.*}}!kernel_arg_addr_space [[ARGMD:![0-9]+]] !kernel_arg_access_qual [[ARGMD]] !kernel_arg_type [[ARGMD]] !kernel_arg_base_type [[ARGMD]] !kernel_arg_type_qual [[ARGMD]]
+// Check that parameters are empty.
+//CHECK: [[ARGMD]] = !{}
Index: cfe/trunk/lib/CodeGen/CodeGenModule.h
===
--- cfe/trunk/lib/CodeGen/CodeGenModule.h
+++ cfe/trunk/lib/CodeGen/CodeGenModule.h
@@ -1315,6 +1315,19 @@
   llvm::Value *
   createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF);
 
+  /// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
+  /// information in the program executable. The argument information stored
+  /// includes the argument name, its type, the address and access qualifiers
+  /// used. This helper can be used to generate metadata for source code kernel
+  /// function as well as generated implicitly kernels. If a kernel is generated
+  /// implicitly null value has to be passed to the last two parameters,
+  /// otherwise all parameters must have valid non-null values.
+  /// \param FN is a pointer to IR function being generated.
+  /// \param FD is a pointer to function declaration if any.
+  /// \param CGF is a pointer to CodeGenFunction that generates this function.
+  void GenOpenCLArgMetadata(llvm::Function *Fn, const FunctionDecl *FD=nullptr,  
+ CodeGenFunction *CGF=nullptr);
+
   /// Get target specific null pointer.
   /// \param T is the LLVM type of the null pointer.
   /// \param QT is the clang QualType of the null pointer.
Index: cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
===
--- cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
+++ cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
@@ -536,205 +536,6 @@
 "decoded_addr");
 }
 
-static void removeImageAccessQualifier(std::string& TyName) {
-  std::string ReadOnlyQual("__read_only");
-  std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
-  if (ReadOnlyPos != std::string::npos)
-// "+ 1" for the space after access qualifier.
-TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
-  else {
-std::string WriteOnlyQual("__write_only");
-std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
-if (WriteOnlyPos != std::string::npos)
-  TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
-else {
-  std::string ReadWriteQual("__read_write");
-  std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
-  if (ReadWritePos != std::string::npos)
-TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
-}
-  }
-}
-
-// Returns the address space id that should be produced to the
-// kernel_arg_addr_space metadata. This is always fixed to the ids
-// as specified in the SPIR 2.0 specification in order to differentiate
-// for example in clGetKernelArgInfo() implementation between the address
-// spaces with targets without unique mapping to the OpenCL address spaces
-// (basically all single AS CPUs).
-static unsigned ArgInfoAddressSpace(LangAS AS) {
-  switch (AS) {
-  case LangAS::opencl_global:   return 1;
-  case LangAS::opencl_constant: return 2;
-  case LangAS::opencl_local:return 3;
-  case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
-  default:
-return 0; // Assume private.
-  }
-}
-
-// OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
-// information in the program executable. The argument information stored
-// includes the argument name, its type, the address and access qualifiers used.
-static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
- CodeGenModule &CGM, llvm::LLVMContext &Context,
- CGBuilderTy &Builder, ASTContext &ASTCtx) {
-  // Create MDNodes

[PATCH] D60934: [clang] adding explicit(bool) from c++2a

2019-05-09 Thread Tyker via Phabricator via cfe-commits
Tyker marked an inline comment as done.
Tyker added inline comments.



Comment at: cfe/trunk/lib/Parse/ParseDecl.cpp:3939
+ "both or neither of isAlreadyConsumed and 
"
+ "RangeEnd needs to be set");
+DS.SetRangeEnd(isAlreadyConsumed ? RangeEnd : Tok.getLocation());

RKSimon wrote:
> @Tyker @rsmith We're seeing -Wparentheses warnings because of this - please 
> can you take a look? The logic looks a little dodgy for a both/neither 
> assertion as well.
> 
> http://lab.llvm.org:8011/builders/clang-ppc64be-linux-lnt/builds/27322/steps/build%20stage%201/logs/warnings%20%281%29
i made a revision that fixes this: https://reviews.llvm.org/D61731


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60934/new/

https://reviews.llvm.org/D60934



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


[PATCH] D61335: [LibTooling] Add support to Transformer for composing rules as an ordered choice.

2019-05-09 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

In D61335#1495324 , @ilya-biryukov 
wrote:

> Sorry for the delay.
>  I personally like the `RewriteRule::Action` best. Allows to use a rather 
> common term, while still avoiding any possible confusion.


I tried going with `RewriteRule::Action` (it was my preference as well), but 
found that it didn't work well once I tried folding the composite rules into 
RewriteRule.  The problem is that the Action structure forces you to eagerly 
join the matchers (which is what my first diff did). But then it doesn't work 
to join multiple rules that themselves were built with makeOrderedRule. 
Previously, this was impossible because they had different types, but now a 
user could conceivably do this.  So, I changed the implementation build the 
joined matcher later.  RewriteRule now just stores all of the (sub)rules in a 
single list, and `makeOrderedRule` is a trivial merge.  The real work is done 
at `registerMatchers()`-time where we build the joined matcher for the whole 
rule. But, this means keeping the whole (sub)rule around, not just the Action 
part.

Alternatives I considered:

1. We could use the Action structure inside Transformer -- instead of storing a 
RewriteRule, we could simply store a single matcher and vector of Action. In 
the constructor, we would call `buildMatcher(Rule)` and then copy only the 
action parts from the rules.  However, I don't think this added complexity will 
gain us anything other than a structure which more faithfully reflects the 
control flow -- the matchers in each case are "dead" once we build the joined 
matcher, and the Action approach would reflect that.

2. We could add more structure to Case, like:

  struct RewriteRule {
struct Action {
  SmallVector Edits;
  TextGenerator Explanation;
};
struct Case {
  ast_matchers::internal::DynTypedMatcher Matcher;
  Action A;
};
std::vector Cases;
  };


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61335/new/

https://reviews.llvm.org/D61335



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


[PATCH] D53866: [Preamble] Stop circular inclusion of main file when building preamble

2019-05-09 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik marked an inline comment as done.
nik added inline comments.



Comment at: lib/Basic/SourceManager.cpp:1594
 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
-if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) 
{
+if (MainFile && *SourceFileName == 
llvm::sys::path::filename(MainFile->getName())) {
   SourceFileUID = getActualFileUID(SourceFile);

ilya-biryukov wrote:
> nik wrote:
> > ilya-biryukov wrote:
> > > Can this actually be`null`? 
> > The comment for OrigEntry states that it might be null:
> > 
> > /// Reference to the file entry representing this ContentCache.
> > ///
> > /// This reference does not own the FileEntry object.
> > ///
> > /// It is possible for this to be NULL if the ContentCache encapsulates
> > /// an imaginary text buffer.
> > const FileEntry *OrigEntry;
> > 
> > Note also that further down in this function, a null check for 
> > MainContentCache->OrigEntry is done, so I believe that this was just 
> > forgotten here (since there is also no assert) and we are the first one 
> > running into this with the introduced call to SourceMgr.translateFile(File).
> > 
> > I've tried to understand why we end up with a nullptr here, but this goes 
> > beyond me in the time I've taken for this. What I've observed is that 
> > module code path (LibclangReparseTest.ReparseWithModule vs 
> > LibclangReparseTest.Reparse) creates at least a MemoryBuffer more (in 
> > ModuleMap::parseModuleMapFile; possibly the one referred with "imaginary 
> > text buffer" from the comment) and I suspect this to be somehow related 
> > with the OrigEntry nullptr.
> Should we check for equality of `MainContentCache->ContentsEntry` in that 
> case? I guess this is what should be set for "imaginary" files.
Does not help in this particular case as ContentsEntry is also a nullptr. All 
the members of the ContentsCache seem to be either nullptr or 0 as that 
particular point of execution.

How to continue?

a) Accept as is.
b) Ask someone knowledgeable for whom this could be a no-brainer that could 
respond hopefully soon. Any candidate?
c) Or should I dig deeper? This can take quite some time as this area is new 
for me.



Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D53866/new/

https://reviews.llvm.org/D53866



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


[clang-tools-extra] r360344 - [clangd] Count number of references while merging RefSlabs inside FileIndex

2019-05-09 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Thu May  9 07:22:07 2019
New Revision: 360344

URL: http://llvm.org/viewvc/llvm-project?rev=360344&view=rev
Log:
[clangd] Count number of references while merging RefSlabs inside FileIndex

Summary:
For counting number of references clangd was relying on merging every
duplication of a symbol. Unfortunately this does not apply to FileIndex(and one
of its users' BackgroundIndex), since we get rid of duplication by simply
dropping symbols coming from non-canonical locations. So only one or two(coming
from canonical declaration header and defined source file, if exists)
replications of the same symbol reaches merging step.

This patch changes reference counting logic to rather count number of different
RefSlabs a given SymbolID exists.

Reviewers: ilya-biryukov

Subscribers: ioeric, MaskRay, jkorous, mgrang, arphaman, jdoerfert, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/index/Background.cpp
clang-tools-extra/trunk/clangd/index/FileIndex.cpp
clang-tools-extra/trunk/clangd/index/FileIndex.h
clang-tools-extra/trunk/clangd/index/IndexAction.cpp
clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp
clang-tools-extra/trunk/clangd/unittests/BackgroundIndexTests.cpp
clang-tools-extra/trunk/clangd/unittests/FileIndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/Background.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Background.cpp?rev=360344&r1=360343&r2=360344&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Background.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Background.cpp Thu May  9 07:22:07 2019
@@ -356,7 +356,8 @@ void BackgroundIndex::update(llvm::Strin
   // This can override a newer version that is added in another thread, if
   // this thread sees the older version but finishes later. This should be
   // rare in practice.
-  IndexedSymbols.update(Path, std::move(SS), std::move(RS));
+  IndexedSymbols.update(Path, std::move(SS), std::move(RS),
+Path == MainFile);
 }
   }
 }
@@ -478,7 +479,8 @@ BackgroundIndex::loadShard(const tooling
   struct ShardInfo {
 std::string AbsolutePath;
 std::unique_ptr Shard;
-FileDigest Digest;
+FileDigest Digest = {};
+bool CountReferences = false;
   };
   std::vector IntermediateSymbols;
   // Make sure we don't have duplicate elements in the queue. Keys are absolute
@@ -539,6 +541,7 @@ BackgroundIndex::loadShard(const tooling
   SI.AbsolutePath = CurDependency.Path;
   SI.Shard = std::move(Shard);
   SI.Digest = I.getValue().Digest;
+  SI.CountReferences = I.getValue().IsTU;
   IntermediateSymbols.push_back(std::move(SI));
   // Check if the source needs re-indexing.
   // Get the digest, skip it if file doesn't exist.
@@ -568,7 +571,8 @@ BackgroundIndex::loadShard(const tooling
 ? llvm::make_unique(std::move(*SI.Shard->Refs))
 : nullptr;
   IndexedFileDigests[SI.AbsolutePath] = SI.Digest;
-  IndexedSymbols.update(SI.AbsolutePath, std::move(SS), std::move(RS));
+  IndexedSymbols.update(SI.AbsolutePath, std::move(SS), std::move(RS),
+SI.CountReferences);
 }
   }
 

Modified: clang-tools-extra/trunk/clangd/index/FileIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/FileIndex.cpp?rev=360344&r1=360343&r2=360344&view=diff
==
--- clang-tools-extra/trunk/clangd/index/FileIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/FileIndex.cpp Thu May  9 07:22:07 2019
@@ -90,28 +90,36 @@ SymbolSlab indexHeaderSymbols(ASTContext
 }
 
 void FileSymbols::update(PathRef Path, std::unique_ptr Symbols,
- std::unique_ptr Refs) {
+ std::unique_ptr Refs, bool CountReferences) {
   std::lock_guard Lock(Mutex);
   if (!Symbols)
 FileToSymbols.erase(Path);
   else
 FileToSymbols[Path] = std::move(Symbols);
-  if (!Refs)
+  if (!Refs) {
 FileToRefs.erase(Path);
-  else
-FileToRefs[Path] = std::move(Refs);
+return;
+  }
+  RefSlabAndCountReferences Item;
+  Item.CountReferences = CountReferences;
+  Item.Slab = std::move(Refs);
+  FileToRefs[Path] = std::move(Item);
 }
 
 std::unique_ptr
 FileSymbols::buildIndex(IndexType Type, DuplicateHandling DuplicateHandle) {
   std::vector> SymbolSlabs;
   std::vector> RefSlabs;
+  std::vector MainFileRefs;
   {
 std::lock_guard Lock(Mutex);
 for (const auto &FileAndSymbols : FileToSymbols)
   SymbolSlabs.push_back(FileAndSymbols.second);
-for (const auto &FileAndRefs : FileToRefs)
-  RefSlabs.push_back(FileAndRefs.second);
+for (const auto &FileAndRefs : FileToRefs) {
+  RefSlabs.push_back(Fi

[PATCH] D59481: [clangd] Count number of references while merging RefSlabs inside FileIndex

2019-05-09 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 198816.
kadircet marked 2 inline comments as done.
kadircet added a comment.

- Address comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59481/new/

https://reviews.llvm.org/D59481

Files:
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/FileIndex.h
  clang-tools-extra/clangd/index/IndexAction.cpp
  clang-tools-extra/clangd/indexer/IndexerMain.cpp
  clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
  clang-tools-extra/clangd/unittests/FileIndexTests.cpp

Index: clang-tools-extra/clangd/unittests/FileIndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/FileIndexTests.cpp
+++ clang-tools-extra/clangd/unittests/FileIndexTests.cpp
@@ -45,6 +45,7 @@
   return llvm::StringRef(arg.Definition.FileURI) == U;
 }
 MATCHER_P(QName, N, "") { return (arg.Scope + arg.Name).str() == N; }
+MATCHER_P(NumReferences, N, "") { return arg.References == N; }
 
 namespace clang {
 namespace clangd {
@@ -81,7 +82,7 @@
   FileSymbols FS;
   EXPECT_THAT(runFuzzyFind(*FS.buildIndex(IndexType::Light), ""), IsEmpty());
 
-  FS.update("f1", numSlab(1, 3), refSlab(SymbolID("1"), "f1.cc"));
+  FS.update("f1", numSlab(1, 3), refSlab(SymbolID("1"), "f1.cc"), false);
   EXPECT_THAT(runFuzzyFind(*FS.buildIndex(IndexType::Light), ""),
   UnorderedElementsAre(QName("1"), QName("2"), QName("3")));
   EXPECT_THAT(getRefs(*FS.buildIndex(IndexType::Light), SymbolID("1")),
@@ -90,8 +91,8 @@
 
 TEST(FileSymbolsTest, Overlap) {
   FileSymbols FS;
-  FS.update("f1", numSlab(1, 3), nullptr);
-  FS.update("f2", numSlab(3, 5), nullptr);
+  FS.update("f1", numSlab(1, 3), nullptr, false);
+  FS.update("f2", numSlab(3, 5), nullptr, false);
   for (auto Type : {IndexType::Light, IndexType::Heavy})
 EXPECT_THAT(runFuzzyFind(*FS.buildIndex(Type), ""),
 UnorderedElementsAre(QName("1"), QName("2"), QName("3"),
@@ -110,8 +111,8 @@
   auto X2 = symbol("x");
   X2.Definition.FileURI = "file:///x2";
 
-  FS.update("f1", OneSymboSlab(X1), nullptr);
-  FS.update("f2", OneSymboSlab(X2), nullptr);
+  FS.update("f1", OneSymboSlab(X1), nullptr, false);
+  FS.update("f2", OneSymboSlab(X2), nullptr, false);
   for (auto Type : {IndexType::Light, IndexType::Heavy})
 EXPECT_THAT(
 runFuzzyFind(*FS.buildIndex(Type, DuplicateHandling::Merge), "x"),
@@ -123,14 +124,14 @@
   FileSymbols FS;
 
   SymbolID ID("1");
-  FS.update("f1", numSlab(1, 3), refSlab(ID, "f1.cc"));
+  FS.update("f1", numSlab(1, 3), refSlab(ID, "f1.cc"), false);
 
   auto Symbols = FS.buildIndex(IndexType::Light);
   EXPECT_THAT(runFuzzyFind(*Symbols, ""),
   UnorderedElementsAre(QName("1"), QName("2"), QName("3")));
   EXPECT_THAT(getRefs(*Symbols, ID), RefsAre({FileURI("f1.cc")}));
 
-  FS.update("f1", nullptr, nullptr);
+  FS.update("f1", nullptr, nullptr, false);
   auto Empty = FS.buildIndex(IndexType::Light);
   EXPECT_THAT(runFuzzyFind(*Empty, ""), IsEmpty());
   EXPECT_THAT(getRefs(*Empty, ID), ElementsAre());
@@ -366,6 +367,33 @@
   RefsAre({RefRange(Main.range())}));
 }
 
+TEST(FileSymbolsTest, CountReferencesNoRefSlabs) {
+  FileSymbols FS;
+  FS.update("f1", numSlab(1, 3), nullptr, true);
+  FS.update("f2", numSlab(1, 3), nullptr, false);
+  EXPECT_THAT(
+  runFuzzyFind(*FS.buildIndex(IndexType::Light, DuplicateHandling::Merge),
+   ""),
+  UnorderedElementsAre(AllOf(QName("1"), NumReferences(0u)),
+   AllOf(QName("2"), NumReferences(0u)),
+   AllOf(QName("3"), NumReferences(0u;
+}
+
+TEST(FileSymbolsTest, CountReferencesWithRefSlabs) {
+  FileSymbols FS;
+  FS.update("f1cpp", numSlab(1, 3), refSlab(SymbolID("1"), "f1.cpp"), true);
+  FS.update("f1h", numSlab(1, 3), refSlab(SymbolID("1"), "f1.h"), false);
+  FS.update("f2cpp", numSlab(1, 3), refSlab(SymbolID("2"), "f2.cpp"), true);
+  FS.update("f2h", numSlab(1, 3), refSlab(SymbolID("2"), "f2.h"), false);
+  FS.update("f3cpp", numSlab(1, 3), refSlab(SymbolID("3"), "f3.cpp"), true);
+  FS.update("f3h", numSlab(1, 3), refSlab(SymbolID("3"), "f3.h"), false);
+  EXPECT_THAT(
+  runFuzzyFind(*FS.buildIndex(IndexType::Light, DuplicateHandling::Merge),
+   ""),
+  UnorderedElementsAre(AllOf(QName("1"), NumReferences(1u)),
+   AllOf(QName("2"), NumReferences(1u)),
+   AllOf(QName("3"), NumReferences(1u;
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
+++ clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
@@ -32,6 +32,7 @@
   return !arg.IsTU && !arg.URI.empty() && arg.Digest

[PATCH] D59481: [clangd] Count number of references while merging RefSlabs inside FileIndex

2019-05-09 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE360344: [clangd] Count number of references while merging 
RefSlabs inside FileIndex (authored by kadircet, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59481?vs=198816&id=198818#toc

Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59481/new/

https://reviews.llvm.org/D59481

Files:
  clangd/index/Background.cpp
  clangd/index/FileIndex.cpp
  clangd/index/FileIndex.h
  clangd/index/IndexAction.cpp
  clangd/indexer/IndexerMain.cpp
  clangd/unittests/BackgroundIndexTests.cpp
  clangd/unittests/FileIndexTests.cpp

Index: clangd/unittests/BackgroundIndexTests.cpp
===
--- clangd/unittests/BackgroundIndexTests.cpp
+++ clangd/unittests/BackgroundIndexTests.cpp
@@ -32,6 +32,7 @@
   return !arg.IsTU && !arg.URI.empty() && arg.Digest == FileDigest{{0}} &&
  arg.DirectIncludes.empty();
 }
+MATCHER_P(NumReferences, N, "") { return arg.References == N; }
 
 class MemoryShardStorage : public BackgroundIndexStorage {
   mutable std::mutex StorageMu;
@@ -112,6 +113,9 @@
   #include "A.h"
   void f_b() {
 (void)common;
+(void)common;
+(void)common;
+(void)common;
   })cpp";
   llvm::StringMap Storage;
   size_t CacheHits = 0;
@@ -127,20 +131,25 @@
   CDB.setCompileCommand(testPath("root/A.cc"), Cmd);
 
   ASSERT_TRUE(Idx.blockUntilIdleForTest());
-  EXPECT_THAT(
-  runFuzzyFind(Idx, ""),
-  UnorderedElementsAre(Named("common"), Named("A_CC"), Named("g"),
-   AllOf(Named("f_b"), Declared(), Not(Defined();
+  EXPECT_THAT(runFuzzyFind(Idx, ""),
+  UnorderedElementsAre(AllOf(Named("common"), NumReferences(1U)),
+   AllOf(Named("A_CC"), NumReferences(0U)),
+   AllOf(Named("g"), NumReferences(0U)),
+   AllOf(Named("f_b"), Declared(),
+ Not(Defined()), NumReferences(0U;
 
   Cmd.Filename = testPath("root/B.cc");
   Cmd.CommandLine = {"clang++", Cmd.Filename};
-  CDB.setCompileCommand(testPath("root/A.cc"), Cmd);
+  CDB.setCompileCommand(testPath("root/B.cc"), Cmd);
 
   ASSERT_TRUE(Idx.blockUntilIdleForTest());
   // B_CC is dropped as we don't collect symbols from A.h in this compilation.
   EXPECT_THAT(runFuzzyFind(Idx, ""),
-  UnorderedElementsAre(Named("common"), Named("A_CC"), Named("g"),
-   AllOf(Named("f_b"), Declared(), Defined(;
+  UnorderedElementsAre(AllOf(Named("common"), NumReferences(5U)),
+   AllOf(Named("A_CC"), NumReferences(0U)),
+   AllOf(Named("g"), NumReferences(0U)),
+   AllOf(Named("f_b"), Declared(), Defined(),
+ NumReferences(1U;
 
   auto Syms = runFuzzyFind(Idx, "common");
   EXPECT_THAT(Syms, UnorderedElementsAre(Named("common")));
@@ -148,6 +157,9 @@
   EXPECT_THAT(getRefs(Idx, Common.ID),
   RefsAre({FileURI("unittest:///root/A.h"),
FileURI("unittest:///root/A.cc"),
+   FileURI("unittest:///root/B.cc"),
+   FileURI("unittest:///root/B.cc"),
+   FileURI("unittest:///root/B.cc"),
FileURI("unittest:///root/B.cc")}));
 }
 
Index: clangd/unittests/FileIndexTests.cpp
===
--- clangd/unittests/FileIndexTests.cpp
+++ clangd/unittests/FileIndexTests.cpp
@@ -45,6 +45,7 @@
   return llvm::StringRef(arg.Definition.FileURI) == U;
 }
 MATCHER_P(QName, N, "") { return (arg.Scope + arg.Name).str() == N; }
+MATCHER_P(NumReferences, N, "") { return arg.References == N; }
 
 namespace clang {
 namespace clangd {
@@ -81,7 +82,7 @@
   FileSymbols FS;
   EXPECT_THAT(runFuzzyFind(*FS.buildIndex(IndexType::Light), ""), IsEmpty());
 
-  FS.update("f1", numSlab(1, 3), refSlab(SymbolID("1"), "f1.cc"));
+  FS.update("f1", numSlab(1, 3), refSlab(SymbolID("1"), "f1.cc"), false);
   EXPECT_THAT(runFuzzyFind(*FS.buildIndex(IndexType::Light), ""),
   UnorderedElementsAre(QName("1"), QName("2"), QName("3")));
   EXPECT_THAT(getRefs(*FS.buildIndex(IndexType::Light), SymbolID("1")),
@@ -90,8 +91,8 @@
 
 TEST(FileSymbolsTest, Overlap) {
   FileSymbols FS;
-  FS.update("f1", numSlab(1, 3), nullptr);
-  FS.update("f2", numSlab(3, 5), nullptr);
+  FS.update("f1", numSlab(1, 3), nullptr, false);
+  FS.update("f2", numSlab(3, 5), nullptr, false);
   for (auto Type : {IndexType::Light, IndexType::Heavy})
 EXPECT_THAT(runFuzzyFind(*FS.buildIndex(Type), ""),
 UnorderedElementsAre(QName("1"), QName("2"), QName("3"),
@@ -110,8 +111,8 @@
   auto X2 = symbol("x");
   X2.Definition.

[PATCH] D61522: Added an assertion to constant evaluation enty points that prohibits dependent expressions

2019-05-09 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr marked an inline comment as done.
gribozavr added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:6369
 // very difficult. Ideally, we should handle them more gracefully.
-if (!EIA->getCond()->EvaluateWithSubstitution(
+if (EIA->getCond()->isValueDependent() ||
+!EIA->getCond()->EvaluateWithSubstitution(

rsmith wrote:
> This is treating value-dependent `enable_if` conditions as having failed. Is 
> that really appropriate? (When do we call this with value-depnedent 
> `enable_if` attributes? I'd expect it to only be called after substitution)
This test case in `llvm-project/clang/test/SemaCXX/enable_if.cpp` passes a 
dependent condition:

```
void h(int);
template  void outer() {
  void local_function() __attribute__((enable_if(::h(T()), "")));
  local_function();
};
```

According to https://reviews.llvm.org/D20130, it seems like it was decided to 
document implementation details as specification, and say that `enable_if` is 
evaluated during overload resolution, whenever that happens to happen.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61522/new/

https://reviews.llvm.org/D61522



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


[PATCH] D61438: [ASTImporter] Use llvm::Expected and Error in the importer API

2019-05-09 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 8 inline comments as done.
martong added inline comments.



Comment at: clang/lib/AST/ASTImporter.cpp:5039
+  if (!ToOrErr)
+// FIXME: return the error?
+consumeError(ToOrErr.takeError());

aprantl wrote:
> We don't typically commit FIXME's into LLVM code. Why not just deal with the 
> error properly from the start?
Ok, changed that to return with the error.



Comment at: lldb/source/Symbol/ClangASTImporter.cpp:68
+  return *ret_or_error;
+} else {
+  Log *log =

sgraenitz wrote:
> aprantl wrote:
> > The `else` is redundant.
> Here it's necessary for the scope of `ret_or_error`. That's a bit 
> unfortunate. Maybe invert the condition?
Ok, I have inverted the condition and this way the else  became redundant, so I 
removed it.



Comment at: lldb/source/Symbol/ClangASTImporter.cpp:139
+
+  llvm::consumeError(result.takeError());
+

aprantl wrote:
> Can you convert this to an early return instead?
Okay, I have added
```
  if (!delegate_sp)
return nullptr;
```
But we can't get rid of `consumeError` because otherwise the error object 
remains unchecked and will cause run-time assert.
`LLDB_LOG_ERROR` calls `consumeError` too plus logs the error msg, so I changed 
to use that.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61438/new/

https://reviews.llvm.org/D61438



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


[PATCH] D61438: [ASTImporter] Use llvm::Expected and Error in the importer API

2019-05-09 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 198822.
martong marked 3 inline comments as done.
martong added a comment.

- Remove FIXME and return the error
- Use early return where possible and remove redundant else


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61438/new/

https://reviews.llvm.org/D61438

Files:
  clang/include/clang/AST/ASTImporter.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ExternalASTMerger.cpp
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/lib/Frontend/ASTMerge.cpp
  clang/unittests/AST/ASTImporterTest.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp
  lldb/source/Symbol/ClangASTContext.cpp
  lldb/source/Symbol/ClangASTImporter.cpp
  lldb/source/Symbol/CxxModuleHandler.cpp

Index: lldb/source/Symbol/CxxModuleHandler.cpp
===
--- lldb/source/Symbol/CxxModuleHandler.cpp
+++ lldb/source/Symbol/CxxModuleHandler.cpp
@@ -9,6 +9,7 @@
 #include "lldb/Symbol/CxxModuleHandler.h"
 
 #include "lldb/Symbol/ClangASTContext.h"
+#include "lldb/Utility/Log.h"
 #include "clang/Sema/Lookup.h"
 #include "llvm/Support/Error.h"
 
@@ -214,13 +215,15 @@
   // Import the foreign template arguments.
   llvm::SmallVector imported_args;
 
+  Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
+
   // If this logic is changed, also update templateArgsAreSupported.
   for (const TemplateArgument &arg : foreign_args.asArray()) {
 switch (arg.getKind()) {
 case TemplateArgument::Type: {
-  llvm::Expected type = m_importer->Import_New(arg.getAsType());
+  llvm::Expected type = m_importer->Import(arg.getAsType());
   if (!type) {
-llvm::consumeError(type.takeError());
+LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}");
 return {};
   }
   imported_args.push_back(TemplateArgument(*type));
@@ -229,9 +232,9 @@
 case TemplateArgument::Integral: {
   llvm::APSInt integral = arg.getAsIntegral();
   llvm::Expected type =
-  m_importer->Import_New(arg.getIntegralType());
+  m_importer->Import(arg.getIntegralType());
   if (!type) {
-llvm::consumeError(type.takeError());
+LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}");
 return {};
   }
   imported_args.push_back(
Index: lldb/source/Symbol/ClangASTImporter.cpp
===
--- lldb/source/Symbol/ClangASTImporter.cpp
+++ lldb/source/Symbol/ClangASTImporter.cpp
@@ -62,10 +62,18 @@
 
   ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);
 
-  if (delegate_sp)
-return delegate_sp->Import(type);
-
-  return QualType();
+  if (!delegate_sp)
+return QualType();
+
+  llvm::Expected ret_or_error = delegate_sp->Import(type);
+  if (!ret_or_error) {
+Log *log =
+  lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
+LLDB_LOG_ERROR(log, ret_or_error.takeError(),
+"Couldn't import type: {0}");
+return QualType();
+  }
+  return *ret_or_error;
 }
 
 lldb::opaque_compiler_type_t
@@ -105,34 +113,33 @@
 
   ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);
 
-  if (delegate_sp) {
-clang::Decl *result = delegate_sp->Import(decl);
-
-if (!result) {
-  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
+  if (!delegate_sp)
+return nullptr;
 
-  if (log) {
-lldb::user_id_t user_id = LLDB_INVALID_UID;
-ClangASTMetadata *metadata = GetDeclMetadata(decl);
-if (metadata)
-  user_id = metadata->GetUserID();
-
-if (NamedDecl *named_decl = dyn_cast(decl))
-  log->Printf("  [ClangASTImporter] WARNING: Failed to import a %s "
-  "'%s', metadata 0x%" PRIx64,
-  decl->getDeclKindName(),
-  named_decl->getNameAsString().c_str(), user_id);
-else
-  log->Printf("  [ClangASTImporter] WARNING: Failed to import a %s, "
-  "metadata 0x%" PRIx64,
-  decl->getDeclKindName(), user_id);
-  }
+  llvm::Expected result = delegate_sp->Import(decl);
+  if (!result) {
+Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
+LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}");
+if (log) {
+  lldb::user_id_t user_id = LLDB_INVALID_UID;
+  ClangASTMetadata *metadata = GetDeclMetadata(decl);
+  if (metadata)
+user_id = metadata->GetUserID();
+
+  if (NamedDecl *named_decl = dyn_cast(decl))
+log->Printf("  [ClangASTImporter] WARNING: Failed to import a %s "
+"'%s', metadata 0x%" PRIx64,
+decl->getDeclKindName(),
+named_decl->getNameAsString().c_str(), user_id);
+  els

[PATCH] D61438: [ASTImporter] Use llvm::Expected and Error in the importer API

2019-05-09 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 198824.
martong added a comment.

- Remove remaining FIXMEs


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61438/new/

https://reviews.llvm.org/D61438

Files:
  clang/include/clang/AST/ASTImporter.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ExternalASTMerger.cpp
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/lib/Frontend/ASTMerge.cpp
  clang/unittests/AST/ASTImporterTest.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionDeclMap.cpp
  lldb/source/Symbol/ClangASTContext.cpp
  lldb/source/Symbol/ClangASTImporter.cpp
  lldb/source/Symbol/CxxModuleHandler.cpp

Index: lldb/source/Symbol/CxxModuleHandler.cpp
===
--- lldb/source/Symbol/CxxModuleHandler.cpp
+++ lldb/source/Symbol/CxxModuleHandler.cpp
@@ -9,6 +9,7 @@
 #include "lldb/Symbol/CxxModuleHandler.h"
 
 #include "lldb/Symbol/ClangASTContext.h"
+#include "lldb/Utility/Log.h"
 #include "clang/Sema/Lookup.h"
 #include "llvm/Support/Error.h"
 
@@ -214,13 +215,15 @@
   // Import the foreign template arguments.
   llvm::SmallVector imported_args;
 
+  Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
+
   // If this logic is changed, also update templateArgsAreSupported.
   for (const TemplateArgument &arg : foreign_args.asArray()) {
 switch (arg.getKind()) {
 case TemplateArgument::Type: {
-  llvm::Expected type = m_importer->Import_New(arg.getAsType());
+  llvm::Expected type = m_importer->Import(arg.getAsType());
   if (!type) {
-llvm::consumeError(type.takeError());
+LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}");
 return {};
   }
   imported_args.push_back(TemplateArgument(*type));
@@ -229,9 +232,9 @@
 case TemplateArgument::Integral: {
   llvm::APSInt integral = arg.getAsIntegral();
   llvm::Expected type =
-  m_importer->Import_New(arg.getIntegralType());
+  m_importer->Import(arg.getIntegralType());
   if (!type) {
-llvm::consumeError(type.takeError());
+LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}");
 return {};
   }
   imported_args.push_back(
Index: lldb/source/Symbol/ClangASTImporter.cpp
===
--- lldb/source/Symbol/ClangASTImporter.cpp
+++ lldb/source/Symbol/ClangASTImporter.cpp
@@ -62,10 +62,18 @@
 
   ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);
 
-  if (delegate_sp)
-return delegate_sp->Import(type);
-
-  return QualType();
+  if (!delegate_sp)
+return QualType();
+
+  llvm::Expected ret_or_error = delegate_sp->Import(type);
+  if (!ret_or_error) {
+Log *log =
+  lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
+LLDB_LOG_ERROR(log, ret_or_error.takeError(),
+"Couldn't import type: {0}");
+return QualType();
+  }
+  return *ret_or_error;
 }
 
 lldb::opaque_compiler_type_t
@@ -105,34 +113,33 @@
 
   ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);
 
-  if (delegate_sp) {
-clang::Decl *result = delegate_sp->Import(decl);
-
-if (!result) {
-  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
+  if (!delegate_sp)
+return nullptr;
 
-  if (log) {
-lldb::user_id_t user_id = LLDB_INVALID_UID;
-ClangASTMetadata *metadata = GetDeclMetadata(decl);
-if (metadata)
-  user_id = metadata->GetUserID();
-
-if (NamedDecl *named_decl = dyn_cast(decl))
-  log->Printf("  [ClangASTImporter] WARNING: Failed to import a %s "
-  "'%s', metadata 0x%" PRIx64,
-  decl->getDeclKindName(),
-  named_decl->getNameAsString().c_str(), user_id);
-else
-  log->Printf("  [ClangASTImporter] WARNING: Failed to import a %s, "
-  "metadata 0x%" PRIx64,
-  decl->getDeclKindName(), user_id);
-  }
+  llvm::Expected result = delegate_sp->Import(decl);
+  if (!result) {
+Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
+LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}");
+if (log) {
+  lldb::user_id_t user_id = LLDB_INVALID_UID;
+  ClangASTMetadata *metadata = GetDeclMetadata(decl);
+  if (metadata)
+user_id = metadata->GetUserID();
+
+  if (NamedDecl *named_decl = dyn_cast(decl))
+log->Printf("  [ClangASTImporter] WARNING: Failed to import a %s "
+"'%s', metadata 0x%" PRIx64,
+decl->getDeclKindName(),
+named_decl->getNameAsString().c_str(), user_id);
+  else
+log->Printf("  [ClangASTImporter] WARNING: Failed to import a %s, "
+"metadata 0x

[clang-tools-extra] r360345 - Add the modernize-use-trailing-return check to rewrite function signatures to use trailing return types.

2019-05-09 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Thu May  9 07:48:17 2019
New Revision: 360345

URL: http://llvm.org/viewvc/llvm-project?rev=360345&view=rev
Log:
Add the modernize-use-trailing-return check to rewrite function signatures to 
use trailing return types.

Patch by Bernhard Manfred Gruber.

Added:
clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-use-trailing-return-type.rst

clang-tools-extra/trunk/test/clang-tidy/modernize-use-trailing-return-type.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt?rev=360345&r1=360344&r2=360345&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt Thu May  9 
07:48:17 2019
@@ -30,6 +30,7 @@ add_clang_library(clangTidyModernizeModu
   UseNoexceptCheck.cpp
   UseNullptrCheck.cpp
   UseOverrideCheck.cpp
+  UseTrailingReturnTypeCheck.cpp
   UseTransparentFunctorsCheck.cpp
   UseUncaughtExceptionsCheck.cpp
   UseUsingCheck.cpp

Modified: clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp?rev=360345&r1=360344&r2=360345&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp Thu 
May  9 07:48:17 2019
@@ -35,6 +35,7 @@
 #include "UseNoexceptCheck.h"
 #include "UseNullptrCheck.h"
 #include "UseOverrideCheck.h"
+#include "UseTrailingReturnTypeCheck.h"
 #include "UseTransparentFunctorsCheck.h"
 #include "UseUncaughtExceptionsCheck.h"
 #include "UseUsingCheck.h"
@@ -87,6 +88,8 @@ public:
 CheckFactories.registerCheck("modernize-use-noexcept");
 CheckFactories.registerCheck("modernize-use-nullptr");
 CheckFactories.registerCheck("modernize-use-override");
+CheckFactories.registerCheck(
+"modernize-use-trailing-return-type");
 CheckFactories.registerCheck(
 "modernize-use-transparent-functors");
 CheckFactories.registerCheck(

Added: 
clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp?rev=360345&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp 
(added)
+++ clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp 
Thu May  9 07:48:17 2019
@@ -0,0 +1,477 @@
+//===--- UseTrailingReturnTypeCheck.cpp - 
clang-tidy---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "UseTrailingReturnTypeCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Tooling/FixIt.h"
+
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+namespace {
+struct UnqualNameVisitor : public RecursiveASTVisitor {
+public:
+  UnqualNameVisitor(const FunctionDecl &F, const SourceManager &SM)
+  : F(F), SM(SM) {}
+
+  bool Collision = false;
+
+  bool shouldWalkTypesOfTypeLocs() const { return false; }
+
+  bool VisitUnqualName(StringRef UnqualName) {
+// Check for collisions with function arguments.
+for (ParmVarDecl *Param : F.parameters())
+  if (const IdentifierInfo *Ident = Param->getIdentifier())
+if (Ident->getName() == UnqualName) {
+  Collision = true;
+  return true;
+}
+return false;
+  }
+
+  bool TraverseTypeLoc(TypeLoc TL, bool Elaborated = false) {
+if (TL.isNull())
+  return true;
+
+if (!Elaborated) {
+  switch (TL.getTypeLocClass()) {
+  case TypeLoc::Record:
+if (VisitUnqualName(
+TL.getAs().getTypePtr()->getDecl()->getName()))
+  return false;
+break;
+  case TypeLoc::Enum:
+if (VisitUnqualName(
+TL.getAs().getTypePtr()->getDecl

[PATCH] D56160: [clang-tidy] modernize-use-trailing-return-type check

2019-05-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D56160#1496391 , @bernhardmgruber 
wrote:

> @aaron.ballman I do not have commit privileges and I would be very thankful, 
> if you could commit this patch for me! Thank you!


I've commit for you in r360345, thank you for the patch!


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D56160/new/

https://reviews.llvm.org/D56160



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


[PATCH] D61734: [clangd] Bump index version and get rid of wrong assertion

2019-05-09 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: ilya-biryukov.
Herald added subscribers: cfe-commits, arphaman, jkorous, MaskRay.
Herald added a project: clang.

After rL360344 , BackgroundIndex expects 
symbols with zero refcounts.
Therefore existing index files are no longer valid.

Assertion regarding finding target of a reference was wrong, since
background-index might still be going on or we might've loaded only some part of
the shards and might be missing the declaring shards for the symbol.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D61734

Files:
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/Serialization.cpp


Index: clang-tools-extra/clangd/index/Serialization.cpp
===
--- clang-tools-extra/clangd/index/Serialization.cpp
+++ clang-tools-extra/clangd/index/Serialization.cpp
@@ -370,7 +370,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 9;
+constexpr static uint32_t Version = 10;
 
 llvm::Expected readRIFF(llvm::StringRef Data) {
   auto RIFF = riff::readFile(Data);
Index: clang-tools-extra/clangd/index/FileIndex.cpp
===
--- clang-tools-extra/clangd/index/FileIndex.cpp
+++ clang-tools-extra/clangd/index/FileIndex.cpp
@@ -138,7 +138,9 @@
 for (const RefSlab *Refs : MainFileRefs)
   for (const auto &Sym : *Refs) {
 auto It = Merged.find(Sym.first);
-assert(It != Merged.end() && "Reference to unknown symbol");
+// This might happen while background-index is still running.
+if (It == Merged.end())
+  continue;
 It->getSecond().References += Sym.second.size();
   }
 SymsStorage.reserve(Merged.size());


Index: clang-tools-extra/clangd/index/Serialization.cpp
===
--- clang-tools-extra/clangd/index/Serialization.cpp
+++ clang-tools-extra/clangd/index/Serialization.cpp
@@ -370,7 +370,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 9;
+constexpr static uint32_t Version = 10;
 
 llvm::Expected readRIFF(llvm::StringRef Data) {
   auto RIFF = riff::readFile(Data);
Index: clang-tools-extra/clangd/index/FileIndex.cpp
===
--- clang-tools-extra/clangd/index/FileIndex.cpp
+++ clang-tools-extra/clangd/index/FileIndex.cpp
@@ -138,7 +138,9 @@
 for (const RefSlab *Refs : MainFileRefs)
   for (const auto &Sym : *Refs) {
 auto It = Merged.find(Sym.first);
-assert(It != Merged.end() && "Reference to unknown symbol");
+// This might happen while background-index is still running.
+if (It == Merged.end())
+  continue;
 It->getSecond().References += Sym.second.size();
   }
 SymsStorage.reserve(Merged.size());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r360346 - Fixing a link in the release notes to appease the Sphinx bot.

2019-05-09 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Thu May  9 08:00:38 2019
New Revision: 360346

URL: http://llvm.org/viewvc/llvm-project?rev=360346&view=rev
Log:
Fixing a link in the release notes to appease the Sphinx bot.

Modified:
clang-tools-extra/trunk/docs/ReleaseNotes.rst

Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=360346&r1=360345&r2=360346&view=diff
==
--- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original)
+++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Thu May  9 08:00:38 2019
@@ -151,8 +151,8 @@ Improvements to clang-tidy
   finds and replaces cases that match the pattern ``var &&
   isa(var)``, where ``var`` is evaluated twice.
 
-- New :doc:`modernize-use-trailing-type-return
-  ` check.
+- New :doc:`modernize-use-trailing-return-type
+  ` check.
 
   Rewrites function signatures to use a trailing return type.
 


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


[clang-tools-extra] r360348 - Revert r360345 and r360346, as they are not passing the testbots.

2019-05-09 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Thu May  9 08:06:41 2019
New Revision: 360348

URL: http://llvm.org/viewvc/llvm-project?rev=360348&view=rev
Log:
Revert r360345 and r360346, as they are not passing the testbots.

http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/builds/48063/steps/test/logs/stdio

Removed:
clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-use-trailing-return-type.rst

clang-tools-extra/trunk/test/clang-tidy/modernize-use-trailing-return-type.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt?rev=360348&r1=360347&r2=360348&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt Thu May  9 
08:06:41 2019
@@ -30,7 +30,6 @@ add_clang_library(clangTidyModernizeModu
   UseNoexceptCheck.cpp
   UseNullptrCheck.cpp
   UseOverrideCheck.cpp
-  UseTrailingReturnTypeCheck.cpp
   UseTransparentFunctorsCheck.cpp
   UseUncaughtExceptionsCheck.cpp
   UseUsingCheck.cpp

Modified: clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp?rev=360348&r1=360347&r2=360348&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp Thu 
May  9 08:06:41 2019
@@ -35,7 +35,6 @@
 #include "UseNoexceptCheck.h"
 #include "UseNullptrCheck.h"
 #include "UseOverrideCheck.h"
-#include "UseTrailingReturnTypeCheck.h"
 #include "UseTransparentFunctorsCheck.h"
 #include "UseUncaughtExceptionsCheck.h"
 #include "UseUsingCheck.h"
@@ -88,8 +87,6 @@ public:
 CheckFactories.registerCheck("modernize-use-noexcept");
 CheckFactories.registerCheck("modernize-use-nullptr");
 CheckFactories.registerCheck("modernize-use-override");
-CheckFactories.registerCheck(
-"modernize-use-trailing-return-type");
 CheckFactories.registerCheck(
 "modernize-use-transparent-functors");
 CheckFactories.registerCheck(

Removed: 
clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp?rev=360347&view=auto
==
--- clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp 
(removed)
@@ -1,477 +0,0 @@
-//===--- UseTrailingReturnTypeCheck.cpp - 
clang-tidy---===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===--===//
-
-#include "UseTrailingReturnTypeCheck.h"
-#include "clang/AST/ASTContext.h"
-#include "clang/AST/RecursiveASTVisitor.h"
-#include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "clang/Tooling/FixIt.h"
-
-#include 
-
-using namespace clang::ast_matchers;
-
-namespace clang {
-namespace tidy {
-namespace modernize {
-namespace {
-struct UnqualNameVisitor : public RecursiveASTVisitor {
-public:
-  UnqualNameVisitor(const FunctionDecl &F, const SourceManager &SM)
-  : F(F), SM(SM) {}
-
-  bool Collision = false;
-
-  bool shouldWalkTypesOfTypeLocs() const { return false; }
-
-  bool VisitUnqualName(StringRef UnqualName) {
-// Check for collisions with function arguments.
-for (ParmVarDecl *Param : F.parameters())
-  if (const IdentifierInfo *Ident = Param->getIdentifier())
-if (Ident->getName() == UnqualName) {
-  Collision = true;
-  return true;
-}
-return false;
-  }
-
-  bool TraverseTypeLoc(TypeLoc TL, bool Elaborated = false) {
-if (TL.isNull())
-  return true;
-
-if (!Elaborated) {
-  switch (TL.getTypeLocClass()) {
-  case TypeLoc::Record:
-if (VisitUnqualName(
-TL.getAs().getTypePtr()->getDecl()->getName()))
-  return false;
-break;
-  case TypeLoc::Enum:
-if (VisitUnqualName(
-TL

[PATCH] D61734: [clangd] Bump index version and get rid of wrong assertion

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61734/new/

https://reviews.llvm.org/D61734



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


[clang-tools-extra] r360349 - [clangd] Bump index version and get rid of wrong assertion

2019-05-09 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Thu May  9 08:07:53 2019
New Revision: 360349

URL: http://llvm.org/viewvc/llvm-project?rev=360349&view=rev
Log:
[clangd] Bump index version and get rid of wrong assertion

Summary:
After rL360344, BackgroundIndex expects symbols with zero refcounts.
Therefore existing index files are no longer valid.

Assertion regarding finding target of a reference was wrong, since
background-index might still be going on or we might've loaded only some part of
the shards and might be missing the declaring shards for the symbol.

Reviewers: ilya-biryukov

Subscribers: MaskRay, jkorous, arphaman, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/index/FileIndex.cpp
clang-tools-extra/trunk/clangd/index/Serialization.cpp

Modified: clang-tools-extra/trunk/clangd/index/FileIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/FileIndex.cpp?rev=360349&r1=360348&r2=360349&view=diff
==
--- clang-tools-extra/trunk/clangd/index/FileIndex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/FileIndex.cpp Thu May  9 08:07:53 2019
@@ -138,7 +138,9 @@ FileSymbols::buildIndex(IndexType Type,
 for (const RefSlab *Refs : MainFileRefs)
   for (const auto &Sym : *Refs) {
 auto It = Merged.find(Sym.first);
-assert(It != Merged.end() && "Reference to unknown symbol");
+// This might happen while background-index is still running.
+if (It == Merged.end())
+  continue;
 It->getSecond().References += Sym.second.size();
   }
 SymsStorage.reserve(Merged.size());

Modified: clang-tools-extra/trunk/clangd/index/Serialization.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Serialization.cpp?rev=360349&r1=360348&r2=360349&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp Thu May  9 08:07:53 
2019
@@ -370,7 +370,7 @@ readRefs(Reader &Data, llvm::ArrayRef readRIFF(llvm::StringRef Data) {
   auto RIFF = riff::readFile(Data);


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


[PATCH] D56160: [clang-tidy] modernize-use-trailing-return-type check

2019-05-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman reopened this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

In D56160#1496594 , @aaron.ballman 
wrote:

> In D56160#1496391 , @bernhardmgruber 
> wrote:
>
> > @aaron.ballman I do not have commit privileges and I would be very 
> > thankful, if you could commit this patch for me! Thank you!
>
>
> I've commit for you in r360345, thank you for the patch!


I had to revert in r360348 as the patch does not pass the testbots: 
http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/builds/48063/steps/test/logs/stdio

When you correct the issues, I'm happy to reapply the patch for you. If you 
could also fix up the link in the release notes as part of the cleanup, that 
would be great (it turned out there was a typo -- I've pointed it out in the 
review).




Comment at: docs/ReleaseNotes.rst:154-155
 
+- New :doc:`modernize-use-trailing-type-return
+  ` check.
+

These should be `modernize-use-trailing-return-type` instead (there's a typo).


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D56160/new/

https://reviews.llvm.org/D56160



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


[PATCH] D61497: [clangd] Introduce a structured hover response

2019-05-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Main comment is that I think the code is doing too much work to exactly 
reproduce the current output, and include as much information as possible.
Minimizing the diff is good all else equal, but one of the goals here is to 
have richer hovercards that are more consistent across the different codepaths 
that generate them.




Comment at: clang-tools-extra/clangd/XRefs.cpp:456
 
+// FIXME: Expose in AST/Decl ?
+void printSpecifiers(llvm::raw_ostream &Out, const FunctionDecl *D) {

This has been pulled from DeclPrinter, so by definition duplicates info in the 
printed decl. We should only do this for info that's important, and I'm not 
sure most of this meets the bar.

 - that a function is virtual is certainly important (but isVirtual(), not 
isVirtualAsWritten())
 - that the declaration we found for a function is extern is certainly 
unimportant (it says something about the *decl*, not the function)
 - that a function is static means *something* important, but being a 
non-instance member is pretty different from being an internal helper function. 
Saying Kind=StaticMethod seems more useful for presentation than putting 
"static" next to the type again.

Aside from this, the current implementation puts these specifiers in the type, 
which they're not - functions don't return virtual ints or static strings.

I think we can probably drop these for now, and leave them in the printed decl 
only. We may want to revisit this as part of having Kind describe results more 
precisely.



Comment at: clang-tools-extra/clangd/XRefs.cpp:726
+llvm::raw_string_ostream OS(*P.Type);
+printSpecifiers(OS, PVD);
+PVD->getType().print(OS, Policy);

what are the storage class specifiers that are relevant to function parameters?



Comment at: clang-tools-extra/clangd/XRefs.cpp:737
+}
+if (FD->isVariadic()) {
+  HI.Parameters->emplace_back();

Not totally sure this is the best way to model variadics. We could consider 
leaving it out for now.



Comment at: clang-tools-extra/clangd/XRefs.cpp:1201
+
+  if (Kind == SymbolKind::String) {
+// We use SymbolKind::String for macro kinds

This really seems like the wrong idea to me.
"Kind" is a category description suitable to be shown to the user, it's 
supposed to be useful.
In odd cases we may choose to do things like not show the type if the kind is 
function.

But HoverInfo is basically a box of facts to render, and using totally 
different rendering strategies for different kinds (and assuming strings mean 
macros) cuts against this.



Comment at: clang-tools-extra/clangd/XRefs.cpp:1209
+else {
+  if (TemplateParameters) {
+Output.emplace_back();

why do we have this no-definition case?
Please avoid reinventing code to print C++ syntax if possible...



Comment at: clang-tools-extra/clangd/unittests/XRefsTests.cpp:940
   )cpp",
-  "class std::initializer_list",
+  "template<> class initializer_list {}",
   },

hmm, this is a bit weird - this uses specialization syntax but there's no 
actual specialization here right?
I think the old output without `template<>` is probably better if possible.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61497/new/

https://reviews.llvm.org/D61497



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


[PATCH] D53866: [Preamble] Stop circular inclusion of main file when building preamble

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov marked an inline comment as done.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

LGTM. See the nit about naming of an error, though




Comment at: include/clang/Basic/DiagnosticLexKinds.td:429
   "error opening file '%0': %1">, DefaultFatal;
+def err_pp_including_mainfile_for_preamble : Error<
+  "main file cannot be included recursively when building a preamble">;

NIT: Maybe change to err_pp_including_mainfile_**in**_preamble?




Comment at: lib/Basic/SourceManager.cpp:1594
 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
-if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) 
{
+if (MainFile && *SourceFileName == 
llvm::sys::path::filename(MainFile->getName())) {
   SourceFileUID = getActualFileUID(SourceFile);

nik wrote:
> ilya-biryukov wrote:
> > nik wrote:
> > > ilya-biryukov wrote:
> > > > Can this actually be`null`? 
> > > The comment for OrigEntry states that it might be null:
> > > 
> > > /// Reference to the file entry representing this ContentCache.
> > > ///
> > > /// This reference does not own the FileEntry object.
> > > ///
> > > /// It is possible for this to be NULL if the ContentCache 
> > > encapsulates
> > > /// an imaginary text buffer.
> > > const FileEntry *OrigEntry;
> > > 
> > > Note also that further down in this function, a null check for 
> > > MainContentCache->OrigEntry is done, so I believe that this was just 
> > > forgotten here (since there is also no assert) and we are the first one 
> > > running into this with the introduced call to 
> > > SourceMgr.translateFile(File).
> > > 
> > > I've tried to understand why we end up with a nullptr here, but this goes 
> > > beyond me in the time I've taken for this. What I've observed is that 
> > > module code path (LibclangReparseTest.ReparseWithModule vs 
> > > LibclangReparseTest.Reparse) creates at least a MemoryBuffer more (in 
> > > ModuleMap::parseModuleMapFile; possibly the one referred with "imaginary 
> > > text buffer" from the comment) and I suspect this to be somehow related 
> > > with the OrigEntry nullptr.
> > Should we check for equality of `MainContentCache->ContentsEntry` in that 
> > case? I guess this is what should be set for "imaginary" files.
> Does not help in this particular case as ContentsEntry is also a nullptr. All 
> the members of the ContentsCache seem to be either nullptr or 0 as that 
> particular point of execution.
> 
> How to continue?
> 
> a) Accept as is.
> b) Ask someone knowledgeable for whom this could be a no-brainer that could 
> respond hopefully soon. Any candidate?
> c) Or should I dig deeper? This can take quite some time as this area is new 
> for me.
> 
Wow, I guess I don't understand this code deep enough.
Your change looks ok, I'm happy to LGTM this. But if you're actually interested 
in digging deeper, that would be super-useful.

Based on what you're describe, it feels like "imaginary" main file works by 
accident rather than being properly handled in this function.

BTW, thanks for moving the check up, it definitely looks nicer this way.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D53866/new/

https://reviews.llvm.org/D53866



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


[PATCH] D50993: [clangd] Increase stack size of the new threads on macOS

2019-05-09 Thread Dmitry via Phabricator via cfe-commits
Dmitry.Kozhevnikov added a comment.

In D50993#1496250 , @ilya-biryukov 
wrote:

> We should definitely land this.
>
> @Dmitry.Kozhevnikov, you don't have commit access, right? Should we land 
> these two revisions for you?


The depending review was never done for the Windows part, also I really don’t 
like how it’ interacting with threading disabled (that’s something I’ve 
realized after submitting the review) - so I’ve abandoned that, sorry. I could 
make an another take next week - or should we wait for D61724 
?


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D50993/new/

https://reviews.llvm.org/D50993



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


[PATCH] D50993: [clangd] Increase stack size of the new threads on macOS

2019-05-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D50993#1496638 , 
@Dmitry.Kozhevnikov wrote:

> In D50993#1496250 , @ilya-biryukov 
> wrote:
>
> > We should definitely land this.
> >
> > @Dmitry.Kozhevnikov, you don't have commit access, right? Should we land 
> > these two revisions for you?
>
>
> The depending review was never done for the Windows part, also I really don’t 
> like how it’ interacting with threading disabled (that’s something I’ve 
> realized after submitting the review) - so I’ve abandoned that, sorry. I 
> could make an another take next week - or should we wait for D61724 
> ?


D61724  has landed.

`LLVM_ENABLE_THREADS=Off` is now "officially" unsupported in clangd (rL360115 
), so if it's not sensible to have this in 
llvm/Support due to LLVM_ENABLE_THREADS then we can put it in clangd instead.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D50993/new/

https://reviews.llvm.org/D50993



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


[PATCH] D60974: Clang IFSO driver action.

2019-05-09 Thread Puyan Lotfi via Phabricator via cfe-commits
plotfi marked 2 inline comments as done.
plotfi added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:3590
+Twine("-interface-stubs-version=") +
+Args.getLastArgValue(options::OPT_ifso_version_EQ)));
+  }

compnerd wrote:
> Please ensure that the value being passed is valid or emit a diagnostic.
Couldn't I do this in the cc1 path? 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60974/new/

https://reviews.llvm.org/D60974



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


[PATCH] D61734: [clangd] Bump index version and get rid of wrong assertion

2019-05-09 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE360349: [clangd] Bump index version and get rid of wrong 
assertion (authored by kadircet, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D61734?vs=198825&id=198828#toc

Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61734/new/

https://reviews.llvm.org/D61734

Files:
  clangd/index/FileIndex.cpp
  clangd/index/Serialization.cpp


Index: clangd/index/Serialization.cpp
===
--- clangd/index/Serialization.cpp
+++ clangd/index/Serialization.cpp
@@ -370,7 +370,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 9;
+constexpr static uint32_t Version = 10;
 
 llvm::Expected readRIFF(llvm::StringRef Data) {
   auto RIFF = riff::readFile(Data);
Index: clangd/index/FileIndex.cpp
===
--- clangd/index/FileIndex.cpp
+++ clangd/index/FileIndex.cpp
@@ -138,7 +138,9 @@
 for (const RefSlab *Refs : MainFileRefs)
   for (const auto &Sym : *Refs) {
 auto It = Merged.find(Sym.first);
-assert(It != Merged.end() && "Reference to unknown symbol");
+// This might happen while background-index is still running.
+if (It == Merged.end())
+  continue;
 It->getSecond().References += Sym.second.size();
   }
 SymsStorage.reserve(Merged.size());


Index: clangd/index/Serialization.cpp
===
--- clangd/index/Serialization.cpp
+++ clangd/index/Serialization.cpp
@@ -370,7 +370,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 9;
+constexpr static uint32_t Version = 10;
 
 llvm::Expected readRIFF(llvm::StringRef Data) {
   auto RIFF = riff::readFile(Data);
Index: clangd/index/FileIndex.cpp
===
--- clangd/index/FileIndex.cpp
+++ clangd/index/FileIndex.cpp
@@ -138,7 +138,9 @@
 for (const RefSlab *Refs : MainFileRefs)
   for (const auto &Sym : *Refs) {
 auto It = Merged.find(Sym.first);
-assert(It != Merged.end() && "Reference to unknown symbol");
+// This might happen while background-index is still running.
+if (It == Merged.end())
+  continue;
 It->getSecond().References += Sym.second.size();
   }
 SymsStorage.reserve(Merged.size());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D28462: clang-format: Add new style option AlignConsecutiveMacros

2019-05-09 Thread Micah S. via Phabricator via cfe-commits
micah-s added a comment.

@djasper @klimek @krasimir @sammccall @enyquist  Can I trouble you for an 
update?

In D28462#1492600 , @jkorous wrote:

> Hi @VelocityRa, just FYI - it's considered fine to ping your reviewers once 
> per week here if you've addressed their comments and there's no activity in 
> the review. Sometimes people just get distracted by other things.





CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D28462/new/

https://reviews.llvm.org/D28462



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


[PATCH] D59885: [Lex] Allow to consume tokens while preprocessing

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Here are some numbers from running `clang -cc1 -Eonly` on `SemaExpr.cpp`, it 
includes a whole ton of headers, including a rather large `TreeTransform.h`. 
This was run on my machine, so keep in mind it's rather noisy. Minimal times 
should be somewhat representative, though.

  Before:
Time (mean ± σ): 159.5 ms ±   7.3 ms[User: 137.3 ms, System: 22.1 
ms]
Range (min … max):   148.9 ms … 199.5 ms100 runs
  
  After (no callback specified):
Time (mean ± σ): 165.0 ms ±   7.5 ms[User: 142.8 ms, System: 22.2 
ms]
Range (min … max):   155.0 ms … 196.7 ms100 runs

And two more measurements with callbacks non-empty callbacks:

  Counting tokens:
Time (mean ± σ): 169.0 ms ±   9.5 ms[User: 147.3 ms, System: 21.7 
ms]
Range (min … max):   158.3 ms … 206.0 ms100 runs
  
  Saving tokens to a vector:
Time (mean ± σ): 191.0 ms ±   5.5 ms[User: 154.1 ms, System: 36.8 
ms]
Range (min … max):   180.4 ms … 221.0 ms100 runs

Overall, the performance cost in empty-callback case seems to be lower than 
`5%`. This is significant, but hopefully acceptable.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59885/new/

https://reviews.llvm.org/D59885



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


[PATCH] D61739: check_clang_tidy.py now passes `-format-style=none` to clang_tidy

2019-05-09 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr created this revision.
gribozavr added a reviewer: alexfh.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

If the test does not specify a formatting style, force "none"; otherwise
autodetection logic can discover a ".clang-tidy" file that is not
related to the test.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D61739

Files:
  clang-tools-extra/test/clang-tidy/check_clang_tidy.py


Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -69,20 +69,32 @@
   temp_file_name = temp_file_name + extension
 
   clang_tidy_extra_args = extra_args
-  if len(clang_tidy_extra_args) == 0:
-clang_tidy_extra_args = ['--']
+  clang_extra_args = []
+  if '--' in extra_args:
+i = clang_tidy_extra_args.index('--')
+clang_extra_args = clang_tidy_extra_args[i + 1:]
+clang_tidy_extra_args = clang_tidy_extra_args[:i]
+
+  # If the test does not specify a formatting style, force "none"; otherwise
+  # autodetection logic can discover a ".clang-tidy" file that is not related 
to
+  # the test.
+  if not any(
+  [arg.startswith('-format-style=') for arg in clang_tidy_extra_args]):
+clang_tidy_extra_args.append('-format-style=none')
+
+  if len(clang_extra_args) == 0:
 if extension in ['.cpp', '.hpp', '.mm']:
-  clang_tidy_extra_args.append('--std=c++11')
+  clang_extra_args.append('--std=c++11')
 if extension in ['.m', '.mm']:
-  clang_tidy_extra_args.extend(
+  clang_extra_args.extend(
   ['-fobjc-abi-version=2', '-fobjc-arc'])
 
   # Tests should not rely on STL being available, and instead provide mock
   # implementations of relevant APIs.
-  clang_tidy_extra_args.append('-nostdinc++')
+  clang_extra_args.append('-nostdinc++')
 
   if resource_dir is not None:
-clang_tidy_extra_args.append('-resource-dir=%s' % resource_dir)
+clang_extra_args.append('-resource-dir=%s' % resource_dir)
 
   with open(input_file_name, 'r') as input_file:
 input_text = input_file.read()
@@ -138,7 +150,7 @@
   write_file(original_file_name, cleaned_test)
 
   args = ['clang-tidy', temp_file_name, '-fix', '--checks=-*,' + check_name] + 
\
-clang_tidy_extra_args
+  clang_tidy_extra_args + ['--'] + clang_extra_args
   if expect_clang_tidy_error:
 args.insert(0, 'not')
   print('Running ' + repr(args) + '...')


Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -69,20 +69,32 @@
   temp_file_name = temp_file_name + extension
 
   clang_tidy_extra_args = extra_args
-  if len(clang_tidy_extra_args) == 0:
-clang_tidy_extra_args = ['--']
+  clang_extra_args = []
+  if '--' in extra_args:
+i = clang_tidy_extra_args.index('--')
+clang_extra_args = clang_tidy_extra_args[i + 1:]
+clang_tidy_extra_args = clang_tidy_extra_args[:i]
+
+  # If the test does not specify a formatting style, force "none"; otherwise
+  # autodetection logic can discover a ".clang-tidy" file that is not related to
+  # the test.
+  if not any(
+  [arg.startswith('-format-style=') for arg in clang_tidy_extra_args]):
+clang_tidy_extra_args.append('-format-style=none')
+
+  if len(clang_extra_args) == 0:
 if extension in ['.cpp', '.hpp', '.mm']:
-  clang_tidy_extra_args.append('--std=c++11')
+  clang_extra_args.append('--std=c++11')
 if extension in ['.m', '.mm']:
-  clang_tidy_extra_args.extend(
+  clang_extra_args.extend(
   ['-fobjc-abi-version=2', '-fobjc-arc'])
 
   # Tests should not rely on STL being available, and instead provide mock
   # implementations of relevant APIs.
-  clang_tidy_extra_args.append('-nostdinc++')
+  clang_extra_args.append('-nostdinc++')
 
   if resource_dir is not None:
-clang_tidy_extra_args.append('-resource-dir=%s' % resource_dir)
+clang_extra_args.append('-resource-dir=%s' % resource_dir)
 
   with open(input_file_name, 'r') as input_file:
 input_text = input_file.read()
@@ -138,7 +150,7 @@
   write_file(original_file_name, cleaned_test)
 
   args = ['clang-tidy', temp_file_name, '-fix', '--checks=-*,' + check_name] + \
-clang_tidy_extra_args
+  clang_tidy_extra_args + ['--'] + clang_extra_args
   if expect_clang_tidy_error:
 args.insert(0, 'not')
   print('Running ' + repr(args) + '...')
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61739: check_clang_tidy.py now passes `-format-style=none` to clang_tidy

2019-05-09 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

LG, thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61739/new/

https://reviews.llvm.org/D61739



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


[PATCH] D61438: [ASTImporter] Use llvm::Expected and Error in the importer API

2019-05-09 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added inline comments.



Comment at: clang/include/clang/AST/ASTImporter.h:203
 /// context, or the import error.
-llvm::Expected Import_New(TypeSourceInfo *FromTSI);
-// FIXME: Remove this version.
-TypeSourceInfo *Import(TypeSourceInfo *FromTSI);
+llvm::Expected Import(TypeSourceInfo *FromTSI);
 

Wouldn't it make more sense to return `Expected`?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61438/new/

https://reviews.llvm.org/D61438



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


[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 198857.
ilya-biryukov added a comment.

- Move the constuction logic to a separate class, split into multiple methods.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59887/new/

https://reviews.llvm.org/D59887

Files:
  clang/include/clang/Tooling/Syntax/Tokens.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/Syntax/CMakeLists.txt
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/Syntax/CMakeLists.txt
  clang/unittests/Tooling/Syntax/TokensTest.cpp

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -0,0 +1,622 @@
+//===- TokensTest.cpp -===//
+//
+// 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 "clang/Tooling/Syntax/Tokens.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Expr.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/FileSystemOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.def"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/Utils.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/raw_os_ostream.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock-more-matchers.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang;
+using namespace clang::syntax;
+
+using llvm::ValueIs;
+using ::testing::AllOf;
+using ::testing::Contains;
+using ::testing::ElementsAre;
+using ::testing::Matcher;
+using ::testing::Not;
+using ::testing::StartsWith;
+
+namespace {
+// Checks the passed ArrayRef has the same begin() and end() iterators as the
+// argument.
+MATCHER_P(SameRange, A, "") {
+  return A.begin() == arg.begin() && A.end() == arg.end();
+}
+// Matchers for syntax::Token.
+MATCHER_P(Kind, K, "") { return arg.kind() == K; }
+MATCHER_P2(HasText, Text, SourceMgr, "") {
+  return arg.text(*SourceMgr) == Text;
+}
+/// Checks the start and end location of a token are equal to SourceRng.
+MATCHER_P(RangeIs, SourceRng, "") {
+  return arg.location() == SourceRng.first &&
+ arg.endLocation() == SourceRng.second;
+}
+
+class TokenCollectorTest : public ::testing::Test {
+public:
+  /// Run the clang frontend, collect the preprocessed tokens from the frontend
+  /// invocation and store them in this->Buffer.
+  /// This also clears SourceManager before running the compiler.
+  void recordTokens(llvm::StringRef Code) {
+class RecordTokens : public ASTFrontendAction {
+public:
+  explicit RecordTokens(TokenBuffer &Result) : Result(Result) {}
+
+  bool BeginSourceFileAction(CompilerInstance &CI) override {
+assert(!Collector && "expected only a single call to BeginSourceFile");
+Collector.emplace(CI.getPreprocessor());
+return true;
+  }
+  void EndSourceFileAction() override {
+assert(Collector && "BeginSourceFileAction was never called");
+Result = std::move(*Collector).consume();
+  }
+
+  std::unique_ptr
+  CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
+return llvm::make_unique();
+  }
+
+private:
+  TokenBuffer &Result;
+  llvm::Optional Collector;
+};
+
+constexpr const char *FileName = "./input.cpp";
+FS->addFile(FileName, time_t(), llvm::MemoryBuffer::getMemBufferCopy(""));
+// Prepare to run a compiler.
+std::vector Args = {"tok-test", "-std=c++03", "-fsyntax-only",
+  FileName};
+auto CI = createInvocationFromCommandLine(Args, Diags, FS);
+assert(CI);
+CI->getFrontendOpts().DisableFree = false;
+CI->getPreproces

[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:130
+  OS << llvm::formatv(
+  "['{0}'_{1}, '{2}'_{3}) => ['{4}'_{5}, '{6}'_{7})\n",
+  PrintToken(File.SpelledTokens[M.BeginSpelled]), M.BeginSpelled,

ilya-biryukov wrote:
> sammccall wrote:
> > sammccall wrote:
> > > As predicted :-) I think these `_` suffixes are a maintenance 
> > > hazard.
> > > 
> > > In practice, the assertions are likely to add them by copy-pasting the 
> > > test output.
> > > 
> > > They guard against a class of error that doesn't seem very likely, and in 
> > > practice they don't even really prevent it (because of the copy/paste 
> > > issue).
> > > 
> > > I'd suggest just dropping them, and living with the test assertions being 
> > > slightly ambiguous.
> > > 
> > > Failing that, some slightly trickier formatting could give more context:
> > > 
> > > `A B C D E F` --> `A B  ... E F`
> > > 
> > > With special cases for smaller numbers of tokens. I don't like the 
> > > irregularity of that approach though.
> > (this one is still open)
> Will make sure to do something about it before submitting
As mentioned in the offline conversations, we both agree that we don't want to 
have ambiguous test-cases.
The proposed alternative was putting the counters of tokens **of the same 
kind** in the same token stream, with a goal of making updating test-cases 
simpler (now one would need to update only indicies of the tokens they 
changed). 

After playing around with the idea, I think this complicates the dumping 
function too much. The easiest way to update the test is to run it and 
copy-paste the expected output.
So I'd keep as is and avoiding the extra complexity if that's ok



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:226
+  TokenBuffer B(SourceMgr);
+  for (unsigned I = 0; I < Expanded.size(); ++I) {
+auto FID =

sammccall wrote:
> Is there a reason we do this at the end instead of as tokens are collected?
No strong reason, just wanted to keep the preprocessor callback minimal


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59887/new/

https://reviews.llvm.org/D59887



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


[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 198862.
ilya-biryukov marked 6 inline comments as done.
ilya-biryukov added a comment.

- Move filling the gaps at the end of files to a separate function


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59887/new/

https://reviews.llvm.org/D59887

Files:
  clang/include/clang/Tooling/Syntax/Tokens.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/Syntax/CMakeLists.txt
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/Syntax/CMakeLists.txt
  clang/unittests/Tooling/Syntax/TokensTest.cpp

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -0,0 +1,622 @@
+//===- TokensTest.cpp -===//
+//
+// 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 "clang/Tooling/Syntax/Tokens.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Expr.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/FileSystemOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.def"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/Utils.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/raw_os_ostream.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock-more-matchers.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang;
+using namespace clang::syntax;
+
+using llvm::ValueIs;
+using ::testing::AllOf;
+using ::testing::Contains;
+using ::testing::ElementsAre;
+using ::testing::Matcher;
+using ::testing::Not;
+using ::testing::StartsWith;
+
+namespace {
+// Checks the passed ArrayRef has the same begin() and end() iterators as the
+// argument.
+MATCHER_P(SameRange, A, "") {
+  return A.begin() == arg.begin() && A.end() == arg.end();
+}
+// Matchers for syntax::Token.
+MATCHER_P(Kind, K, "") { return arg.kind() == K; }
+MATCHER_P2(HasText, Text, SourceMgr, "") {
+  return arg.text(*SourceMgr) == Text;
+}
+/// Checks the start and end location of a token are equal to SourceRng.
+MATCHER_P(RangeIs, SourceRng, "") {
+  return arg.location() == SourceRng.first &&
+ arg.endLocation() == SourceRng.second;
+}
+
+class TokenCollectorTest : public ::testing::Test {
+public:
+  /// Run the clang frontend, collect the preprocessed tokens from the frontend
+  /// invocation and store them in this->Buffer.
+  /// This also clears SourceManager before running the compiler.
+  void recordTokens(llvm::StringRef Code) {
+class RecordTokens : public ASTFrontendAction {
+public:
+  explicit RecordTokens(TokenBuffer &Result) : Result(Result) {}
+
+  bool BeginSourceFileAction(CompilerInstance &CI) override {
+assert(!Collector && "expected only a single call to BeginSourceFile");
+Collector.emplace(CI.getPreprocessor());
+return true;
+  }
+  void EndSourceFileAction() override {
+assert(Collector && "BeginSourceFileAction was never called");
+Result = std::move(*Collector).consume();
+  }
+
+  std::unique_ptr
+  CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
+return llvm::make_unique();
+  }
+
+private:
+  TokenBuffer &Result;
+  llvm::Optional Collector;
+};
+
+constexpr const char *FileName = "./input.cpp";
+FS->addFile(FileName, time_t(), llvm::MemoryBuffer::getMemBufferCopy(""));
+// Prepare to run a compiler.
+std::vector Args = {"tok-test", "-std=c++03", "-fsyntax-only",
+  FileName};
+auto CI = createInvocationFromCommandLine(Args, Diags, FS);
+assert(CI);
+CI->getFrontendOpts().Disabl

[PATCH] D61742: [Driver][Windows] Add dependent lib argument for profile instr generate

2019-05-09 Thread Russell Gallop via Phabricator via cfe-commits
russell.gallop created this revision.
russell.gallop added reviewers: rnk, bogner.
russell.gallop added a project: clang.

This is needed so lld-link can find clang_rt.profile when self hosting on 
Windows with PGO.

Trying to self host on Windows with PGO runs into undefined symbols as lld-link 
doesn't know to link clang_rt.profile as discussed here:
http://lists.llvm.org/pipermail/llvm-dev/2019-January/129500.html

Using clang-cl as a linker knows to add the library but self hosting, using 
-DCMAKE_LINKER=<...>/lld-link.exe doesn't.  I think that the cleanest way to 
make this work is to add a dependent library when using profile-instr-generate 
on Windows.

Note some cmake changes are also required to get PGO self hosting on Windows 
working. I will post them separately.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D61742

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/cl-options.c


Index: clang/test/Driver/cl-options.c
===
--- clang/test/Driver/cl-options.c
+++ clang/test/Driver/cl-options.c
@@ -66,7 +66,7 @@
 // RUN: %clang_cl -### /FA -fprofile-instr-generate=/tmp/somefile.profraw -- 
%s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-GENERATE-FILE %s
 // RUN: %clang_cl -### /FA -fprofile-instr-generate -fprofile-instr-use -- %s 
2>&1 | FileCheck -check-prefix=CHECK-NO-MIX-GEN-USE %s
 // RUN: %clang_cl -### /FA -fprofile-instr-generate -fprofile-instr-use=file 
-- %s 2>&1 | FileCheck -check-prefix=CHECK-NO-MIX-GEN-USE %s
-// CHECK-PROFILE-GENERATE: "-fprofile-instrument=clang"
+// CHECK-PROFILE-GENERATE: "-fprofile-instrument=clang" 
"--dependent-lib={{[^"]*}}clang_rt.profile-{{[^"]*}}.lib"
 // CHECK-PROFILE-GENERATE-FILE: 
"-fprofile-instrument-path=/tmp/somefile.profraw"
 // CHECK-NO-MIX-GEN-USE: '{{[a-z=-]*}}' not allowed with '{{[a-z=-]*}}'
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -731,8 +731,9 @@
   Result.append(UID.begin(), UID.end());
 }
 
-static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
-   const InputInfo &Output, const ArgList 
&Args,
+static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
+   const Driver &D, const InputInfo &Output,
+   const ArgList &Args,
ArgStringList &CmdArgs) {
 
   auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
@@ -783,6 +784,11 @@
ProfileGenerateArg->getValue()));
 // The default is to use Clang Instrumentation.
 CmdArgs.push_back("-fprofile-instrument=clang");
+if (TC.getTriple().isOSWindows()) {
+  // Add dependent lib for clang_rt.profile
+  CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
+   TC.getCompilerRT(Args, "profile")));
+}
   }
 
   Arg *PGOGenArg = nullptr;
@@ -4176,7 +4182,7 @@
   // sampling, overhead of call arc collection is way too high and there's no
   // way to collect the output.
   if (!Triple.isNVPTX())
-addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
+addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
 
   if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
 ABICompatArg->render(Args, CmdArgs);


Index: clang/test/Driver/cl-options.c
===
--- clang/test/Driver/cl-options.c
+++ clang/test/Driver/cl-options.c
@@ -66,7 +66,7 @@
 // RUN: %clang_cl -### /FA -fprofile-instr-generate=/tmp/somefile.profraw -- %s 2>&1 | FileCheck -check-prefix=CHECK-PROFILE-GENERATE-FILE %s
 // RUN: %clang_cl -### /FA -fprofile-instr-generate -fprofile-instr-use -- %s 2>&1 | FileCheck -check-prefix=CHECK-NO-MIX-GEN-USE %s
 // RUN: %clang_cl -### /FA -fprofile-instr-generate -fprofile-instr-use=file -- %s 2>&1 | FileCheck -check-prefix=CHECK-NO-MIX-GEN-USE %s
-// CHECK-PROFILE-GENERATE: "-fprofile-instrument=clang"
+// CHECK-PROFILE-GENERATE: "-fprofile-instrument=clang" "--dependent-lib={{[^"]*}}clang_rt.profile-{{[^"]*}}.lib"
 // CHECK-PROFILE-GENERATE-FILE: "-fprofile-instrument-path=/tmp/somefile.profraw"
 // CHECK-NO-MIX-GEN-USE: '{{[a-z=-]*}}' not allowed with '{{[a-z=-]*}}'
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -731,8 +731,9 @@
   Result.append(UID.begin(), UID.end());
 }
 
-static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
-   const InputInfo &Output, const ArgList &Args,
+static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
+  

[PATCH] D61689: Change -gz and -Wa,--compress-debug-sections to use gABI compression (SHF_COMPRESSED)

2019-05-09 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd added a comment.

I don't really have a problem with this change.  But, if we make this change, 
please include a change to the release notes *now*.  This is something which 
may catch users off guard and confuse them and require them to go looking for 
what happened.

As an aside, I think that it is high time that we consider the 
`-mlinker-version=` option coming over to Linux (and Windows?).  macOS has had 
this option for a long time, and it allows you to properly control the linker 
invocation because you know what version of the linker you are using (with a 
default version that is determined at runtime).


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61689/new/

https://reviews.llvm.org/D61689



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


[PATCH] D61743: New clang option -MD-filter=prefix to filter files from make dependencies

2019-05-09 Thread Melanie Blower via Phabricator via cfe-commits
mibintc created this revision.
mibintc added reviewers: clang-c, fedor.sergeev.
mibintc added a project: clang.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Intel is developing an offload compiler based on clang (that will eventually be 
contributed to open source). In the course of the compilation many temporary .h 
files are generated in /tmp.  We'd like to have a way of eliding these 
dependencies from the -MD output. This new option -MD-filter=prefixstring is 
proposed.


Repository:
  rL LLVM

https://reviews.llvm.org/D61743

Files:
  docs/ClangCommandLineReference.rst
  include/clang/Driver/Options.td
  include/clang/Frontend/DependencyOutputOptions.h
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp
  lib/Frontend/DependencyFile.cpp
  test/Frontend/dependency-gen.c

Index: test/Frontend/dependency-gen.c
===
--- test/Frontend/dependency-gen.c
+++ test/Frontend/dependency-gen.c
@@ -5,6 +5,10 @@
 // RUN: cd %t.dir
 // RUN: %clang -MD -MF - %s -fsyntax-only -I a/b | FileCheck -check-prefix=CHECK-ONE %s
 // CHECK-ONE: {{ }}a{{[/\\]}}b{{[/\\]}}x.h
+// RUN: %clang -MD -MF - %s -fsyntax-only -I a/b -MD-filter="a/b" | FileCheck -check-prefix=CHECK-FILTER %s
+// CHECK-FILTER-NOT: {{ }}a{{[/\\]}}b{{[/\\]}}x.h
+// RUN: %clang -MD -MF - %s -fsyntax-only -I a/b -MD-filter="a/b" | FileCheck -check-prefix=CHECK-WS %s
+// CHECK-WS: {{^ *$}}
 
 // PR8974 (-include flag)
 // RUN: %clang -MD -MF - %s -fsyntax-only -include a/b/x.h -DINCLUDE_FLAG_TEST | FileCheck -check-prefix=CHECK-TWO %s
Index: lib/Frontend/DependencyFile.cpp
===
--- lib/Frontend/DependencyFile.cpp
+++ lib/Frontend/DependencyFile.cpp
@@ -154,6 +154,7 @@
   llvm::StringSet<> FilesSet;
   const Preprocessor *PP;
   std::string OutputFile;
+  std::string DependencyFilter;
   std::vector Targets;
   bool IncludeSystemHeaders;
   bool PhonyTarget;
@@ -170,7 +171,8 @@
 
 public:
   DFGImpl(const Preprocessor *_PP, const DependencyOutputOptions &Opts)
-: PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
+: PP(_PP), OutputFile(Opts.OutputFile),
+  DependencyFilter(Opts.DependencyFilter), Targets(Opts.Targets),
   IncludeSystemHeaders(Opts.IncludeSystemHeaders),
   PhonyTarget(Opts.UsePhonyTargets),
   AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
@@ -273,6 +275,11 @@
   if (isSpecialFilename(Filename))
 return false;
 
+  if (DependencyFilter.size() &&
+  strncmp(Filename, DependencyFilter.c_str(), DependencyFilter.size()) == 0)
+// Remove dependencies that are prefixed by the Filter string.
+return false;
+
   if (IncludeSystemHeaders)
 return true;
 
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -1340,6 +1340,7 @@
 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
   ArgList &Args) {
   Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
+  Opts.DependencyFilter = Args.getLastArgValue(OPT_dependency_filter);
   Opts.Targets = Args.getAllArgValues(OPT_MT);
   Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
   Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -1118,6 +1118,11 @@
   CmdArgs.push_back("-module-file-deps");
   }
 
+  if (Arg *MD_Filter = Args.getLastArg(options::OPT_MD_filter)) {
+CmdArgs.push_back("-dependency-filter");
+CmdArgs.push_back(MD_Filter->getValue());
+  }
+
   if (Args.hasArg(options::OPT_MG)) {
 if (!A || A->getOption().matches(options::OPT_MD) ||
 A->getOption().matches(options::OPT_MMD))
Index: include/clang/Frontend/DependencyOutputOptions.h
===
--- include/clang/Frontend/DependencyOutputOptions.h
+++ include/clang/Frontend/DependencyOutputOptions.h
@@ -41,6 +41,10 @@
   /// The file to write dependency output to.
   std::string OutputFile;
 
+  /// Dependency output which is prefixed with this string is filtered
+  /// from the dependency output.
+  std::string DependencyFilter;
+
   /// The file to write header include output to. This is orthogonal to
   /// ShowHeaderIncludes (-H) and will include headers mentioned in the
   /// predefines buffer. If the output file is "-", output will be sent to
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -368,6 +368,8 @@
 HelpText<"Like -MD, but also implies -E and writes to stdout by default">;
 def MM : Flag<["-"], "MM">,

[clang-tools-extra] r360358 - check_clang_tidy.py now passes `-format-style=none` to clang_tidy

2019-05-09 Thread Dmitri Gribenko via cfe-commits
Author: gribozavr
Date: Thu May  9 10:08:10 2019
New Revision: 360358

URL: http://llvm.org/viewvc/llvm-project?rev=360358&view=rev
Log:
check_clang_tidy.py now passes `-format-style=none` to clang_tidy

Summary:
If the test does not specify a formatting style, force "none"; otherwise
autodetection logic can discover a ".clang-tidy" file that is not
related to the test.

Reviewers: alexfh

Subscribers: cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py

Modified: clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py?rev=360358&r1=360357&r2=360358&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py (original)
+++ clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py Thu May  9 
10:08:10 2019
@@ -69,20 +69,32 @@ def main():
   temp_file_name = temp_file_name + extension
 
   clang_tidy_extra_args = extra_args
-  if len(clang_tidy_extra_args) == 0:
-clang_tidy_extra_args = ['--']
+  clang_extra_args = []
+  if '--' in extra_args:
+i = clang_tidy_extra_args.index('--')
+clang_extra_args = clang_tidy_extra_args[i + 1:]
+clang_tidy_extra_args = clang_tidy_extra_args[:i]
+
+  # If the test does not specify a formatting style, force "none"; otherwise
+  # autodetection logic can discover a ".clang-tidy" file that is not related 
to
+  # the test.
+  if not any(
+  [arg.startswith('-format-style=') for arg in clang_tidy_extra_args]):
+clang_tidy_extra_args.append('-format-style=none')
+
+  if len(clang_extra_args) == 0:
 if extension in ['.cpp', '.hpp', '.mm']:
-  clang_tidy_extra_args.append('--std=c++11')
+  clang_extra_args.append('--std=c++11')
 if extension in ['.m', '.mm']:
-  clang_tidy_extra_args.extend(
+  clang_extra_args.extend(
   ['-fobjc-abi-version=2', '-fobjc-arc'])
 
   # Tests should not rely on STL being available, and instead provide mock
   # implementations of relevant APIs.
-  clang_tidy_extra_args.append('-nostdinc++')
+  clang_extra_args.append('-nostdinc++')
 
   if resource_dir is not None:
-clang_tidy_extra_args.append('-resource-dir=%s' % resource_dir)
+clang_extra_args.append('-resource-dir=%s' % resource_dir)
 
   with open(input_file_name, 'r') as input_file:
 input_text = input_file.read()
@@ -138,7 +150,7 @@ def main():
   write_file(original_file_name, cleaned_test)
 
   args = ['clang-tidy', temp_file_name, '-fix', '--checks=-*,' + check_name] + 
\
-clang_tidy_extra_args
+  clang_tidy_extra_args + ['--'] + clang_extra_args
   if expect_clang_tidy_error:
 args.insert(0, 'not')
   print('Running ' + repr(args) + '...')


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


[PATCH] D61689: Change -gz and -Wa,--compress-debug-sections to use gABI compression (SHF_COMPRESSED)

2019-05-09 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd accepted this revision.
compnerd added a comment.
This revision is now accepted and ready to land.

(Accepting with the condition that you will update the release notes before 
committing)


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61689/new/

https://reviews.llvm.org/D61689



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


[PATCH] D61739: check_clang_tidy.py now passes `-format-style=none` to clang_tidy

2019-05-09 Thread Dmitri Gribenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL360358: check_clang_tidy.py now passes `-format-style=none` 
to clang_tidy (authored by gribozavr, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D61739?vs=198845&id=198865#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61739/new/

https://reviews.llvm.org/D61739

Files:
  clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py


Index: clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py
@@ -69,20 +69,32 @@
   temp_file_name = temp_file_name + extension
 
   clang_tidy_extra_args = extra_args
-  if len(clang_tidy_extra_args) == 0:
-clang_tidy_extra_args = ['--']
+  clang_extra_args = []
+  if '--' in extra_args:
+i = clang_tidy_extra_args.index('--')
+clang_extra_args = clang_tidy_extra_args[i + 1:]
+clang_tidy_extra_args = clang_tidy_extra_args[:i]
+
+  # If the test does not specify a formatting style, force "none"; otherwise
+  # autodetection logic can discover a ".clang-tidy" file that is not related 
to
+  # the test.
+  if not any(
+  [arg.startswith('-format-style=') for arg in clang_tidy_extra_args]):
+clang_tidy_extra_args.append('-format-style=none')
+
+  if len(clang_extra_args) == 0:
 if extension in ['.cpp', '.hpp', '.mm']:
-  clang_tidy_extra_args.append('--std=c++11')
+  clang_extra_args.append('--std=c++11')
 if extension in ['.m', '.mm']:
-  clang_tidy_extra_args.extend(
+  clang_extra_args.extend(
   ['-fobjc-abi-version=2', '-fobjc-arc'])
 
   # Tests should not rely on STL being available, and instead provide mock
   # implementations of relevant APIs.
-  clang_tidy_extra_args.append('-nostdinc++')
+  clang_extra_args.append('-nostdinc++')
 
   if resource_dir is not None:
-clang_tidy_extra_args.append('-resource-dir=%s' % resource_dir)
+clang_extra_args.append('-resource-dir=%s' % resource_dir)
 
   with open(input_file_name, 'r') as input_file:
 input_text = input_file.read()
@@ -138,7 +150,7 @@
   write_file(original_file_name, cleaned_test)
 
   args = ['clang-tidy', temp_file_name, '-fix', '--checks=-*,' + check_name] + 
\
-clang_tidy_extra_args
+  clang_tidy_extra_args + ['--'] + clang_extra_args
   if expect_clang_tidy_error:
 args.insert(0, 'not')
   print('Running ' + repr(args) + '...')


Index: clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py
@@ -69,20 +69,32 @@
   temp_file_name = temp_file_name + extension
 
   clang_tidy_extra_args = extra_args
-  if len(clang_tidy_extra_args) == 0:
-clang_tidy_extra_args = ['--']
+  clang_extra_args = []
+  if '--' in extra_args:
+i = clang_tidy_extra_args.index('--')
+clang_extra_args = clang_tidy_extra_args[i + 1:]
+clang_tidy_extra_args = clang_tidy_extra_args[:i]
+
+  # If the test does not specify a formatting style, force "none"; otherwise
+  # autodetection logic can discover a ".clang-tidy" file that is not related to
+  # the test.
+  if not any(
+  [arg.startswith('-format-style=') for arg in clang_tidy_extra_args]):
+clang_tidy_extra_args.append('-format-style=none')
+
+  if len(clang_extra_args) == 0:
 if extension in ['.cpp', '.hpp', '.mm']:
-  clang_tidy_extra_args.append('--std=c++11')
+  clang_extra_args.append('--std=c++11')
 if extension in ['.m', '.mm']:
-  clang_tidy_extra_args.extend(
+  clang_extra_args.extend(
   ['-fobjc-abi-version=2', '-fobjc-arc'])
 
   # Tests should not rely on STL being available, and instead provide mock
   # implementations of relevant APIs.
-  clang_tidy_extra_args.append('-nostdinc++')
+  clang_extra_args.append('-nostdinc++')
 
   if resource_dir is not None:
-clang_tidy_extra_args.append('-resource-dir=%s' % resource_dir)
+clang_extra_args.append('-resource-dir=%s' % resource_dir)
 
   with open(input_file_name, 'r') as input_file:
 input_text = input_file.read()
@@ -138,7 +150,7 @@
   write_file(original_file_name, cleaned_test)
 
   args = ['clang-tidy', temp_file_name, '-fix', '--checks=-*,' + check_name] + \
-clang_tidy_extra_args
+  clang_tidy_extra_args + ['--'] + clang_extra_args
   if expect_clang_tidy_error:
 args.insert(0, 'not')
   print('Running ' + repr(args) + '...')
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 198867.
ilya-biryukov marked 5 inline comments as done.
ilya-biryukov added a comment.

- Check invariants on FileRange construction, unify access to all fields


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59887/new/

https://reviews.llvm.org/D59887

Files:
  clang/include/clang/Tooling/Syntax/Tokens.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/Syntax/CMakeLists.txt
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/Syntax/CMakeLists.txt
  clang/unittests/Tooling/Syntax/TokensTest.cpp

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -0,0 +1,622 @@
+//===- TokensTest.cpp -===//
+//
+// 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 "clang/Tooling/Syntax/Tokens.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Expr.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/FileSystemOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.def"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/Utils.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/raw_os_ostream.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock-more-matchers.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang;
+using namespace clang::syntax;
+
+using llvm::ValueIs;
+using ::testing::AllOf;
+using ::testing::Contains;
+using ::testing::ElementsAre;
+using ::testing::Matcher;
+using ::testing::Not;
+using ::testing::StartsWith;
+
+namespace {
+// Checks the passed ArrayRef has the same begin() and end() iterators as the
+// argument.
+MATCHER_P(SameRange, A, "") {
+  return A.begin() == arg.begin() && A.end() == arg.end();
+}
+// Matchers for syntax::Token.
+MATCHER_P(Kind, K, "") { return arg.kind() == K; }
+MATCHER_P2(HasText, Text, SourceMgr, "") {
+  return arg.text(*SourceMgr) == Text;
+}
+/// Checks the start and end location of a token are equal to SourceRng.
+MATCHER_P(RangeIs, SourceRng, "") {
+  return arg.location() == SourceRng.first &&
+ arg.endLocation() == SourceRng.second;
+}
+
+class TokenCollectorTest : public ::testing::Test {
+public:
+  /// Run the clang frontend, collect the preprocessed tokens from the frontend
+  /// invocation and store them in this->Buffer.
+  /// This also clears SourceManager before running the compiler.
+  void recordTokens(llvm::StringRef Code) {
+class RecordTokens : public ASTFrontendAction {
+public:
+  explicit RecordTokens(TokenBuffer &Result) : Result(Result) {}
+
+  bool BeginSourceFileAction(CompilerInstance &CI) override {
+assert(!Collector && "expected only a single call to BeginSourceFile");
+Collector.emplace(CI.getPreprocessor());
+return true;
+  }
+  void EndSourceFileAction() override {
+assert(Collector && "BeginSourceFileAction was never called");
+Result = std::move(*Collector).consume();
+  }
+
+  std::unique_ptr
+  CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
+return llvm::make_unique();
+  }
+
+private:
+  TokenBuffer &Result;
+  llvm::Optional Collector;
+};
+
+constexpr const char *FileName = "./input.cpp";
+FS->addFile(FileName, time_t(), llvm::MemoryBuffer::getMemBufferCopy(""));
+// Prepare to run a compiler.
+std::vector Args = {"tok-test", "-std=c++03", "-fsyntax-only",
+  FileName};
+auto CI = createInvocationFromCommandLine(Args, Diags, FS);
+assert(CI);
+CI->getFrontendOpts().

[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added inline comments.



Comment at: clang/include/clang/Tooling/Syntax/Tokens.h:62
+  SourceLocation location() const { return Location; }
+  SourceLocation endLocation() const {
+return Location.getLocWithOffset(Length);

sammccall wrote:
> ilya-biryukov wrote:
> > sammccall wrote:
> > > sadly, this would need documentation - it's the one-past-the-end 
> > > location, not the last character in the token, not the location of the 
> > > "next" token, or the location of the "next" character...
> > > 
> > > I do wonder whether this is actually the right function to expose...
> > >  Do you ever care about end but not start? (The reverse seems likelier). 
> > > Having two independent source location accessors obscures the invariant 
> > > that they have the same file ID.
> > > 
> > > I think exposing a `FileRange` accessor instead might be better, but for 
> > > now you could also make callers use 
> > > `Tok.location().getLocWithOffset(Tok.length())` until we know it's the 
> > > right pattern to encourage
> > Added a comment. With the comment and an implementation being inline and 
> > trivial, I don't think anyone would have trouble understanding what this 
> > method does.
> (this is ok. I do think a FileRange accessor would make client code more 
> readable/less error-prone. Let's discuss offline)
I've added a corresponding accessor (and a version of it that accepts a range 
of tokens) to D61681.
I'd keep it off this patch for now, will refactor in a follow-up.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59887/new/

https://reviews.llvm.org/D59887



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


[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked 3 inline comments as done.
ilya-biryukov added inline comments.



Comment at: clang/include/clang/Tooling/Syntax/Tokens.h:78
+  /// For debugging purposes.
+  std::string str() const;
+

sammccall wrote:
> ilya-biryukov wrote:
> > sammccall wrote:
> > > (do we need to have two names for this version?)
> > You mean to have distinct names for two different overloads?
> > I wouldn't do it, they both have fairly similar outputs, could add a small 
> > comment that the one with SourceManager should probably be preferred if you 
> > have one.
> > 
> No sorry, I meant do we need both str() and operator<<
one can type `str()` in debugger, `operator <<` is for convenience when one is 
already using streams.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59887/new/

https://reviews.llvm.org/D59887



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


[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 198868.
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

- Use bsearch instead of upper_bound


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59887/new/

https://reviews.llvm.org/D59887

Files:
  clang/include/clang/Tooling/Syntax/Tokens.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/Syntax/CMakeLists.txt
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/Syntax/CMakeLists.txt
  clang/unittests/Tooling/Syntax/TokensTest.cpp

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -0,0 +1,622 @@
+//===- TokensTest.cpp -===//
+//
+// 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 "clang/Tooling/Syntax/Tokens.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Expr.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/FileSystemOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.def"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/Utils.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/raw_os_ostream.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock-more-matchers.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang;
+using namespace clang::syntax;
+
+using llvm::ValueIs;
+using ::testing::AllOf;
+using ::testing::Contains;
+using ::testing::ElementsAre;
+using ::testing::Matcher;
+using ::testing::Not;
+using ::testing::StartsWith;
+
+namespace {
+// Checks the passed ArrayRef has the same begin() and end() iterators as the
+// argument.
+MATCHER_P(SameRange, A, "") {
+  return A.begin() == arg.begin() && A.end() == arg.end();
+}
+// Matchers for syntax::Token.
+MATCHER_P(Kind, K, "") { return arg.kind() == K; }
+MATCHER_P2(HasText, Text, SourceMgr, "") {
+  return arg.text(*SourceMgr) == Text;
+}
+/// Checks the start and end location of a token are equal to SourceRng.
+MATCHER_P(RangeIs, SourceRng, "") {
+  return arg.location() == SourceRng.first &&
+ arg.endLocation() == SourceRng.second;
+}
+
+class TokenCollectorTest : public ::testing::Test {
+public:
+  /// Run the clang frontend, collect the preprocessed tokens from the frontend
+  /// invocation and store them in this->Buffer.
+  /// This also clears SourceManager before running the compiler.
+  void recordTokens(llvm::StringRef Code) {
+class RecordTokens : public ASTFrontendAction {
+public:
+  explicit RecordTokens(TokenBuffer &Result) : Result(Result) {}
+
+  bool BeginSourceFileAction(CompilerInstance &CI) override {
+assert(!Collector && "expected only a single call to BeginSourceFile");
+Collector.emplace(CI.getPreprocessor());
+return true;
+  }
+  void EndSourceFileAction() override {
+assert(Collector && "BeginSourceFileAction was never called");
+Result = std::move(*Collector).consume();
+  }
+
+  std::unique_ptr
+  CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
+return llvm::make_unique();
+  }
+
+private:
+  TokenBuffer &Result;
+  llvm::Optional Collector;
+};
+
+constexpr const char *FileName = "./input.cpp";
+FS->addFile(FileName, time_t(), llvm::MemoryBuffer::getMemBufferCopy(""));
+// Prepare to run a compiler.
+std::vector Args = {"tok-test", "-std=c++03", "-fsyntax-only",
+  FileName};
+auto CI = createInvocationFromCommandLine(Args, Diags, FS);
+assert(CI);
+CI->getFrontendOpts().DisableFree = false;
+CI->getPre

[PATCH] D50993: [clangd] Increase stack size of the new threads on macOS

2019-05-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

I'd still put it into LLVM to avoid platform-specific code in clangd. 
Maybe `std::abort()` in the added `...Async` function if threads are disabled? 
It's a bit unusual, but would allow keeping this function where it belongs.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D50993/new/

https://reviews.llvm.org/D50993



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


r360359 - [CodeGen][ObjC] Remove the leading `l_` from ObjC symbols and make

2019-05-09 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Thu May  9 10:43:52 2019
New Revision: 360359

URL: http://llvm.org/viewvc/llvm-project?rev=360359&view=rev
Log:
[CodeGen][ObjC] Remove the leading `l_` from ObjC symbols and make
private symbols in the __DATA segment internal.

This prevents the linker from removing the symbol names. Keeping the
symbols visible enables tools to collect various information about the
symbols, for example, tools that discover whether or not a symbol gets
dirtied.

rdar://problem/48887111

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

Modified:
cfe/trunk/lib/CodeGen/CGObjCMac.cpp
cfe/trunk/test/CodeGenObjC/arc.m
cfe/trunk/test/CodeGenObjC/boxing.m
cfe/trunk/test/CodeGenObjC/exceptions-asm-attribute.m
cfe/trunk/test/CodeGenObjC/externally-initialized-selectors.m
cfe/trunk/test/CodeGenObjC/forward-protocol-metadata-symbols.m
cfe/trunk/test/CodeGenObjC/instance-method-metadata.m
cfe/trunk/test/CodeGenObjC/interface-layout-64.m
cfe/trunk/test/CodeGenObjC/metadata-class-properties.m
cfe/trunk/test/CodeGenObjC/metadata-symbols-32.m
cfe/trunk/test/CodeGenObjC/metadata-symbols-64.m
cfe/trunk/test/CodeGenObjC/metadata_symbols.m
cfe/trunk/test/CodeGenObjC/mrc-weak.m
cfe/trunk/test/CodeGenObjC/non-lazy-classes.m
cfe/trunk/test/CodeGenObjC/private-extern-selector-reference.m
cfe/trunk/test/CodeGenObjC/property-category-impl.m
cfe/trunk/test/CodeGenObjC/property-list-in-class.m
cfe/trunk/test/CodeGenObjC/property-list-in-extension.m
cfe/trunk/test/CodeGenObjC/protocol-comdat.m
cfe/trunk/test/CodeGenObjC/protocols.m
cfe/trunk/test/CodeGenObjC/section-name.m
cfe/trunk/test/CodeGenObjC/sections.m
cfe/trunk/test/CodeGenObjCXX/externally-initialized-selectors.mm
cfe/trunk/test/CodeGenObjCXX/mrc-weak.mm

Modified: cfe/trunk/lib/CodeGen/CGObjCMac.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGObjCMac.cpp?rev=360359&r1=360358&r2=360359&view=diff
==
--- cfe/trunk/lib/CodeGen/CGObjCMac.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGObjCMac.cpp Thu May  9 10:43:52 2019
@@ -1809,6 +1809,28 @@ static bool hasObjCExceptionAttribute(AS
   return false;
 }
 
+static llvm::GlobalValue::LinkageTypes
+getLinkageTypeForObjCMetadata(CodeGenModule &CGM, StringRef Section) {
+  if (CGM.getTriple().isOSBinFormatMachO() &&
+  (Section.empty() || Section.startswith("__DATA")))
+return llvm::GlobalValue::InternalLinkage;
+  return llvm::GlobalValue::PrivateLinkage;
+}
+
+/// A helper function to create an internal or private global variable.
+static llvm::GlobalVariable *
+finishAndCreateGlobal(ConstantInitBuilder::StructBuilder &Builder,
+ const llvm::Twine &Name, CodeGenModule &CGM) {
+  std::string SectionName;
+  if (CGM.getTriple().isOSBinFormatMachO())
+SectionName = "__DATA, __objc_const";
+  auto *GV = Builder.finishAndCreateGlobal(
+  Name, CGM.getPointerAlign(), /*constant*/ false,
+  getLinkageTypeForObjCMetadata(CGM, SectionName));
+  GV->setSection(SectionName);
+  return GV;
+}
+
 /* *** CGObjCMac Public Interface *** */
 
 CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
@@ -3105,7 +3127,7 @@ CGObjCMac::EmitProtocolExtension(const O
   values.add(classProperties);
 
   // No special section, but goes in llvm.used
-  return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(), values,
+  return CreateMetadataVar("_OBJC_PROTOCOLEXT_" + PD->getName(), values,
StringRef(), CGM.getPointerAlign(), true);
 }
 
@@ -3338,9 +3360,9 @@ void CGObjCMac::GenerateCategory(const O
 
   // If there is no category @interface then there can be no properties.
   if (Category) {
-Values.add(EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
+Values.add(EmitPropertyList("_OBJC_$_PROP_LIST_" + ExtName.str(),
 OCD, Category, ObjCTypes, false));
-Values.add(EmitPropertyList("\01l_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
+Values.add(EmitPropertyList("_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),
 OCD, Category, ObjCTypes, true));
   } else {
 Values.addNullPointer(ObjCTypes.PropertyListPtrTy);
@@ -3686,8 +3708,8 @@ CGObjCMac::EmitClassExtension(const ObjC
 
   // Properties.
   llvm::Constant *propertyList =
-EmitPropertyList((isMetaclass ? Twine("\01l_OBJC_$_CLASS_PROP_LIST_")
-  : Twine("\01l_OBJC_$_PROP_LIST_"))
+EmitPropertyList((isMetaclass ? Twine("_OBJC_$_CLASS_PROP_LIST_")
+  : Twine("_OBJC_$_PROP_LIST_"))
 + ID->getName(),
  ID, ID->getClassInterface(), ObjCTypes, isMetaclass);
 
@@ -3935,9 +3957,10 @@ llvm::GlobalVariable *CGObjCCommonMac::C
  StringRef Section,
  

[PATCH] D61454: [CodeGen][ObjC] Remove the leading 'l_' from ObjC symbols and make private symbols in the __DATA segment internal.

2019-05-09 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC360359: [CodeGen][ObjC] Remove the leading `l_` from ObjC 
symbols and make (authored by ahatanak, committed by ).

Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61454/new/

https://reviews.llvm.org/D61454

Files:
  lib/CodeGen/CGObjCMac.cpp
  test/CodeGenObjC/arc.m
  test/CodeGenObjC/boxing.m
  test/CodeGenObjC/exceptions-asm-attribute.m
  test/CodeGenObjC/externally-initialized-selectors.m
  test/CodeGenObjC/forward-protocol-metadata-symbols.m
  test/CodeGenObjC/instance-method-metadata.m
  test/CodeGenObjC/interface-layout-64.m
  test/CodeGenObjC/metadata-class-properties.m
  test/CodeGenObjC/metadata-symbols-32.m
  test/CodeGenObjC/metadata-symbols-64.m
  test/CodeGenObjC/metadata_symbols.m
  test/CodeGenObjC/mrc-weak.m
  test/CodeGenObjC/non-lazy-classes.m
  test/CodeGenObjC/private-extern-selector-reference.m
  test/CodeGenObjC/property-category-impl.m
  test/CodeGenObjC/property-list-in-class.m
  test/CodeGenObjC/property-list-in-extension.m
  test/CodeGenObjC/protocol-comdat.m
  test/CodeGenObjC/protocols.m
  test/CodeGenObjC/section-name.m
  test/CodeGenObjC/sections.m
  test/CodeGenObjCXX/externally-initialized-selectors.mm
  test/CodeGenObjCXX/mrc-weak.mm

Index: test/CodeGenObjC/externally-initialized-selectors.m
===
--- test/CodeGenObjC/externally-initialized-selectors.m
+++ test/CodeGenObjC/externally-initialized-selectors.m
@@ -1,7 +1,8 @@
-// RUN: %clang_cc1 -fobjc-runtime=macosx-fragile-10.5 -o - -emit-llvm %s | FileCheck %s
-// RUN: %clang_cc1 -o - -emit-llvm %s | FileCheck %s
+// RUN: %clang_cc1 -fobjc-runtime=macosx-fragile-10.5 -o - -emit-llvm %s | FileCheck -check-prefix=FRAGILE %s
+// RUN: %clang_cc1 -o - -emit-llvm %s | FileCheck -check-prefix=NONFRAGILE %s
 
-// CHECK: @OBJC_SELECTOR_REFERENCES_ = private externally_initialized global
+// NONFRAGILE: @OBJC_SELECTOR_REFERENCES_ = internal externally_initialized global
+// FRAGILE: @OBJC_SELECTOR_REFERENCES_ = private externally_initialized global
 
 void test(id x) {
   [x doSomething];
Index: test/CodeGenObjC/instance-method-metadata.m
===
--- test/CodeGenObjC/instance-method-metadata.m
+++ test/CodeGenObjC/instance-method-metadata.m
@@ -27,7 +27,7 @@
 @synthesize prop;
 @end
 
-// CHECK: l_OBJC_$_INSTANCE_METHODS_Bar:
+// CHECK: _OBJC_$_INSTANCE_METHODS_Bar:
 // CHECK-NEXT:.long   24
 // CHECK-NEXT:.long   2
 // CHECK-NEXT:.quad   L_OBJC_METH_VAR_NAME_
Index: test/CodeGenObjC/protocol-comdat.m
===
--- test/CodeGenObjC/protocol-comdat.m
+++ test/CodeGenObjC/protocol-comdat.m
@@ -20,8 +20,8 @@
 
 // CHECK: $"_OBJC_PROTOCOL_$_P" = comdat any
 // CHECK: $"_OBJC_LABEL_PROTOCOL_$_P" = comdat any
-// CHECK: $"\01l_OBJC_PROTOCOL_REFERENCE_$_Q" = comdat any
-// CHECK: $"\01l_OBJC_PROTOCOL_REFERENCE_$_R" = comdat any
+// CHECK: $"_OBJC_PROTOCOL_REFERENCE_$_Q" = comdat any
+// CHECK: $"_OBJC_PROTOCOL_REFERENCE_$_R" = comdat any
 
 // CHECK: @"_OBJC_PROTOCOL_$_P" = {{.*}}, comdat
 // CHECK: @"_OBJC_LABEL_PROTOCOL_$_P" = {{.*}}, comdat
Index: test/CodeGenObjC/non-lazy-classes.m
===
--- test/CodeGenObjC/non-lazy-classes.m
+++ test/CodeGenObjC/non-lazy-classes.m
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -Wno-objc-root-class -emit-llvm -o - %s | FileCheck %s
 
-// CHECK: @"OBJC_LABEL_NONLAZY_CLASS_$" = private global [3 x {{.*}}]{{.*}}@"OBJC_CLASS_$_A"{{.*}},{{.*}}@"OBJC_CLASS_$_D"{{.*}},{{.*}}"OBJC_CLASS_$_E"{{.*}} section "__DATA,__objc_nlclslist,regular,no_dead_strip", align 8
-// CHECK: @"OBJC_LABEL_NONLAZY_CATEGORY_$" = private global [2 x {{.*}}] {{.*}}@"\01l_OBJC_$_CATEGORY_A_$_Cat"{{.*}},{{.*}}@"\01l_OBJC_$_CATEGORY_E_$_MyCat"{{.*}}, section "__DATA,__objc_nlcatlist,regular,no_dead_strip", align 8
+// CHECK: @"OBJC_LABEL_NONLAZY_CLASS_$" = internal global [3 x {{.*}}]{{.*}}@"OBJC_CLASS_$_A"{{.*}},{{.*}}@"OBJC_CLASS_$_D"{{.*}},{{.*}}"OBJC_CLASS_$_E"{{.*}} section "__DATA,__objc_nlclslist,regular,no_dead_strip", align 8
+// CHECK: @"OBJC_LABEL_NONLAZY_CATEGORY_$" = internal global [2 x {{.*}}] {{.*}}@"_OBJC_$_CATEGORY_A_$_Cat"{{.*}},{{.*}}@"_OBJC_$_CATEGORY_E_$_MyCat"{{.*}}, section "__DATA,__objc_nlcatlist,regular,no_dead_strip", align 8
 
 @interface A @end
 @implementation A
Index: test/CodeGenObjC/metadata-symbols-64.m
===
--- test/CodeGenObjC/metadata-symbols-64.m
+++ test/CodeGenObjC/metadata-symbols-64.m
@@ -8,29 +8,29 @@
 // CHECK: @OBJC_CLASS_NAME_{{[0-9]*}} = private unnamed_addr constant {{.*}} section "__TEXT,__objc_classname,cstring_literals", align 1
 // CHECK: @OBJC_METH_VAR_NAME_{{[0-9]*}} = private unnamed_addr constant {{.*}} section "__TE

  1   2   >