[PATCH] D88281: [clangd] Use Decision Forest to score code compeltions.

2020-09-25 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 created this revision.
Herald added subscribers: cfe-commits, kadircet, arphaman, mgrang.
Herald added a project: clang.
usaxena95 requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.

By default clangd scores a code completion item using heuristic model.
Scoring can be done by Decision Forest by passing --ranking_model=df to
clangd.

TODO:

- Explain and backup the heuristic for combining NameMatch and DF prediction.
- Maybe add tests for sanity.
- Add end-to-end latency metrics.
- Add extra debug logging for the DF model.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88281

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/CodeComplete.h
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp

Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -26,6 +26,8 @@
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/Timer.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
@@ -33,6 +35,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -648,6 +651,76 @@
 Has("bar", CompletionItemKind::Function)));
 }
 
+/*
+TEST(CompletionTest, DO_NOT_SUBMIT_SpeedTestForReviewOnly) {
+
+  auto randFunction = []() {
+std::stringstream ss;
+ss << "void ";
+for (int i = 0; i < 10; ++i)
+  ss << char(rand() % 3 == 0 ? 'a' + rand() % 3 : 'A' + rand() % 3);
+ss << "();\n";
+return ss.str();
+  };
+  int Trials = 1;
+  std::vector IndexedResults;
+  IndexedResults.push_back(cls({"ns::ABCDabc"}));
+  IndexedResults.push_back(cls({"ns::abcABC"}));
+
+  std::string code = R"cpp(
+  namespace ns {
+void abc();
+)cpp";
+  for (int i = 0; i < 50; ++i)
+code += randFunction();
+  code += "namepsace ns2 {\n";
+  for (int i = 0; i < 50; ++i)
+code += randFunction();
+  code += "} //namespace ns2\n";
+  code += R"cpp(} // namespace ns
+  void f() { abc^ }
+   )cpp";
+  llvm::errs() << code << "\n";
+
+  CodeCompleteOptions Opts;
+  Opts.AllScopes = true;
+
+  llvm::Timer DF("DF", "Decision Forest");
+  llvm::Timer Heuristic("Heuristic", "Heuristic ranking.");
+
+  Opts.RankingModel = CodeCompleteOptions::DecisionForest;
+  DF.startTimer();
+  auto DFCompletions = completions(code, IndexedResults, Opts);
+  for (int i = 0; i < Trials; ++i)
+completions(code, IndexedResults, Opts);
+  DF.stopTimer();
+
+  Opts.RankingModel = CodeCompleteOptions::Heuristic;
+  Heuristic.startTimer();
+  auto HeuristicCompletions = completions(code, IndexedResults, Opts);
+  for (int i = 0; i < Trials; ++i)
+completions(code, IndexedResults, Opts);
+  Heuristic.stopTimer();
+
+  for (const auto &M : {DFCompletions, HeuristicCompletions}) {
+auto S = M.Completions;
+std::sort(S.begin(), S.end(),
+  [&](const CodeCompletion &a, const CodeCompletion &b) {
+return a.Score.Total > b.Score.Total ||
+   (a.Score.Total == b.Score.Total && a.Name < b.Name);
+  });
+int r = 0;
+for (const auto &C : S) {
+  llvm::errs() << r++ << ".\t" << C.Scope << " " << C.Name << " "
+   << C.Score.Total << " / " << C.Score.ExcludingName
+   << "\t\tNameMatch = "
+   << C.Score.Total / C.Score.ExcludingName << "\n";
+}
+llvm::errs() << "\n\n";
+  }
+  EXPECT_LT(int(DFCompletions.Completions.size()), 0LL);
+}
+*/
 TEST(CompletionTest, SemaIndexMerge) {
   auto Results = completions(
   R"cpp(
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -167,6 +167,18 @@
 Hidden,
 };
 
+opt RankingModel{
+"ranking-model",
+cat(Features),
+desc("Model to use to rank code-completion items"),
+values(clEnumValN(CodeCompleteOptions::Heuristic, "heuristic",
+  "Use hueristics to rank code completion items"),
+   clEnumValN(CodeCompleteOptions::DecisionForest, "df",
+  "Use Decision Forest model to rank completion items")),
+init(CodeCompleteOptions().RankingModel),
+Hidden,
+};
+
 // FIXME: also support "plain" style where signatures are always omitted.
 enum CompletionStyleFlag { Detailed, Bundled };
 opt CompletionStyle{
@@ -739,6 +751,7 @@
   CCOpts.EnableFunctionArgSnippets = EnableFunctionArgSnippets;
   CCOpts.AllScopes = AllScopesCompletion;
   CCOpts.RunParser = CodeCompletionParse;

[PATCH] D77229: [Analyzer][NFC] Avoid handling of LazyCompundVals in IteratorModeling

2020-09-25 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

@gamesh411, @whisperity, @martong and others, please suggest me new test cases 
if you think the current ones are not enough.


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

https://reviews.llvm.org/D77229

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


[PATCH] D80791: [AArch64] Generate .note.gnu.property based on module flags.

2020-09-25 Thread Momchil Velikov via Phabricator via cfe-commits
chill requested changes to this revision.
chill added a comment.
This revision now requires changes to proceed.

In D85649  I changed the module flags to be 
always present and have a zero/non-zero value. That's needed during LTO, if a 
flag is present in one module and absent in another,
no error is reported and the existing flags is used in the merged module, 
affecting the codegen for the module that did not initially have the flag.

tl;dr we need to check the value of the flags, not just their existence.


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

https://reviews.llvm.org/D80791

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


[PATCH] D87146: [analyzer] Implement shared semantics checks for XNU functions in PthreadLockChecker

2020-09-25 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

It would be nice if someone had time to look at this. Thanks.


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

https://reviews.llvm.org/D87146

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


[PATCH] D87528: Enable '#pragma STDC FENV_ACCESS' in frontend cf. D69272 - Work in Progress

2020-09-25 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added inline comments.



Comment at: clang/test/CodeGen/fp-floatcontrol-pragma.cpp:154
+  if (i<0)
+  return 1.0 + 2.0;
+  // Check that floating point constant folding doesn't occur if

In this particular case we know for sure that the result does not depend on 
rounding mode and no FP exceptions occurs, so it is safe to constfold the 
expression.

Expressions like `1.0 / 0.0` or `1.0F + 0x0.01p0F` indeed may require 
execution in runtime, depending on the required exception handling. I would 
propose to connect their const-evaluability with `FPExceptionMode` and set the 
latter to `strict` whenever `AllowFEnvAccess` is set to `true`. 



Comment at: clang/test/CodeGen/pragma-fenv_access.c:9
+// CHECK-LABEL: @func_01
+// CHECK: call float @llvm.experimental.constrained.fadd.f32(float {{.*}}, 
float {{.*}}, metadata !"round.tonearest", metadata !"fpexcept.strict")
+

Shall the rounding mode be `dynamic` rather than `tonearest`? If `#pragma STDC 
FENV_ACCESS ON` is specified, it means FP environment may be changed in 
arbitrary way and we cannot expect any particular rounding mode. Probably the 
environment was changed in the caller of `func_01`.


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

https://reviews.llvm.org/D87528

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


[PATCH] D88154: Initial support for vectorization using Libmvec (GLIBC vector math library).

2020-09-25 Thread Renato Golin via Phabricator via cfe-commits
rengolin added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1564
 def fveclib : Joined<["-"], "fveclib=">, Group, Flags<[CC1Option]>,
-HelpText<"Use the given vector functions library">, 
Values<"Accelerate,MASSV,SVML,none">;
+HelpText<"Use the given vector functions library">, 
Values<"Accelerate,LIBMVEC,MASSV,SVML,none">;
 def fno_lax_vector_conversions : Flag<["-"], "fno-lax-vector-conversions">, 
Group,

abique wrote:
> I think glibc always refer to the library as "libmvec" in lower case,  should 
> we do so here?
Yes, so clang can be a drop in replacement. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88154

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


[PATCH] D88265: Fix comma with half vectors.

2020-09-25 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:13936
   // arm64).
-  assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
- isVector(LHS.get()->getType(), Context.HalfTy) &&
- "both sides are half vectors or neither sides are");
+  assert(Opc == BO_Comma ||
+ isVector(RHS.get()->getType(), Context.HalfTy) ==

I think you need braces around the expression before `&& "..."`, otherwise some 
compilers may complain.



Comment at: clang/test/Sema/fp16vec-sema.c:29
   sv0 = hv0 >= hv1;
+  hv0, 1; // expected-warning 2 {{expression result unused}}
   sv0 = hv0 || hv1; // expected-error{{logical expression with vector types 
'half4' (vector of 4 '__fp16' values) and 'half4' is only supported in C++}}

nit: it might be slightly better to move it 2 lines further down, so all 
operators that assign the result are grouped together. Also, should we add `1, 
hv0` as well?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88265

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


[PATCH] D87972: [OldPM] Pass manager: run SROA after (simple) loop unrolling

2020-09-25 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

@MaskRay, @dmgreen & @sanwou01 thank you for running perf experiment!

I think all the results are consistent along the lines of "this sounds
generally reasonable (esp. given that new-pm does it already),
as usual results in ups&downs, but seems to be a (small) geomean win overall".

Does that sound reasonable?
What are the next suggested steps?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87972

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


[PATCH] D87972: [OldPM] Pass manager: run SROA after (simple) loop unrolling

2020-09-25 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

>> Does that sound reasonable?

Yes IMHO.

>> What are the next suggested steps?

It would be great to isolate and check the cases which regressed a bit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87972

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


[PATCH] D77062: [analyzer] Improve zero assumption in CStringChecke::assumeZero

2020-09-25 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Finally, I made my investigations and I come up with this code:

  void strcpy(char *, char *);
  void test(int *a, char ***b) {
*(unsigned char **)b = (unsigned char*)a; // #1
if (**b == nullptr) // will-crash
  ;
  }

So, this issue does not relate to CStringChecker. It will crash at 
`ExprEngineC.cpp:100`.
It seems that we have to make the choice of how to model type punning.
As you can see in the example, we overwrite the pointer value of `*b` to point 
to an //unsigned char// value //(#1)//.
The static type of `b` (//char***//) does not reflect the associated value's 
type which (//unsigned char**//) - //(note the number of indirections!)// in 
other words, an obvious type pun happened at that line.
If we get the value of `**b`, we get a //NonLoc// of type //unsigned char//.
The dump of `**b` confirms this: `reg_$4},0 S64b,unsigned char}>`, which is a `NonLoc` 
in deed.

IMO we should fix the root cause of this in the Core.
I think we should have a symbolic cast back to the static type before doing 
anything with the SVal (iff the BaseKind differs).
If we do this, we will get a Loc as expected - and neither this bug nor your 
original bug would fire.
WDYT @NoQ @martong @ASDenysPetrov @Szelethus?


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

https://reviews.llvm.org/D77062

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


[PATCH] D87146: [analyzer] Implement shared semantics checks for XNU functions in PthreadLockChecker

2020-09-25 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

In D87146#2294423 , @ASDenysPetrov 
wrote:

> It would be nice if someone had time to look at this. Thanks.

I am just looking, but I am not a `pthread` expert.


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

https://reviews.llvm.org/D87146

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


[PATCH] D77062: [analyzer] Improve zero assumption in CStringChecke::assumeZero

2020-09-25 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

And of course, repro:

  ./bin/clang -cc1 -analyze -setup-static-analyzer -analyzer-checker=core 
example.c
  
  Assertion `op == BO_Add' failed
  
   #0 0x7f5bea743904 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
/home/elnbbea/git/llvm-project/build/debug/../../llvm/lib/Support/Unix/Signals.inc:563:0
   #1 0x7f5bea7439a8 PrintStackTraceSignalHandler(void*) 
/home/elnbbea/git/llvm-project/build/debug/../../llvm/lib/Support/Unix/Signals.inc:627:0
   #2 0x7f5bea741759 llvm::sys::RunSignalHandlers() 
/home/elnbbea/git/llvm-project/build/debug/../../llvm/lib/Support/Signals.cpp:70:0
   #3 0x7f5bea743286 SignalHandler(int) 
/home/elnbbea/git/llvm-project/build/debug/../../llvm/lib/Support/Unix/Signals.inc:405:0
   #4 0x7f5be9b19fd0 (/lib/x86_64-linux-gnu/libc.so.6+0x3efd0)
   #5 0x7f5be9b19f47 raise 
/build/glibc-2ORdQG/glibc-2.27/signal/../sysdeps/unix/sysv/linux/raise.c:51:0
   #6 0x7f5be9b1b8b1 abort 
/build/glibc-2ORdQG/glibc-2.27/stdlib/abort.c:81:0
   #7 0x7f5be9b0b42a __assert_fail_base 
/build/glibc-2ORdQG/glibc-2.27/assert/assert.c:89:0
   #8 0x7f5be9b0b4a2 (/lib/x86_64-linux-gnu/libc.so.6+0x304a2)
   #9 0x7f5bdece2000 
clang::ento::SValBuilder::evalBinOp(llvm::IntrusiveRefCntPtr, clang::BinaryOperatorKind, clang::ento::SVal, clang::ento::SVal, 
clang::QualType) 
/home/elnbbea/git/llvm-project/build/debug/../../clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:439:0
  #10 0x7f5bdebd28ae 
clang::ento::ExprEngine::evalBinOp(llvm::IntrusiveRefCntPtr, clang::BinaryOperatorKind, clang::ento::SVal, clang::ento::SVal, 
clang::QualType) 
/home/elnbbea/git/llvm-project/build/debug/../../clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h:631:0
  #11 0x7f5bdebeb031 
clang::ento::ExprEngine::VisitBinaryOperator(clang::BinaryOperator const*, 
clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) 
/home/elnbbea/git/llvm-project/build/debug/../../clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp:100:0
  #12 0x7f5bdebc0aa5 clang::ento::ExprEngine::Visit(clang::Stmt const*, 
clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) 
/home/elnbbea/git/llvm-project/build/debug/../../clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:1573:0
  #13 0x7f5bdebbca10 clang::ento::ExprEngine::ProcessStmt(clang::Stmt 
const*, clang::ento::ExplodedNode*) 
/home/elnbbea/git/llvm-project/build/debug/../../clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:792:0


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

https://reviews.llvm.org/D77062

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


[PATCH] D77062: [analyzer] Improve zero assumption in CStringChecke::assumeZero

2020-09-25 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Beware, Phabricator ruins the visual experience of this nice analysis. E.g 
`//char ***//` is visible as an italic `char *`.

> I think we should have a symbolic cast back to the static type before doing 
> anything with the SVal (iff the BaseKind differs).
> If we do this, we will get a Loc as expected - and neither this bug nor your 
> original bug would fire.

I fully agree, I think this is the way.

Though, the fix probably will not be simple, because the issue itself always 
requires a 3x indirection. The code that is presented by @steakhal is the least 
minimal example to get this crash. The reason why we cannot have a crash with a 
`**` is a mystic at the moment.


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

https://reviews.llvm.org/D77062

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


[PATCH] D77062: [analyzer] Improve zero assumption in CStringChecke::assumeZero

2020-09-25 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D77062#2294516 , @martong wrote:

> Though, the fix probably will not be simple, because the issue itself always 
> requires a 3x indirection. The code that is presented by @steakhal is the 
> least minimal example to get this crash. The reason why we cannot have a 
> crash with a `**` is a mystic at the moment.

I think probably the representation of casts is behind this.

Eg. if you reinterpret cast `b` to `int**`, and make the type pun that way, we 
don't crash.

  template  void clang_analyzer_dump(T);
  void test(int *a, char ***b) {
*(int **)b = a; // only this line changed!
clang_analyzer_dump(**b); // &SymRegion{reg_$2},0 S64b,char *}>}
if (**b == nullptr) // will-not-crash
  ;
  }


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

https://reviews.llvm.org/D77062

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


[PATCH] D87043: [Analyzer] Fix for dereferece of smart pointer after branching on unknown inner pointer

2020-09-25 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

Congrats on your GSoC! Unless I missed it, it seems like you haven't posted 
your final evaluation on cfe-dev, even though its an amazing looking document 
with a lot of examples and explanations. I think it would be great to spread 
the message, its a work to be proud of!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87043

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


[PATCH] D68364: Implement C++20's P0784 (More constexpr containers)

2020-09-25 Thread Jonathan Wakely via Phabricator via cfe-commits
jwakely added a comment.

In D68364#2293971 , @leonardchan wrote:

> Is there a recommended way for working around this? We're using GCC 10.2.1. 
> Thanks.

I don't think your implementation is valid. I think P0784 only allows 
new-expressions and calls to `std::allocator::allocate` in constexpr functions, 
not calls to `operator new`.

Can you use something like `if (__builtin_is_constant_evaluated() return new 
unsigned char[n];` and the equivalent in the corresponding deallocation 
function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68364

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


[PATCH] D83144: Allow to specify macro names for android-comparison-in-temp-failure-retry.

2020-09-25 Thread Florian Mayer via Phabricator via cfe-commits
fmayer added a comment.

I am not very experienced with Phabricator, but I think this needs another 
approval for the latest revision :) Thanks in advance!


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

https://reviews.llvm.org/D83144

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


[PATCH] D85649: [AArch64] PAC/BTI code generation for LLVM generated functions

2020-09-25 Thread Momchil Velikov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa88c722e687e: [AArch64] PAC/BTI code generation for LLVM 
generated functions (authored by chill).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85649

Files:
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/aarch64-branch-protection-attr.c
  clang/test/CodeGen/aarch64-sign-return-address.c
  clang/test/CodeGenCXX/aarch64-sign-return-address-static-ctor.cpp
  llvm/lib/Target/AArch64/AArch64BranchTargets.cpp
  llvm/lib/Target/AArch64/AArch64FrameLowering.cpp
  llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp
  llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
  llvm/lib/Target/AArch64/AArch64InstrInfo.td
  llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
  llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.h
  llvm/lib/Target/AArch64/GISel/AArch64CallLowering.cpp
  llvm/test/CodeGen/AArch64/branch-target-enforcement-indirect-calls.ll
  llvm/test/CodeGen/AArch64/branch-target-enforcement.mir
  llvm/test/CodeGen/AArch64/bti-branch-relaxation.ll
  llvm/test/CodeGen/AArch64/machine-outliner-2fixup-blr-terminator.mir
  llvm/test/CodeGen/AArch64/machine-outliner-bti.mir
  llvm/test/CodeGen/AArch64/machine-outliner-outline-bti.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-0.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-1.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-3.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-4.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-5.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-7.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-8.ll
  llvm/test/CodeGen/AArch64/pacbti-llvm-generated-funcs-1.ll
  llvm/test/CodeGen/AArch64/pacbti-llvm-generated-funcs-2.ll
  llvm/test/CodeGen/AArch64/pacbti-module-attrs.ll
  llvm/test/CodeGen/AArch64/patchable-function-entry-bti.ll

Index: llvm/test/CodeGen/AArch64/patchable-function-entry-bti.ll
===
--- llvm/test/CodeGen/AArch64/patchable-function-entry-bti.ll
+++ llvm/test/CodeGen/AArch64/patchable-function-entry-bti.ll
@@ -1,6 +1,6 @@
 ; RUN: llc -mtriple=aarch64 %s -o - | FileCheck %s
 
-define void @f0() "patchable-function-entry"="0" "branch-target-enforcement" {
+define void @f0() "patchable-function-entry"="0" "branch-target-enforcement"="true" {
 ; CHECK-LABEL: f0:
 ; CHECK-NEXT: .Lfunc_begin0:
 ; CHECK:  // %bb.0:
@@ -12,7 +12,7 @@
 
 ;; -fpatchable-function-entry=1 -mbranch-protection=bti
 ;; For M=0, place the label .Lpatch0 after the initial BTI.
-define void @f1() "patchable-function-entry"="1" "branch-target-enforcement" {
+define void @f1() "patchable-function-entry"="1" "branch-target-enforcement"="true" {
 ; CHECK-LABEL: f1:
 ; CHECK-NEXT: .Lfunc_begin1:
 ; CHECK-NEXT: .cfi_startproc
@@ -28,7 +28,7 @@
 }
 
 ;; -fpatchable-function-entry=2,1 -mbranch-protection=bti
-define void @f2_1() "patchable-function-entry"="1" "patchable-function-prefix"="1" "branch-target-enforcement" {
+define void @f2_1() "patchable-function-entry"="1" "patchable-function-prefix"="1" "branch-target-enforcement"="true" {
 ; CHECK-LABEL: .type f2_1,@function
 ; CHECK-NEXT: .Ltmp0:
 ; CHECK-NEXT:  nop
@@ -50,7 +50,7 @@
 ;; -fpatchable-function-entry=1 -mbranch-protection=bti
 ;; For M=0, don't create .Lpatch0 if the initial instruction is not BTI,
 ;; even if other basic blocks may have BTI.
-define internal void @f1i(i64 %v) "patchable-function-entry"="1" "branch-target-enforcement" {
+define internal void @f1i(i64 %v) "patchable-function-entry"="1" "branch-target-enforcement"="true" {
 ; CHECK-LABEL: f1i:
 ; CHECK-NEXT: .Lfunc_begin3:
 ; CHECK:  // %bb.0:
Index: llvm/test/CodeGen/AArch64/pacbti-module-attrs.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AArch64/pacbti-module-attrs.ll
@@ -0,0 +1,77 @@
+;; RUN: llc -mtriple=aarch64-eabi -mattr=+v8.5a %s -o - | FileCheck %s
+
+declare i32 @g(i32) #5
+
+define i32 @f0(i32 %x) #0 {
+entry:
+  %call = tail call i32 @g(i32 %x) #5
+  %add = add nsw i32 %call, 1
+  ret i32 %add
+}
+;; CHECK-LABEL: f0:
+;; CHECK-NOT:   bti
+;; CHECK-NOT:   pacia
+;; CHECK-NOT:   reta
+
+define i32 @f1(i32 %x) #1 {
+entry:
+  %call = tail call i32 @g(i32 %x) #5
+  %add = add nsw i32 %call, 1
+  ret i32 %add
+}
+;; CHECK-LABEL: f1:
+;; CHECK:   bti c
+;; CHECK-NOT:   reta
+
+define i32 @f2(i32 %x) #2 {
+entry:
+  %call = tail call i32 @g(i32 %x) #5
+  %add = add nsw i32 %call, 1
+  ret i32 %add
+}
+;; CHECK-LABEL: f2:
+;; CHECK:   paciasp
+;; CHECK:   retaa
+
+define i32 @f3(i32 %x) #3 {
+entry:
+  %call = tail call i32 @g(i32 %x) #5
+  %add = add nsw i32 %call, 1
+  ret i32 %add
+}
+;; CHECK-LABEL: f3:
+;

[clang] a88c722 - [AArch64] PAC/BTI code generation for LLVM generated functions

2020-09-25 Thread Momchil Velikov via cfe-commits

Author: Momchil Velikov
Date: 2020-09-25T11:47:14+01:00
New Revision: a88c722e687e6780dcd6a58718350dc76fcc4cc9

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

LOG: [AArch64] PAC/BTI code generation for LLVM generated functions

PAC/BTI-related codegen in the AArch64 backend is controlled by a set
of LLVM IR function attributes, added to the function by Clang, based
on command-line options and GCC-style function attributes. However,
functions, generated in the LLVM middle end (for example,
asan.module.ctor or __llvm_gcov_write_out) do not get any attributes
and the backend incorrectly does not do any PAC/BTI code generation.

This patch record the default state of PAC/BTI codegen in a set of
LLVM IR module-level attributes, based on command-line options:

* "sign-return-address", with non-zero value means generate code to
  sign return addresses (PAC-RET), zero value means disable PAC-RET.

* "sign-return-address-all", with non-zero value means enable PAC-RET
  for all functions, zero value means enable PAC-RET only for
  functions, which spill LR.

* "sign-return-address-with-bkey", with non-zero value means use B-key
  for signing, zero value mean use A-key.

This set of attributes are always added for AArch64 targets (as
opposed, for example, to interpreting a missing attribute as having a
value 0) in order to be able to check for conflicts when combining
module attributed during LTO.

Module-level attributes are overridden by function level attributes.
All the decision making about whether to not to generate PAC and/or
BTI code is factored out into AArch64FunctionInfo, there shouldn't be
any places left, other than AArch64FunctionInfo, which directly
examine PAC/BTI attributes, except AArch64AsmPrinter.cpp, which
is/will-be handled by a separate patch.

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

Added: 
llvm/test/CodeGen/AArch64/pacbti-llvm-generated-funcs-1.ll
llvm/test/CodeGen/AArch64/pacbti-llvm-generated-funcs-2.ll
llvm/test/CodeGen/AArch64/pacbti-module-attrs.ll

Modified: 
clang/lib/CodeGen/CGDeclCXX.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/TargetInfo.cpp
clang/test/CodeGen/aarch64-branch-protection-attr.c
clang/test/CodeGen/aarch64-sign-return-address.c
llvm/lib/Target/AArch64/AArch64BranchTargets.cpp
llvm/lib/Target/AArch64/AArch64FrameLowering.cpp
llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp
llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
llvm/lib/Target/AArch64/AArch64InstrInfo.td
llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.h
llvm/lib/Target/AArch64/GISel/AArch64CallLowering.cpp
llvm/test/CodeGen/AArch64/branch-target-enforcement-indirect-calls.ll
llvm/test/CodeGen/AArch64/branch-target-enforcement.mir
llvm/test/CodeGen/AArch64/bti-branch-relaxation.ll
llvm/test/CodeGen/AArch64/machine-outliner-2fixup-blr-terminator.mir
llvm/test/CodeGen/AArch64/machine-outliner-bti.mir
llvm/test/CodeGen/AArch64/machine-outliner-outline-bti.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-0.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-1.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-3.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-4.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-5.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-7.ll
llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-8.ll
llvm/test/CodeGen/AArch64/patchable-function-entry-bti.ll

Removed: 
clang/test/CodeGenCXX/aarch64-sign-return-address-static-ctor.cpp



diff  --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index bfefd7956157..3f6d0e23c685 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -421,22 +421,6 @@ llvm::Function 
*CodeGenModule::CreateGlobalInitOrCleanUpFunction(
   !isInSanitizerBlacklist(SanitizerKind::ShadowCallStack, Fn, Loc))
 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
 
-  auto RASignKind = getLangOpts().getSignReturnAddressScope();
-  if (RASignKind != LangOptions::SignReturnAddressScopeKind::None) {
-Fn->addFnAttr("sign-return-address",
-  RASignKind == LangOptions::SignReturnAddressScopeKind::All
-  ? "all"
-  : "non-leaf");
-auto RASignKey = getLangOpts().getSignReturnAddressKey();
-Fn->addFnAttr("sign-return-address-key",
-  RASignKey == LangOptions::SignReturnAddressKeyKind::AKey
-  ? "a_key"
-  : "b_key");
-  }
-
-  if (getLangOpts().BranchTargetEnforcement)
-Fn->addFnAttr("branch-target-enforcement");
-
   return Fn;
 }
 

diff  --git a/clan

[PATCH] D87972: [OldPM] Pass manager: run SROA after (simple) loop unrolling

2020-09-25 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D87972#2294488 , @xbolva00 wrote:

>>> Does that sound reasonable?
>
> Yes IMHO.
>
>>> What are the next suggested steps?
>
> It would be great to isolate and check the cases which regressed a bit.

I've rerun my benchmark, and while the results are still the same (runtime 
geomean -0.53%/-0.40%,
but that obviously depends on the benchmarks), there are some obvious outliers:
F13059172: image.png 
F13059175: rsbench.txt 
I'll try to take a look at that, assuming it's not noise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87972

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


[clang] facad21 - [Analyzer] Fix for `ExprEngine::computeObjectUnderConstruction()` for base and delegating consturctor initializers

2020-09-25 Thread Adam Balogh via cfe-commits

Author: Adam Balogh
Date: 2020-09-25T13:28:22+02:00
New Revision: facad21b29839a08fdf448eb4dd5a4e31e293b9b

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

LOG: [Analyzer] Fix for `ExprEngine::computeObjectUnderConstruction()` for base 
and delegating consturctor initializers

For /C++/ constructor initializers `ExprEngine:computeUnderConstruction()`
asserts that they are all member initializers. This is not neccessarily
true when this function is used to get the return value for the
construction context thus attempts to fetch return values of base and
delegating constructor initializers result in assertions. This small
patch fixes this issue.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
index 802bc934cfb06..953a8ef58b447 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -132,10 +132,20 @@ SVal ExprEngine::computeObjectUnderConstruction(
 case ConstructionContext::SimpleConstructorInitializerKind: {
   const auto *ICC = cast(CC);
   const auto *Init = ICC->getCXXCtorInitializer();
-  assert(Init->isAnyMemberInitializer());
   const CXXMethodDecl *CurCtor = cast(LCtx->getDecl());
   Loc ThisPtr = SVB.getCXXThis(CurCtor, LCtx->getStackFrame());
   SVal ThisVal = State->getSVal(ThisPtr);
+  if (Init->isBaseInitializer()) {
+const auto *ThisReg = cast(ThisVal.getAsRegion());
+const CXXRecordDecl *BaseClass =
+  Init->getBaseClass()->getAsCXXRecordDecl();
+const auto *BaseReg =
+  MRMgr.getCXXBaseObjectRegion(BaseClass, ThisReg,
+   Init->isBaseVirtual());
+return SVB.makeLoc(BaseReg);
+  }
+  if (Init->isDelegatingInitializer())
+return ThisVal;
 
   const ValueDecl *Field;
   SVal FieldVal;
@@ -364,6 +374,11 @@ ProgramStateRef ExprEngine::updateObjectsUnderConstruction(
 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
 case ConstructionContext::SimpleConstructorInitializerKind: {
   const auto *ICC = cast(CC);
+  const auto *Init = ICC->getCXXCtorInitializer();
+  // Base and delegating initializers handled above
+  assert(Init->isAnyMemberInitializer() &&
+ "Base and delegating initializers should have been handled by"
+ "computeObjectUnderConstruction()");
   return addObjectUnderConstruction(State, ICC->getCXXCtorInitializer(),
 LCtx, V);
 }

diff  --git 
a/clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp 
b/clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
index 5750d5918db32..eb0ee6c1fd8a0 100644
--- a/clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
+++ b/clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
@@ -23,8 +23,8 @@ class TestReturnValueUnderConstructionChecker
   : public Checker {
 public:
   void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
-// Only calls with origin expression are checked. These are `returnC()`
-// and C::C().
+// Only calls with origin expression are checked. These are `returnC()`,
+// `returnD()`, C::C() and D::D().
 if (!Call.getOriginExpr())
   return;
 
@@ -35,6 +35,10 @@ class TestReturnValueUnderConstructionChecker
 Optional RetVal = Call.getReturnValueUnderConstruction();
 ASSERT_TRUE(RetVal);
 ASSERT_TRUE(RetVal->getAsRegion());
+
+const auto *RetReg = cast(RetVal->getAsRegion());
+const Expr *OrigExpr = Call.getOriginExpr();
+ASSERT_EQ(OrigExpr->getType(), RetReg->getValueType());
   }
 };
 
@@ -51,22 +55,65 @@ void addTestReturnValueUnderConstructionChecker(
 TEST(TestReturnValueUnderConstructionChecker,
  ReturnValueUnderConstructionChecker) {
   EXPECT_TRUE(runCheckerOnCode(
-  R"(class C {
- public:
-   C(int nn): n(nn) {}
-   virtual ~C() {}
- private:
-   int n;
- };
-
- C returnC(int m) {
-   C c(m);
-   return c;
- }
-
- void foo() {
-   C c = returnC(1); 
- })"));
+  R"(class C {
+ public:
+   C(int nn): n(nn) {}
+   virtual ~C() {}
+ private:
+   int n;
+ };
+
+

[PATCH] D85351: [Analyzer] Fix for `ExprEngine::computeObjectUnderConstruction()` for base and delegating consturctor initializers

2020-09-25 Thread Balogh , Ádám via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
baloghadamsoftware marked an inline comment as done.
Closed by commit rGfacad21b2983: [Analyzer] Fix for 
`ExprEngine::computeObjectUnderConstruction()` for base and… (authored by 
baloghadamsoftware).

Changed prior to commit:
  https://reviews.llvm.org/D85351?vs=290917&id=294273#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85351

Files:
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp

Index: clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
===
--- clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
+++ clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
@@ -23,8 +23,8 @@
   : public Checker {
 public:
   void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
-// Only calls with origin expression are checked. These are `returnC()`
-// and C::C().
+// Only calls with origin expression are checked. These are `returnC()`,
+// `returnD()`, C::C() and D::D().
 if (!Call.getOriginExpr())
   return;
 
@@ -35,6 +35,10 @@
 Optional RetVal = Call.getReturnValueUnderConstruction();
 ASSERT_TRUE(RetVal);
 ASSERT_TRUE(RetVal->getAsRegion());
+
+const auto *RetReg = cast(RetVal->getAsRegion());
+const Expr *OrigExpr = Call.getOriginExpr();
+ASSERT_EQ(OrigExpr->getType(), RetReg->getValueType());
   }
 };
 
@@ -51,22 +55,65 @@
 TEST(TestReturnValueUnderConstructionChecker,
  ReturnValueUnderConstructionChecker) {
   EXPECT_TRUE(runCheckerOnCode(
-  R"(class C {
- public:
-   C(int nn): n(nn) {}
-   virtual ~C() {}
- private:
-   int n;
- };
-
- C returnC(int m) {
-   C c(m);
-   return c;
- }
-
- void foo() {
-   C c = returnC(1); 
- })"));
+  R"(class C {
+ public:
+   C(int nn): n(nn) {}
+   virtual ~C() {}
+ private:
+   int n;
+ };
+
+ C returnC(int m) {
+   C c(m);
+   return c;
+ }
+
+ void foo() {
+   C c = returnC(1);
+ })"));
+
+  EXPECT_TRUE(runCheckerOnCode(
+  R"(class C {
+ public:
+   C(int nn): n(nn) {}
+   explicit C(): C(0) {}
+   virtual ~C() {}
+ private:
+   int n;
+ };
+
+ C returnC() {
+   C c;
+   return c;
+ }
+
+ void foo() {
+   C c = returnC();
+ })"));
+
+  EXPECT_TRUE(runCheckerOnCode(
+  R"(class C {
+ public:
+   C(int nn): n(nn) {}
+   virtual ~C() {}
+ private:
+   int n;
+ };
+
+ class D: public C {
+ public:
+   D(int nn): C(nn) {}
+   virtual ~D() {}
+ };
+
+ D returnD(int m) {
+   D d(m);
+   return d;
+ }
+
+ void foo() {
+   D d = returnD(1); 
+ })"));
 }
 
 } // namespace
Index: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -132,10 +132,20 @@
 case ConstructionContext::SimpleConstructorInitializerKind: {
   const auto *ICC = cast(CC);
   const auto *Init = ICC->getCXXCtorInitializer();
-  assert(Init->isAnyMemberInitializer());
   const CXXMethodDecl *CurCtor = cast(LCtx->getDecl());
   Loc ThisPtr = SVB.getCXXThis(CurCtor, LCtx->getStackFrame());
   SVal ThisVal = State->getSVal(ThisPtr);
+  if (Init->isBaseInitializer()) {
+const auto *ThisReg = cast(ThisVal.getAsRegion());
+const CXXRecordDecl *BaseClass =
+  Init->getBaseClass()->getAsCXXRecordDecl();
+const auto *BaseReg =
+  MRMgr.getCXXBaseObjectRegion(BaseClass, ThisReg,
+   Init->isBaseVirtual());
+return SVB.makeLoc(BaseReg);
+  }
+  if (Init->isDelegatingInitializer())
+return ThisVal;
 
   const ValueDecl *Field;
   SVal FieldVal;
@@ -364,6 +374,11 @@
 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind:
 case ConstructionContext::SimpleConstructorInitializerKind: {
   const auto *ICC = cast(CC);
+  const auto *Init = ICC->getCXXCtorInitializer();
+  // Base and delegating initializers handled above
+  assert(Init->isAnyMemberInitializer() &&
+ "Base and delegating initializers should have been handled by"
+

[PATCH] D84176: [CMake][CTE] Add "check-clang-extra-..." targets to test only a particular Clang extra tool

2020-09-25 Thread Whisperity via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9d2ef5e74eea: [CMake][CTE] Add 
"check-clang-extra-..." targets to test only a particular… (authored 
by whisperity).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84176

Files:
  clang-tools-extra/test/CMakeLists.txt


Index: clang-tools-extra/test/CMakeLists.txt
===
--- clang-tools-extra/test/CMakeLists.txt
+++ clang-tools-extra/test/CMakeLists.txt
@@ -90,3 +90,7 @@
   )
 
 set_target_properties(check-clang-tools PROPERTIES FOLDER "Clang extra tools' 
tests")
+
+add_lit_testsuites(CLANG-EXTRA ${CMAKE_CURRENT_SOURCE_DIR}
+  DEPENDS ${CLANG_TOOLS_TEST_DEPS}
+  )


Index: clang-tools-extra/test/CMakeLists.txt
===
--- clang-tools-extra/test/CMakeLists.txt
+++ clang-tools-extra/test/CMakeLists.txt
@@ -90,3 +90,7 @@
   )
 
 set_target_properties(check-clang-tools PROPERTIES FOLDER "Clang extra tools' tests")
+
+add_lit_testsuites(CLANG-EXTRA ${CMAKE_CURRENT_SOURCE_DIR}
+  DEPENDS ${CLANG_TOOLS_TEST_DEPS}
+  )
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 9d2ef5e - [CMake][CTE] Add "check-clang-extra-..." targets to test only a particular Clang extra tool

2020-09-25 Thread via cfe-commits

Author: Whisperity
Date: 2020-09-25T13:32:56+02:00
New Revision: 9d2ef5e74eea2247657431f44152f1f83ed99b84

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

LOG: [CMake][CTE] Add "check-clang-extra-..." targets to test only a particular 
Clang extra tool

Create targets `check-clang-extra-clang-tidy`, `check-clang-extra-clang-query`
similar to how `check-clang-sema`, `check-clang-parser`, etc. are
auto-generated from the directory structure.

This allows running only a particular sub-tool's tests, not having to wait
through the entire `check-clang-tools` execution.

Differential Revision: http://reviews.llvm.org/D84176

Added: 


Modified: 
clang-tools-extra/test/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/test/CMakeLists.txt 
b/clang-tools-extra/test/CMakeLists.txt
index 15b756f0a320..662b138e9f46 100644
--- a/clang-tools-extra/test/CMakeLists.txt
+++ b/clang-tools-extra/test/CMakeLists.txt
@@ -90,3 +90,7 @@ add_lit_testsuite(check-clang-tools "Running the Clang extra 
tools' regression t
   )
 
 set_target_properties(check-clang-tools PROPERTIES FOLDER "Clang extra tools' 
tests")
+
+add_lit_testsuites(CLANG-EXTRA ${CMAKE_CURRENT_SOURCE_DIR}
+  DEPENDS ${CLANG_TOOLS_TEST_DEPS}
+  )



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


[PATCH] D84306: [clang-format][NFC] Be more careful about the layout of FormatToken.

2020-09-25 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

FWIW, finding this due to seeing the added complexity. Do you have data on what 
the difference is on clang-format for either overall memory use or performance? 
Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84306

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


[PATCH] D88130: [PPC] [AIX] Implement calling convention IR for C99 complex types on AIX

2020-09-25 Thread Zarko Todorovski via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf330d9f163f6: [PPC] [AIX] Implement calling convention IR 
for C99 complex types on AIX (authored by cebowleratibm, committed by ZarkoCA).

Changed prior to commit:
  https://reviews.llvm.org/D88130?vs=293627&id=294277#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88130

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/aix-complex.c
  clang/test/CodeGen/powerpc-c99complex.c

Index: clang/test/CodeGen/powerpc-c99complex.c
===
--- clang/test/CodeGen/powerpc-c99complex.c
+++ clang/test/CodeGen/powerpc-c99complex.c
@@ -1,39 +1,44 @@
-// RUN: %clang_cc1 -triple powerpc64-unknown-linux -emit-llvm %s -o - | FileCheck %s --check-prefixes=PPC64LNX
-// RUN: %clang_cc1 -triple ppc64le-unknown-linux -emit-llvm %s -o - | FileCheck %s --check-prefixes=PPC64LNX
+// RUN: %clang_cc1 -triple powerpc64-unknown-aix -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-NOLDBL128
+// RUN: %clang_cc1 -triple powerpc-unknown-aix -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-NOLDBL128
+// RUN: %clang_cc1 -triple powerpc64-unknown-linux -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-LDBL128
+// RUN: %clang_cc1 -triple ppc64le-unknown-linux -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-LDBL128
 // RUN: %clang_cc1 -triple powerpc-unknown-linux -emit-llvm %s -o - | FileCheck %s --check-prefix=PPC32LNX
 
 _Complex float foo1(_Complex float x) {
   return x;
-// PPC64LNX-LABEL:   define { float, float } @foo1(float %x.{{.*}}, float %x.{{.*}}) #0 {
-// PPC64LNX: ret { float, float }
+// CHECK-LABEL: define { float, float } @foo1(float %x.{{.*}}, float %x.{{.*}}) #0 {
+// CHECK:   ret { float, float }
 
-// PPC32LNX-LABEL:   define void @foo1({ float, float }* noalias sret align 4 %agg.result, { float, float }* byval({ float, float }) align 4 %x) #0 {
-// PPC32LNX: [[RETREAL:%.*]] = getelementptr inbounds { float, float }, { float, float }* %agg.result, i32 0, i32 0
-// PPC32LNX-NEXT:[[RETIMAG:%.*]] = getelementptr inbounds { float, float }, { float, float }* %agg.result, i32 0, i32 1
-// PPC32LNX-NEXT:store float %{{.*}}, float* [[RETREAL]], align 4
-// PPC32LNX-NEXT:store float %{{.*}}, float* [[RETIMAG]], align 4
+// PPC32LNX-LABEL:  define void @foo1({ float, float }* noalias sret align 4 %agg.result, { float, float }* byval({ float, float }) align 4 %x) #0 {
+// PPC32LNX:[[RETREAL:%.*]] = getelementptr inbounds { float, float }, { float, float }* %agg.result, i32 0, i32 0
+// PPC32LNX-NEXT:   [[RETIMAG:%.*]] = getelementptr inbounds { float, float }, { float, float }* %agg.result, i32 0, i32 1
+// PPC32LNX-NEXT:   store float %{{.*}}, float* [[RETREAL]], align 4
+// PPC32LNX-NEXT:   store float %{{.*}}, float* [[RETIMAG]], align 4
 }
 
 _Complex double foo2(_Complex double x) {
   return x;
-// PPC64LNX-LABEL:   define { double, double } @foo2(double %x.{{.*}}, double %x.{{.*}}) #0 {
-// PPC64LNX: ret { double, double }
+// CHECK-LABEL: define { double, double } @foo2(double %x.{{.*}}, double %x.{{.*}}) #0 {
+// CHECK:   ret { double, double }
 
-// PPC32LNX-LABEL:   define void @foo2({ double, double }* noalias sret align 8 %agg.result, { double, double }* byval({ double, double }) align 8 %x) #0 {
-// PPC32LNX: [[RETREAL:%.*]] = getelementptr inbounds { double, double }, { double, double }* %agg.result, i32 0, i32 0
-// PPC32LNX-NEXT:[[RETIMAG:%.*]] = getelementptr inbounds { double, double }, { double, double }* %agg.result, i32 0, i32 1
-// PPC32LNX-NEXT:store double %{{.*}}, double* [[RETREAL]], align 8
-// PPC32LNX-NEXT:store double %{{.*}}, double* [[RETIMAG]], align 8
+// PPC32LNX-LABEL:  define void @foo2({ double, double }* noalias sret align 8 %agg.result, { double, double }* byval({ double, double }) align 8 %x) #0 {
+// PPC32LNX:[[RETREAL:%.*]] = getelementptr inbounds { double, double }, { double, double }* %agg.result, i32 0, i32 0
+// PPC32LNX-NEXT:   [[RETIMAG:%.*]] = getelementptr inbounds { double, double }, { double, double }* %agg.result, i32 0, i32 1
+// PPC32LNX-NEXT:   store double %{{.*}}, double* [[RETREAL]], align 8
+// PPC32LNX-NEXT:   store double %{{.*}}, double* [[RETIMAG]], align 8
 }
 
 _Complex long double foo3(_Complex long double x) {
   return x;
-// PPC64LNX-LABEL:  define { ppc_fp128, ppc_fp128 } @foo3(ppc_fp128 %x.{{.*}}, ppc_fp128 %x.{{.*}}) #0 {
-// PPC64LNX:ret { ppc_fp128, ppc_fp128 }
+// CHECK-NOLDBL128-LABEL:   define { double, double } @foo3(do

[clang] f330d9f - [PPC] [AIX] Implement calling convention IR for C99 complex types on AIX

2020-09-25 Thread Zarko Todorovski via cfe-commits

Author: Chris Bowler
Date: 2020-09-25T07:43:31-04:00
New Revision: f330d9f163f644b968c6aa5884dc1be5efda20a1

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

LOG: [PPC] [AIX] Implement calling convention IR for C99 complex types on AIX

Add AIX calling convention logic to Clang for C99 complex types on AIX

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

Added: 


Modified: 
clang/lib/CodeGen/TargetInfo.cpp
clang/test/CodeGen/powerpc-c99complex.c

Removed: 
clang/test/CodeGen/aix-complex.c



diff  --git a/clang/lib/CodeGen/TargetInfo.cpp 
b/clang/lib/CodeGen/TargetInfo.cpp
index 2f3f4c281079..6e15cac7359e 100644
--- a/clang/lib/CodeGen/TargetInfo.cpp
+++ b/clang/lib/CodeGen/TargetInfo.cpp
@@ -4504,7 +4504,7 @@ bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) 
const {
 
 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
   if (RetTy->isAnyComplexType())
-llvm::report_fatal_error("complex type is not supported on AIX yet");
+return ABIArgInfo::getDirect();
 
   if (RetTy->isVectorType())
 llvm::report_fatal_error("vector type is not supported on AIX yet");
@@ -4525,7 +4525,7 @@ ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) 
const {
   Ty = useFirstFieldIfTransparentUnion(Ty);
 
   if (Ty->isAnyComplexType())
-llvm::report_fatal_error("complex type is not supported on AIX yet");
+return ABIArgInfo::getDirect();
 
   if (Ty->isVectorType())
 llvm::report_fatal_error("vector type is not supported on AIX yet");
@@ -4550,8 +4550,9 @@ ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) 
const {
 }
 
 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
-  if (Ty->isAnyComplexType())
-llvm::report_fatal_error("complex type is not supported on AIX yet");
+  // Complex types are passed just like their elements.
+  if (const ComplexType *CTy = Ty->getAs())
+Ty = CTy->getElementType();
 
   if (Ty->isVectorType())
 llvm::report_fatal_error("vector type is not supported on AIX yet");

diff  --git a/clang/test/CodeGen/aix-complex.c 
b/clang/test/CodeGen/aix-complex.c
deleted file mode 100644
index 62ab481a9156..
--- a/clang/test/CodeGen/aix-complex.c
+++ /dev/null
@@ -1,10 +0,0 @@
-// REQUIRES: powerpc-registered-target
-// RUN: not %clang_cc1 -triple powerpc-unknown-aix \
-// RUN:   -emit-llvm -o - %s 2>&1 | FileCheck %s
-// RUN: not %clang_cc1 -triple powerpc64-unknown-aix \
-// RUN:   -emit-llvm -o - %s 2>&1 | FileCheck %s
-
-// CHECK: fatal error: error in backend: complex type is not supported on AIX 
yet
-_Complex float foo_float(_Complex float x) {
-  return x;
-}

diff  --git a/clang/test/CodeGen/powerpc-c99complex.c 
b/clang/test/CodeGen/powerpc-c99complex.c
index 95c71ee4ec81..a59cdb683c0e 100644
--- a/clang/test/CodeGen/powerpc-c99complex.c
+++ b/clang/test/CodeGen/powerpc-c99complex.c
@@ -1,39 +1,44 @@
-// RUN: %clang_cc1 -triple powerpc64-unknown-linux -emit-llvm %s -o - | 
FileCheck %s --check-prefixes=PPC64LNX
-// RUN: %clang_cc1 -triple ppc64le-unknown-linux -emit-llvm %s -o - | 
FileCheck %s --check-prefixes=PPC64LNX
+// RUN: %clang_cc1 -triple powerpc64-unknown-aix -emit-llvm %s -o - | 
FileCheck %s --check-prefixes=CHECK,CHECK-NOLDBL128
+// RUN: %clang_cc1 -triple powerpc-unknown-aix -emit-llvm %s -o - | FileCheck 
%s --check-prefixes=CHECK,CHECK-NOLDBL128
+// RUN: %clang_cc1 -triple powerpc64-unknown-linux -emit-llvm %s -o - | 
FileCheck %s --check-prefixes=CHECK,CHECK-LDBL128
+// RUN: %clang_cc1 -triple ppc64le-unknown-linux -emit-llvm %s -o - | 
FileCheck %s --check-prefixes=CHECK,CHECK-LDBL128
 // RUN: %clang_cc1 -triple powerpc-unknown-linux -emit-llvm %s -o - | 
FileCheck %s --check-prefix=PPC32LNX
 
 _Complex float foo1(_Complex float x) {
   return x;
-// PPC64LNX-LABEL:   define { float, float } @foo1(float %x.{{.*}}, float 
%x.{{.*}}) #0 {
-// PPC64LNX: ret { float, float }
+// CHECK-LABEL: define { float, float } @foo1(float %x.{{.*}}, 
float %x.{{.*}}) #0 {
+// CHECK:   ret { float, float }
 
-// PPC32LNX-LABEL:   define void @foo1({ float, float }* noalias sret 
align 4 %agg.result, { float, float }* byval({ float, float }) align 4 %x) #0 {
-// PPC32LNX: [[RETREAL:%.*]] = getelementptr inbounds { float, 
float }, { float, float }* %agg.result, i32 0, i32 0
-// PPC32LNX-NEXT:[[RETIMAG:%.*]] = getelementptr inbounds { float, 
float }, { float, float }* %agg.result, i32 0, i32 1
-// PPC32LNX-NEXT:store float %{{.*}}, float* [[RETREAL]], align 4
-// PPC32LNX-NEXT:store float %{{.*}}, float* [[RETIMAG]], align 4
+// PPC32LNX-LABEL:  define void @foo1({ float, float }* noalias sret 
align 4 %agg.result, { float, float }* byval({ float, float }) align 4 %x) #0 {
+// PPC3

[PATCH] D87030: Adapt CastExpr::getSubExprAsWritten to ConstantExpr

2020-09-25 Thread Stephan Bergmann via Phabricator via cfe-commits
sberg added a comment.

ping^2


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

https://reviews.llvm.org/D87030

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


[PATCH] D88281: [clangd] Use Decision Forest to score code compeltions.

2020-09-25 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 294281.
usaxena95 added a comment.

Moved DF evaluation to Quality.cpp


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88281

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/CodeComplete.h
  clang-tools-extra/clangd/Quality.cpp
  clang-tools-extra/clangd/Quality.h
  clang-tools-extra/clangd/tool/ClangdMain.cpp

Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -167,6 +167,18 @@
 Hidden,
 };
 
+opt RankingModel{
+"ranking-model",
+cat(Features),
+desc("Model to use to rank code-completion items"),
+values(clEnumValN(CodeCompleteOptions::Heuristics, "heuristic",
+  "Use hueristics to rank code completion items"),
+   clEnumValN(CodeCompleteOptions::DecisionForest, "df",
+  "Use Decision Forest model to rank completion items")),
+init(CodeCompleteOptions().RankingModel),
+Hidden,
+};
+
 // FIXME: also support "plain" style where signatures are always omitted.
 enum CompletionStyleFlag { Detailed, Bundled };
 opt CompletionStyle{
@@ -739,6 +751,7 @@
   CCOpts.EnableFunctionArgSnippets = EnableFunctionArgSnippets;
   CCOpts.AllScopes = AllScopesCompletion;
   CCOpts.RunParser = CodeCompletionParse;
+  CCOpts.RankingModel = RankingModel;
 
   RealThreadsafeFS TFS;
   std::vector> ProviderStack;
Index: clang-tools-extra/clangd/Quality.h
===
--- clang-tools-extra/clangd/Quality.h
+++ clang-tools-extra/clangd/Quality.h
@@ -136,6 +136,10 @@
   // Whether the item matches the type expected in the completion context.
   bool TypeMatchesPreferred = false;
 
+  /// Length of the unqualified partial name of Symbol typed in
+  /// CompletionPrefix.
+  unsigned FilterLength = 0;
+
   /// Set of derived signals computed by calculateDerivedSignals(). Must not be
   /// set explicitly.
   struct DerivedSignals {
@@ -161,6 +165,8 @@
 /// Combine symbol quality and relevance into a single score.
 float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance);
 
+float evaluateDecisionForest(const SymbolQualitySignals &Quality,
+ const SymbolRelevanceSignals &Relevance);
 /// TopN is a lossy container that preserves only the "best" N elements.
 template > class TopN {
 public:
Index: clang-tools-extra/clangd/Quality.cpp
===
--- clang-tools-extra/clangd/Quality.cpp
+++ clang-tools-extra/clangd/Quality.cpp
@@ -8,6 +8,7 @@
 
 #include "Quality.h"
 #include "AST.h"
+#include "CompletionModel.h"
 #include "FileDistance.h"
 #include "SourceCode.h"
 #include "URI.h"
@@ -486,6 +487,33 @@
   return SymbolQuality * SymbolRelevance;
 }
 
+float evaluateDecisionForest(const SymbolQualitySignals &Quality,
+ const SymbolRelevanceSignals &Relevance) {
+  Example E;
+  E.setIsDeprecated(Quality.Deprecated);
+  E.setIsReservedName(Quality.ReservedName);
+  E.setIsImplementationDetail(Quality.ImplementationDetail);
+  E.setNumReferences(Quality.References);
+  E.setSymbolCategory(Quality.Category);
+
+  SymbolRelevanceSignals::DerivedSignals Derived =
+  Relevance.calculateDerivedSignals();
+  E.setIsNameInContext(Derived.NameMatchesContext);
+  E.setIsForbidden(Relevance.Forbidden);
+  E.setIsInBaseClass(Relevance.InBaseClass);
+  E.setFileProximityDistance(Derived.FileProximityDistance);
+  E.setSemaFileProximityScore(Relevance.SemaFileProximityScore);
+  E.setSymbolScopeDistance(Derived.ScopeProximityDistance);
+  E.setSemaSaysInScope(Relevance.SemaSaysInScope);
+  E.setScope(Relevance.Scope);
+  E.setContextKind(Relevance.Context);
+  E.setIsInstanceMember(Relevance.IsInstanceMember);
+  E.setHadContextType(Relevance.HadContextType);
+  E.setHadSymbolType(Relevance.HadSymbolType);
+  E.setTypeMatchesPreferred(Relevance.TypeMatchesPreferred);
+  E.setFilterLength(Relevance.FilterLength);
+  return Evaluate(E);
+}
 // Produces an integer that sorts in the same order as F.
 // That is: a < b <==> encodeFloat(a) < encodeFloat(b).
 static uint32_t encodeFloat(float F) {
Index: clang-tools-extra/clangd/CodeComplete.h
===
--- clang-tools-extra/clangd/CodeComplete.h
+++ clang-tools-extra/clangd/CodeComplete.h
@@ -147,6 +147,12 @@
   std::function
   RecordCCResult;
+
+  /// Model to use for ranking code completion candidates.
+  enum CodeCompletionRankingModel {
+Heuristics,
+DecisionForest,
+  } RankingModel = Heuristics;
 };
 
 // Semi-structured representation of a code-complete suggestion for our C++ API.
Index: clang-tools-extra/clangd/CodeComplete.cpp
==

[PATCH] D87146: [analyzer] Implement shared semantics checks for XNU functions in PthreadLockChecker

2020-09-25 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

In D87146#2294514 , 
@baloghadamsoftware wrote:

> In D87146#2294423 , @ASDenysPetrov 
> wrote:
>
>> It would be nice if someone had time to look at this. Thanks.
>
> I am just looking, but I am not a `pthread` expert.

Sorry, absolutely no competence.


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

https://reviews.llvm.org/D87146

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


[PATCH] D83296: [clang-format] Add a MacroExpander.

2020-09-25 Thread Manuel Klimek via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
klimek marked 5 inline comments as done.
Closed by commit rGe336b74c995d: [clang-format] Add a MacroExpander. (authored 
by klimek).

Changed prior to commit:
  https://reviews.llvm.org/D83296?vs=292970&id=294285#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83296

Files:
  clang/lib/Format/CMakeLists.txt
  clang/lib/Format/FormatToken.h
  clang/lib/Format/MacroExpander.cpp
  clang/lib/Format/Macros.h
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/MacroExpanderTest.cpp
  clang/unittests/Format/TestLexer.h

Index: clang/unittests/Format/TestLexer.h
===
--- /dev/null
+++ clang/unittests/Format/TestLexer.h
@@ -0,0 +1,88 @@
+//===--- TestLexer.h - Format C++ code --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+///
+/// \file
+/// This file contains a TestLexer to create FormatTokens from strings.
+///
+//===--===//
+
+#ifndef CLANG_UNITTESTS_FORMAT_TESTLEXER_H
+#define CLANG_UNITTESTS_FORMAT_TESTLEXER_H
+
+#include "../../lib/Format/FormatTokenLexer.h"
+
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/SourceManager.h"
+
+#include 
+#include 
+
+namespace clang {
+namespace format {
+
+typedef llvm::SmallVector TokenList;
+
+inline std::ostream &operator<<(std::ostream &Stream, const FormatToken &Tok) {
+  Stream << "(" << Tok.Tok.getName() << ", \"" << Tok.TokenText.str() << "\")";
+  return Stream;
+}
+inline std::ostream &operator<<(std::ostream &Stream, const TokenList &Tokens) {
+  Stream << "{";
+  for (size_t I = 0, E = Tokens.size(); I != E; ++I) {
+Stream << (I > 0 ? ", " : "") << *Tokens[I];
+  }
+  Stream << "}";
+  return Stream;
+}
+
+inline TokenList uneof(const TokenList &Tokens) {
+  assert(!Tokens.empty() && Tokens.back()->is(tok::eof));
+  return TokenList(Tokens.begin(), std::prev(Tokens.end()));
+}
+
+inline std::string text(llvm::ArrayRef Tokens) {
+  return std::accumulate(Tokens.begin(), Tokens.end(), std::string(),
+ [](const std::string &R, FormatToken *Tok) {
+   return (R + Tok->TokenText).str();
+ });
+}
+
+class TestLexer {
+public:
+  TestLexer() : SourceMgr("test.cpp", "") {}
+
+  TokenList lex(llvm::StringRef Code) {
+Buffers.push_back(
+llvm::MemoryBuffer::getMemBufferCopy(Code, ""));
+clang::FileID FID = SourceMgr.get().createFileID(SourceManager::Unowned,
+ Buffers.back().get());
+FormatTokenLexer Lex(SourceMgr.get(), FID, 0, Style, Encoding, Allocator,
+ IdentTable);
+auto Result = Lex.lex();
+return TokenList(Result.begin(), Result.end());
+  }
+
+  FormatToken *id(llvm::StringRef Code) {
+auto Result = uneof(lex(Code));
+assert(Result.size() == 1U && "Code must expand to 1 token.");
+return Result[0];
+  }
+
+  FormatStyle Style = getLLVMStyle();
+  encoding::Encoding Encoding = encoding::Encoding_UTF8;
+  std::vector> Buffers;
+  clang::SourceManagerForFile SourceMgr;
+  llvm::SpecificBumpPtrAllocator Allocator;
+  IdentifierTable IdentTable;
+};
+
+} // namespace format
+} // namespace clang
+
+#endif // LLVM_CLANG_UNITTESTS_FORMAT_TEST_LEXER_H
Index: clang/unittests/Format/MacroExpanderTest.cpp
===
--- /dev/null
+++ clang/unittests/Format/MacroExpanderTest.cpp
@@ -0,0 +1,187 @@
+#include "../../lib/Format/Macros.h"
+#include "TestLexer.h"
+#include "clang/Basic/FileManager.h"
+
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace format {
+
+namespace {
+
+class MacroExpanderTest : public ::testing::Test {
+public:
+  std::unique_ptr
+  create(const std::vector &MacroDefinitions) {
+return std::make_unique(MacroDefinitions,
+   Lex.SourceMgr.get(), Lex.Style,
+   Lex.Allocator, Lex.IdentTable);
+  }
+
+  std::string expand(MacroExpander &Macros, llvm::StringRef Name,
+ const std::vector &Args = {}) {
+EXPECT_TRUE(Macros.defined(Name));
+return text(Macros.expand(Lex.id(Name), lexArgs(Args)));
+  }
+
+  llvm::SmallVector
+  lexArgs(const std::vector &Args) {
+llvm::SmallVector Result;
+for (const auto &Arg : Args) {
+  Result.push_back(uneof(Lex.lex(Arg)));
+}
+return Result;
+  }
+
+  struct MacroAttributes {
+clang::tok::TokenKind Kind;
+MacroR

[clang] e336b74 - [clang-format] Add a MacroExpander.

2020-09-25 Thread Manuel Klimek via cfe-commits

Author: Manuel Klimek
Date: 2020-09-25T14:08:13+02:00
New Revision: e336b74c995d665bc3fb75164375bbb0f78f516c

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

LOG: [clang-format] Add a MacroExpander.

Summary:
The MacroExpander allows to expand simple (non-resursive) macro
definitions from a macro identifier token and macro arguments. It
annotates the tokens with a newly introduced MacroContext that keeps
track of the role a token played in expanding the macro in order to
be able to reconstruct the macro expansion from an expanded (formatted)
token stream.

Made Token explicitly copy-able to enable copying tokens from the parsed
macro definition.

Reviewers: sammccall

Subscribers: mgorny, cfe-commits

Tags: #clang

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

Added: 
clang/lib/Format/MacroExpander.cpp
clang/lib/Format/Macros.h
clang/unittests/Format/MacroExpanderTest.cpp
clang/unittests/Format/TestLexer.h

Modified: 
clang/lib/Format/CMakeLists.txt
clang/lib/Format/FormatToken.h
clang/unittests/Format/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Format/CMakeLists.txt b/clang/lib/Format/CMakeLists.txt
index 0019d045cd06..ec1522db7e87 100644
--- a/clang/lib/Format/CMakeLists.txt
+++ b/clang/lib/Format/CMakeLists.txt
@@ -7,6 +7,7 @@ add_clang_library(clangFormat
   Format.cpp
   FormatToken.cpp
   FormatTokenLexer.cpp
+  MacroExpander.cpp
   NamespaceEndCommentsFixer.cpp
   SortJavaScriptImports.cpp
   TokenAnalyzer.cpp

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 76ef99e72d58..c6af71a768a1 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -136,6 +136,68 @@ enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, 
PPK_Inconclusive };
 
 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
 
+/// Roles a token can take in a configured macro expansion.
+enum MacroRole {
+  /// The token was expanded from a macro argument when formatting the expanded
+  /// token sequence.
+  MR_ExpandedArg,
+  /// The token is part of a macro argument that was previously formatted as
+  /// expansion when formatting the unexpanded macro call.
+  MR_UnexpandedArg,
+  /// The token was expanded from a macro definition, and is not visible as 
part
+  /// of the macro call.
+  MR_Hidden,
+};
+
+struct FormatToken;
+
+/// Contains information on the token's role in a macro expansion.
+///
+/// Given the following definitions:
+/// A(X) = [ X ]
+/// B(X) = < X >
+/// C(X) = X
+///
+/// Consider the macro call:
+/// A({B(C(C(x)))}) -> [{}]
+///
+/// In this case, the tokens of the unexpanded macro call will have the
+/// following relevant entries in their macro context (note that formatting
+/// the unexpanded macro call happens *after* formatting the expanded macro
+/// call):
+///   A( { B( C( C(x) ) ) } )
+/// Role: NN U NN NN NNUN N N U N  (N=None, U=UnexpandedArg)
+///
+///   [  { <   x> } ]
+/// Role: H  E H   EH E H  (H=Hidden, E=ExpandedArg)
+/// ExpandedFrom[0]:  A  A A   AA A A
+/// ExpandedFrom[1]:   B   BB
+/// ExpandedFrom[2]:   C
+/// ExpandedFrom[3]:   C
+/// StartOfExpansion: 1  0 1   20 0 0
+/// EndOfExpansion:   0  0 0   21 0 1
+struct MacroExpansion {
+  MacroExpansion(MacroRole Role) : Role(Role) {}
+
+  /// The token's role in the macro expansion.
+  /// When formatting an expanded macro, all tokens that are part of macro
+  /// arguments will be MR_ExpandedArg, while all tokens that are not visible 
in
+  /// the macro call will be MR_Hidden.
+  /// When formatting an unexpanded macro call, all tokens that are part of
+  /// macro arguments will be MR_UnexpandedArg.
+  MacroRole Role;
+
+  /// The stack of macro call identifier tokens this token was expanded from.
+  llvm::SmallVector ExpandedFrom;
+
+  /// The number of expansions of which this macro is the first entry.
+  unsigned StartOfExpansion = 0;
+
+  /// The number of currently open expansions in \c ExpandedFrom this macro is
+  /// the last token in.
+  unsigned EndOfExpansion = 0;
+};
+
 class TokenRole;
 class AnnotatedLine;
 
@@ -163,7 +225,9 @@ struct FormatToken {
 
   /// A token can have a special role that can carry extra information
   /// about the token's formatting.
-  std::unique_ptr Role;
+  /// FIXME: Make FormatToken for parsing and AnnotatedToken two 
diff erent
+  /// classes and make this a unique_ptr in the AnnotatedToken class.
+  std::shared_ptr Role;
 
   /// The range of the whitespace immediately preceding the \c Token.
   SourceRange WhitespaceRange;
@@ -378,6 +442,10 @@ struct FormatToken {
   /// in it.
   SmallVector Children;
 
+  // Contai

[clang] 6a1bca8 - [Analyzer] Fix unused variable warning in Release builds

2020-09-25 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2020-09-25T14:09:43+02:00
New Revision: 6a1bca8798c6ba119f188061472b60876495b9ae

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

LOG: [Analyzer] Fix unused variable warning in Release builds

clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp:377:19: warning: unused 
variable 'Init'

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
index 953a8ef58b44..cab65687444b 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -379,8 +379,7 @@ ProgramStateRef ExprEngine::updateObjectsUnderConstruction(
   assert(Init->isAnyMemberInitializer() &&
  "Base and delegating initializers should have been handled by"
  "computeObjectUnderConstruction()");
-  return addObjectUnderConstruction(State, ICC->getCXXCtorInitializer(),
-LCtx, V);
+  return addObjectUnderConstruction(State, Init, LCtx, V);
 }
 case ConstructionContext::NewAllocatedObjectKind: {
   return State;



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


[PATCH] D88295: [Sema] Fix volatile check when test if a return object can be implicitly move

2020-09-25 Thread Yang Fan via Phabricator via cfe-commits
nullptr.cpp created this revision.
nullptr.cpp added reviewers: Quuxplusone, rsmith, erik.pilkington.
Herald added subscribers: cfe-commits, dexonsmith.
Herald added a project: clang.
nullptr.cpp requested review of this revision.

In C++11 standard, to become implicitly movable, the expression in return
statement should be a non-volatile automatic object. CWG1579 changed the rule
to require that the expression only needs to be a automatic object. C++14
standard and C++17 standard kept this rule unchanged. C++20 standard changed
the rule back to require the expression be a non-volatile automatic object.
This should be a typo in standards, and `VD` should be non-volatile.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88295

Files:
  clang/lib/Sema/SemaStmt.cpp


Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3056,12 +3056,13 @@
   // variable will no longer be used.
   if (VD->hasAttr()) return false;
 
+  // ...non-volatile...
+  if (VD->getType().isVolatileQualified())
+return false;
+
   if (CESK & CES_AllowDifferentTypes)
 return true;
 
-  // ...non-volatile...
-  if (VD->getType().isVolatileQualified()) return false;
-
   // Variables with higher required alignment than their type's ABI
   // alignment cannot use NRVO.
   if (!VD->getType()->isDependentType() && VD->hasAttr() &&


Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3056,12 +3056,13 @@
   // variable will no longer be used.
   if (VD->hasAttr()) return false;
 
+  // ...non-volatile...
+  if (VD->getType().isVolatileQualified())
+return false;
+
   if (CESK & CES_AllowDifferentTypes)
 return true;
 
-  // ...non-volatile...
-  if (VD->getType().isVolatileQualified()) return false;
-
   // Variables with higher required alignment than their type's ABI
   // alignment cannot use NRVO.
   if (!VD->getType()->isDependentType() && VD->hasAttr() &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80791: [AArch64] Generate .note.gnu.property based on module flags.

2020-09-25 Thread Daniel Kiss via Phabricator via cfe-commits
danielkiss updated this revision to Diff 294284.

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

https://reviews.llvm.org/D80791

Files:
  llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-0.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-1.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-2.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-3.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-4.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-5.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-6.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-7.ll
  llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-8.ll

Index: llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-8.ll
===
--- llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-8.ll
+++ /dev/null
@@ -1,21 +0,0 @@
-; RUN: llc -mtriple=aarch64-linux %s   -o - | \
-; RUN:   FileCheck %s --check-prefix=ASM
-; RUN: llc -mtriple=aarch64-linux %s -filetype=obj -o - | \
-; RUN:   llvm-readelf --notes - | FileCheck %s --check-prefix=OBJ
-
-define dso_local i32 @f() #0 {
-entry:
-  %r = tail call i32 @g()
-  ret i32 %r
-}
-
-declare dso_local i32 @g()
-
-attributes #0 = { "branch-target-enforcement"="true" }
-
-; Declarations don't prevent setting BTI
-; ASM:	.word	3221225472
-; ASM-NEXT:	.word	4
-; ASM-NEXT:	.word	1
-
-; OBJ: Properties: aarch64 feature: BTI
Index: llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-7.ll
===
--- llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-7.ll
+++ /dev/null
@@ -1,23 +0,0 @@
-; RUN: llc -mtriple=aarch64-linux %s   -o - 2>&1 | \
-; RUN:   FileCheck %s --check-prefix=ASM
-; RUN: llc -mtriple=aarch64-linux %s -filetype=obj -o -  |  \
-; RUN:   llvm-readelf -S - | FileCheck %s --check-prefix=OBJ
-
-define dso_local i32 @f() #0 {
-entry:
-  ret i32 0
-}
-
-define dso_local i32 @g() #1 {
-entry:
-  ret i32 0
-}
-
-attributes #0 = { "sign-return-address"="non-leaf" }
-
-attributes #1 = { "branch-target-enforcement"="true" }
-
-; No common attribute, no note section
-; ASM: warning: not setting BTI in feature flags
-; ASM-NOT: .note.gnu.property
-; OBJ-NOT: .note.gnu.property
Index: llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-6.ll
===
--- llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-6.ll
+++ /dev/null
@@ -1,22 +0,0 @@
-; RUN: llc -mtriple=aarch64-linux %s   -o - | \
-; RUN:   FileCheck %s --check-prefix=ASM
-; RUN: llc -mtriple=aarch64-linux %s -filetype=obj -o - |  \
-; RUN:   llvm-readelf -S - | FileCheck %s --check-prefix=OBJ
-
-define dso_local i32 @f() #0 {
-entry:
-  ret i32 0
-}
-
-define dso_local i32 @g() #1 {
-entry:
-  ret i32 0
-}
-
-attributes #0 = { "sign-return-address"="non-leaf" }
-
-attributes #1 = { "sign-return-address"="none" }
-
-; No common attribute, no note section
-; ASM-NOT: .note.gnu.property
-; OBJ-NOT: .note.gnu.property
Index: llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-5.ll
===
--- llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-5.ll
+++ /dev/null
@@ -1,26 +0,0 @@
-; RUN: llc -mtriple=aarch64-linux %s   -o - 2>&1 | \
-; RUN:   FileCheck %s --check-prefix=ASM
-; RUN: llc -mtriple=aarch64-linux %s -filetype=obj -o -  |  \
-; RUN:   llvm-readelf --notes - | FileCheck %s --check-prefix=OBJ
-
-define dso_local i32 @f() #0 {
-entry:
-  ret i32 0
-}
-
-define dso_local i32 @g() #1 {
-entry:
-  ret i32 0
-}
-
-attributes #0 = { "branch-target-enforcement"="true" "sign-return-address"="non-leaf" }
-
-attributes #1 = { "sign-return-address"="all" }
-
-; Only the common atttribute (PAC)
-; ASM: warning: not setting BTI in feature flags
-; ASM:	.word	3221225472
-; ASM-NEXT:	.word	4
-; ASM-NEXT:	.word	2
-
-; OBJ: Properties: aarch64 feature: PAC
Index: llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-4.ll
===
--- llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-4.ll
+++ llvm/test/CodeGen/AArch64/note-gnu-property-pac-bti-4.ll
@@ -1,7 +1,5 @@
 ; RUN: llc -mtriple=aarch64-linux %s   -o - | \
 ; RUN:   FileCheck %s --check-prefix=ASM
-; RUN: llc -mtriple=aarch64-linux %s -filetype=obj -o - |  \
-; RUN:   llvm-readelf --notes - | FileCheck %s --check-prefix=OBJ
 
 define dso_local i32 @f() #0 {
 entry:
@@ -17,9 +15,12 @@
 
 attributes #1 = { "branch-target-enforcement"="true" }
 
-; Only the common atttribute (BTI)
-; ASM:	.word	3221225472
-; ASM-NEXT:	.word	4
-; ASM-NEXT:	.word	1
+!llvm.module.flags = !{!0, !1, !2, !3}
 
-; OBJ: Properties: aarch64 feature: BTI
+!0 = !{i32 1, !"branch-target-enforcement", i32 0}
+!1 = !{i32 1, !"sign-return-address", i32 0}
+!2 = !{i32 1, 

[PATCH] D88263: Sema: remove unnecessary parameter for SwiftName handling (NFCI)

2020-09-25 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/D88263/new/

https://reviews.llvm.org/D88263

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


[PATCH] D87989: [Flang][Driver] Add InputOutputTest frontend action with new -test-IO flag

2020-09-25 Thread Caroline via Phabricator via cfe-commits
CarolineConcatto updated this revision to Diff 294288.
CarolineConcatto added a comment.
Herald added subscribers: llvm-commits, hiraditya.
Herald added a project: LLVM.

Solve review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87989

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/lib/Driver/Types.cpp
  clang/test/Driver/immediate-options.c
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/include/flang/Frontend/FrontendAction.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/include/flang/FrontendTool/Utils.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInstance.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendAction.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/FrontendOptions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Flang-Driver/driver-help-hidden.f90
  flang/test/Flang-Driver/driver-help.f90
  flang/test/Flang-Driver/emit-obj.f90
  flang/test/Frontend/Inputs/hello-world.f90
  flang/test/Frontend/input-output-file.f90
  flang/test/Frontend/multiple-input-files.f90
  flang/test/lit.cfg.py
  flang/tools/flang-driver/fc1_main.cpp
  flang/unittests/Frontend/CMakeLists.txt
  flang/unittests/Frontend/CompilerInstanceTest.cpp
  flang/unittests/Frontend/InputOutputTest.cpp
  llvm/lib/Option/OptTable.cpp

Index: llvm/lib/Option/OptTable.cpp
===
--- llvm/lib/Option/OptTable.cpp
+++ llvm/lib/Option/OptTable.cpp
@@ -639,6 +639,7 @@
   continue;
 
 unsigned Flags = getInfo(Id).Flags;
+
 if (FlagsToInclude && !(Flags & FlagsToInclude))
   continue;
 if (Flags & FlagsToExclude)
Index: flang/unittests/Frontend/InputOutputTest.cpp
===
--- /dev/null
+++ flang/unittests/Frontend/InputOutputTest.cpp
@@ -0,0 +1,65 @@
+//===- unittests/Frontend/OutputStreamTest.cpp --- FrontendAction tests --===//
+//
+// 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 "flang/Frontend/CompilerInstance.h"
+#include "flang/Frontend/CompilerInvocation.h"
+#include "flang/Frontend/FrontendOptions.h"
+#include "flang/FrontendTool/Utils.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/raw_ostream.h"
+#include "gtest/gtest.h"
+
+using namespace Fortran::frontend;
+#include 
+
+namespace {
+
+TEST(FrontendOutputTests, TestInputOutputStreamOwned) {
+  // 1. Prepare the input file to be used by IO
+  // Create the file to be used by AllSources
+  // Flang function 'FortranAllSources.Open' needs a physical file
+  // and the full path to work with
+  std::string inputFilename = "io-file-test.f";
+  std::error_code ec;
+  std::unique_ptr os{
+  new llvm::raw_fd_ostream(inputFilename, ec, llvm::sys::fs::OF_None)};
+  if (ec)
+llvm::errs() << "Fail to create the file need by the test";
+  *(os) << "End Program arithmetic";
+  os.reset();
+  std::string getFileFullPath = std::filesystem::current_path().c_str();
+  getFileFullPath = getFileFullPath + "/" + inputFilename;
+
+  // 2. Prepare the compiler (Invocation + Instance)
+  CompilerInstance compInst;
+  compInst.CreateDiagnostics();
+  auto invocation = std::make_shared();
+  invocation->GetFrontendOpts().programAction_ = InputOutputTest;
+  compInst.SetInvocation(std::move(invocation));
+  compInst.GetFrontendOpts().inputs_.push_back(
+  FrontendInputFile(/*File=*/getFileFullPath, Language::Fortran));
+
+  // 3. Set-up the output stream. Using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst.SetOutputStream(std::move(outputFileStream));
+
+  // 4. Run the earlier defined FrontendAction
+  bool success = ExecuteCompilerInvocation(&compInst);
+
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .startswith("End Program arithmetic"));
+
+  // 5. Remove files
+  compInst.ClearOutputFiles(/*EraseFiles=*/false);
+}
+} // namespace
\ No newline at end of file
Index: flang/unittests/Frontend/CompilerInstanceTest.cpp
===
--- flang/unittests/Frontend/CompilerInstanceTest.cpp
+++ flang/unittests/Frontend/CompilerInstanceTe

[PATCH] D87449: [clang-tidy] Add new check for SEI CERT rule SIG30-C.

2020-09-25 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added inline comments.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:31
+static bool isSystemCall(const FunctionDecl *FD) {
+  // This check does not work with function calls in std namespace.
+  if (!FD->isGlobal() || FD->isInStdNamespace())

Why? In //C++// we have everything in `std` namespace, such as `std::signal()`, 
`std::abort()` or `std::_Exit()`. In `C++` the general rule is to use them 
instead of the global //C// variants.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:35
+  // It is assumed that the function has no other re-declaration that is not
+  // in a system header. Otherwise this may produce wrong result.
+  return FD->getASTContext().getSourceManager().isInSystemHeader(

The assumption is basically right, we do not repeat declarations from system 
headers but maybe we could loop over the redeclaration chain.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:40
+
+static bool isAllowedSystemCall(const FunctionDecl *FD) {
+  if (!FD->getIdentifier())

The name suggests that this function checks for both //system call// and 
//allowed call//. I would either rename this function to simply 
`isAllowedCall()` or at least put an assertion to the beginning: 
`assert(isSystemCall(FD));`.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:44
+  const StringRef N = FD->getName();
+  if (N == AbortFun || N == ExitFun || N == QuickExitFun || N == SignalFun)
+return true;

Maybe you could use `IdentifierInfo` instead of string comparisons.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:81
+  callExpr(IsSignalFunction, HandlerAsSecondArg).bind("register_call"),
+  this);
+}

More readable would be this way:
```
const auto HandlerExpr = 
declRefExpr(hasDeclaration(functionDecl().bind("handler_decl")),
   unless(isExpandedFromMacro("SIG_IGN")),
   unless(isExpandedFromMacro("SIG_DFL")))
  .bind("handler_expr");
Finder->addMatcher(
   callExpr(IsSignalFunction, hasArgument(1, 
HandlerExpr)).bind("register_call"),
   this);
```



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:95
+  std::deque> CalledFunctions{
+  {HandlerDecl, HandlerExpr}};
+

Do we really need to store `FunctionDecl` in the map? The whole code would be 
much simpler if you only store the call expression and the retrieve the callee 
declaration once at the beginning of the loop body. Beside simplicity this 
would also reduce the memory footprint and surely not increase the execution 
time.



Comment at: clang-tools-extra/docs/clang-tidy/checks/cert-sig30-c.rst:1-17
+.. title:: clang-tidy - cert-sig30-c
+
+cert-sig30-c
+
+
+Finds functions registered as signal handlers that call non asynchronous-safe
+functions. User functions called from the handlers are checked too, as far as

Please add at least one minimal code example. (E.g. from the tests.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87449

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


[PATCH] D88295: [Sema] Fix volatile check when test if a return object can be implicitly move

2020-09-25 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added a comment.

(This patch was split out from D88220  at my 
request.)

@nullptr.cpp, please add the regression test from https://godbolt.org/z/5EfK99 
.  After a test is added, this patch LGTM (but will need approval also from 
someone else).

Your summary makes it sound as if Clang's [current/old] behavior is correct in 
C++14 and C++17; but I think it is wrong in any version. I don't see anything 
in CWG1579  that affects 
volatile, and I see the same phrase "in a return statement in a function with a 
class return type, when the expression is the name of a non-volatile automatic 
object..." in both N3337 (C++11) and N4140 (C++14).  So, I think your summary 
is confusing/wrong, but I think your //code patch// is absolutely correct: the 
volatile check should be moved up unconditionally, as you have done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88295

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


[PATCH] D87989: [Flang][Driver] Add InputOutputTest frontend action with new -test-IO flag

2020-09-25 Thread Caroline via Phabricator via cfe-commits
CarolineConcatto marked 23 inline comments as done.
CarolineConcatto added a comment.

@awarzynski thank you for the review. 
It is a big patch to review at once.
I accepted almost all of your changes.




Comment at: flang/test/Flang-Driver/emit-obj.f90:2
 ! RUN: not %flang-new  %s 2>&1 | FileCheck %s --check-prefix=ERROR-IMPLICIT
-! RUN: not %flang-new  -emit-obj %s 2>&1 | FileCheck %s 
--check-prefix=ERROR-EXPLICIT
 ! RUN: not %flang-new  -fc1 -emit-obj %s 2>&1 | FileCheck %s 
--check-prefix=ERROR-FC1

awarzynski wrote:
> Why is this line deleted? `flang-new -emit-obj` should still fail, right?
I remove this because the text does not apply any more
! ERROR-IMPLICIT: error: unknown argument: '-o'


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87989

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


[PATCH] D88296: [clang-format] De-duplicate includes with leading or trailing whitespace.

2020-09-25 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius created this revision.
curdeius added a reviewer: MyDeveloperDay.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
curdeius requested review of this revision.

This fixes PR46555.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88296

Files:
  clang/lib/Format/Format.cpp
  clang/unittests/Format/SortIncludesTest.cpp


Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -266,12 +266,19 @@
 sort(" #include \"a.h\"\n"
  "  #include \"c.h\"\n"
  "   #include \"b.h\"\n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   " #include \"a.h\"\n"));
+}
+
+TEST_F(SortIncludesTest, TrailingWhitespace) {
   EXPECT_EQ("#include \"a.h\"\n"
 "#include \"b.h\"\n"
 "#include \"c.h\"\n",
-sort("# include \"a.h\"\n"
- "#  include \"c.h\"\n"
- "#   include \"b.h\"\n"));
+sort("#include \"a.h\" \n"
+ "#include \"c.h\"  \n"
+ "#include \"b.h\"   \n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   "#include \"a.h\" \n"));
 }
 
 TEST_F(SortIncludesTest, GreaterInComment) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2160,7 +2160,8 @@
   // Deduplicate #includes.
   Indices.erase(std::unique(Indices.begin(), Indices.end(),
 [&](unsigned LHSI, unsigned RHSI) {
-  return Includes[LHSI].Text == 
Includes[RHSI].Text;
+  return Includes[LHSI].Text.trim() ==
+ Includes[RHSI].Text.trim();
 }),
 Indices.end());
 


Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -266,12 +266,19 @@
 sort(" #include \"a.h\"\n"
  "  #include \"c.h\"\n"
  "   #include \"b.h\"\n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   " #include \"a.h\"\n"));
+}
+
+TEST_F(SortIncludesTest, TrailingWhitespace) {
   EXPECT_EQ("#include \"a.h\"\n"
 "#include \"b.h\"\n"
 "#include \"c.h\"\n",
-sort("# include \"a.h\"\n"
- "#  include \"c.h\"\n"
- "#   include \"b.h\"\n"));
+sort("#include \"a.h\" \n"
+ "#include \"c.h\"  \n"
+ "#include \"b.h\"   \n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   "#include \"a.h\" \n"));
 }
 
 TEST_F(SortIncludesTest, GreaterInComment) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2160,7 +2160,8 @@
   // Deduplicate #includes.
   Indices.erase(std::unique(Indices.begin(), Indices.end(),
 [&](unsigned LHSI, unsigned RHSI) {
-  return Includes[LHSI].Text == Includes[RHSI].Text;
+  return Includes[LHSI].Text.trim() ==
+ Includes[RHSI].Text.trim();
 }),
 Indices.end());
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87449: [clang-tidy] Add new check for SEI CERT rule SIG30-C

2020-09-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:31-33
+  // This check does not work with function calls in std namespace.
+  if (!FD->isGlobal() || FD->isInStdNamespace())
+return false;

baloghadamsoftware wrote:
> Why? In //C++// we have everything in `std` namespace, such as 
> `std::signal()`, `std::abort()` or `std::_Exit()`. In `C++` the general rule 
> is to use them instead of the global //C// variants.
This seems incorrect to me. `::std::quick_exit()` resolves to `::quick_exit()`, 
so why should that call be ignored as a system call? I would assume that 
anything in namespace `std` is a system call. It's a bit questionable whether a 
user-written template specialization in namespace `std` should be handled that 
way, but I think that's still reasonable to consider as a system call.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:34
+return false;
+  // It is assumed that the function has no other re-declaration that is not
+  // in a system header. Otherwise this may produce wrong result.

re-declaration -> redeclaration



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:41
+static bool isAllowedSystemCall(const FunctionDecl *FD) {
+  if (!FD->getIdentifier())
+return true;

A function without an identifier is not a system call, so I would have expected 
this to return `false` based on the function name.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:43
+return true;
+  const StringRef N = FD->getName();
+  if (N == AbortFun || N == ExitFun || N == QuickExitFun || N == SignalFun)

We don't typically use top-level `const` in the project, so this can be 
dropped. Same comment applies elsewhere in the patch.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:44-46
+  if (N == AbortFun || N == ExitFun || N == QuickExitFun || N == SignalFun)
+return true;
+  return false;

baloghadamsoftware wrote:
> Maybe you could use `IdentifierInfo` instead of string comparisons.
The logic isn't quite correct here as this will claim to be an allowed system 
call:
```
namespace awesome {
  void quick_exit(void); // Considers this to be a system call
}
```
You should be checking the namespace as well.

Also, this list is very incomplete depending on your platform. The CERT rule 
lists a whole bunch of POSIX functions that are required to be async signal 
safe. I am guessing Microsoft likely has a list somewhere as well. I worry 
about the number of false positives this check will issue if we don't at least 
consider POSIX (where signals are much, much more useful than in strictly 
conforming C).



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:73
+  const auto IsSignalFunction =
+  callee(functionDecl(hasName(SignalFun), parameterCountIs(2)));
+  const auto HandlerAsSecondArg = hasArgument(

Similar issue here with finding functions in the wrong namespace.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:117-118
+  diag(FunctionCall->getBeginLoc(),
+   "'%0' is considered as non asynchronous-safe and "
+   "should not be called from a signal handler")
+  << FunctionToCheck->getName();

How about: `'%0' may not be asynchronous-safe; calling it from a signal handler 
may be dangerous`?



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:135
+[&CalledFunctions](const FunctionDecl *FD, const CallExpr *CE) {
+  CalledFunctions.push_back(std::make_pair(FD, CE));
+}};

`emplace_back(FD, CE)`?



Comment at: clang-tools-extra/docs/clang-tidy/checks/cert-sig30-c.rst:13
+(for ``signal`` there are additional conditions that are not checked).
+Every other system call is considered as non asynchronous-safe by the checker.
+

I would document this as: `Any function that cannot be determined to be an 
asynchronous-safe function call is assumed to be non-asynchronous-safe by the 
checker, including function calls for which only the declaration of the called 
function is visible.`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87449

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


[PATCH] D88297: [clangd] Trivial setter support when moving items to fields

2020-09-25 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: sammccall, kadircet, hokein.
Herald added subscribers: cfe-commits, usaxena95, arphaman.
Herald added a project: clang.
njames93 requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.

Extend the Trivial setter documentation to support cases where the value is 
moved into a field using `std::move`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88297

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -698,6 +698,26 @@
  HI.Parameters->back().Name = "v";
  HI.AccessSpecifier = "public";
}},
+  {// Setter (move)
+   R"cpp(
+  namespace std { template T&& move(T&& t); }
+  struct X { int Y; void [[^setY]](float v) { Y = std::move(v); } };
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "setY";
+ HI.Kind = index::SymbolKind::InstanceMethod;
+ HI.NamespaceScope = "";
+ HI.Definition = "void setY(float v)";
+ HI.LocalScope = "X::";
+ HI.Documentation = "Trivial setter for `Y`.";
+ HI.Type = "void (float)";
+ HI.ReturnType = "void";
+ HI.Parameters.emplace();
+ HI.Parameters->emplace_back();
+ HI.Parameters->back().Type = "float";
+ HI.Parameters->back().Name = "v";
+ HI.AccessSpecifier = "public";
+   }},
   {// Field type initializer.
R"cpp(
   struct X { int x = 2; };
@@ -802,8 +822,8 @@
  HI.Type = "int";
  HI.AccessSpecifier = "public";
}},
-   {// No crash on InitListExpr.
-R"cpp(
+  {// No crash on InitListExpr.
+   R"cpp(
   struct Foo {
 int a[10];
   };
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -455,6 +455,21 @@
   } else {
 return llvm::None;
   }
+
+  // Detect the case when the item is moved into the field.
+  if (auto *CE = llvm::dyn_cast(RHS->IgnoreCasts())) {
+// Make sure we get the version of move with 1 arg, the other is for moving
+// ranges.
+if (CE->getNumArgs() != 1)
+  return llvm::None;
+auto *ND = llvm::dyn_cast(CE->getCalleeDecl());
+if (!ND)
+  return llvm::None;
+if (ND->getName() != "move" || !ND->isInStdNamespace())
+  return llvm::None;
+RHS = CE->getArg(0);
+  }
+
   auto *DRE = llvm::dyn_cast(RHS->IgnoreCasts());
   if (!DRE || DRE->getDecl() != Arg)
 return llvm::None;


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -698,6 +698,26 @@
  HI.Parameters->back().Name = "v";
  HI.AccessSpecifier = "public";
}},
+  {// Setter (move)
+   R"cpp(
+  namespace std { template T&& move(T&& t); }
+  struct X { int Y; void [[^setY]](float v) { Y = std::move(v); } };
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "setY";
+ HI.Kind = index::SymbolKind::InstanceMethod;
+ HI.NamespaceScope = "";
+ HI.Definition = "void setY(float v)";
+ HI.LocalScope = "X::";
+ HI.Documentation = "Trivial setter for `Y`.";
+ HI.Type = "void (float)";
+ HI.ReturnType = "void";
+ HI.Parameters.emplace();
+ HI.Parameters->emplace_back();
+ HI.Parameters->back().Type = "float";
+ HI.Parameters->back().Name = "v";
+ HI.AccessSpecifier = "public";
+   }},
   {// Field type initializer.
R"cpp(
   struct X { int x = 2; };
@@ -802,8 +822,8 @@
  HI.Type = "int";
  HI.AccessSpecifier = "public";
}},
-   {// No crash on InitListExpr.
-R"cpp(
+  {// No crash on InitListExpr.
+   R"cpp(
   struct Foo {
 int a[10];
   };
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -455,6 +455,21 @@
   } else {
 return llvm::None;
   }
+
+  // Detect the case when the item is moved into the field.
+  if (auto *CE = llvm::dyn_cast(RHS->IgnoreCasts())) {
+// Make sure we get the version of move with 1 arg, the other is for moving
+// ranges.
+if (CE->getNumArgs() != 1)
+  return llvm::None;
+auto *ND = llvm::dyn_cast(CE->getCalleeDecl());
+if (!ND)
+  return llvm::None;
+if (ND->getName() != "move"

[PATCH] D88296: [clang-format] De-duplicate includes with leading or trailing whitespace.

2020-09-25 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 294291.
curdeius added a comment.

- Ooops. Revert unwanted test changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88296

Files:
  clang/lib/Format/Format.cpp
  clang/unittests/Format/SortIncludesTest.cpp


Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -272,6 +272,19 @@
 sort("# include \"a.h\"\n"
  "#  include \"c.h\"\n"
  "#   include \"b.h\"\n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   " #include \"a.h\"\n"));
+}
+
+TEST_F(SortIncludesTest, TrailingWhitespace) {
+  EXPECT_EQ("#include \"a.h\"\n"
+"#include \"b.h\"\n"
+"#include \"c.h\"\n",
+sort("#include \"a.h\" \n"
+ "#include \"c.h\"  \n"
+ "#include \"b.h\"   \n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   "#include \"a.h\" \n"));
 }
 
 TEST_F(SortIncludesTest, GreaterInComment) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2160,7 +2160,8 @@
   // Deduplicate #includes.
   Indices.erase(std::unique(Indices.begin(), Indices.end(),
 [&](unsigned LHSI, unsigned RHSI) {
-  return Includes[LHSI].Text == 
Includes[RHSI].Text;
+  return Includes[LHSI].Text.trim() ==
+ Includes[RHSI].Text.trim();
 }),
 Indices.end());
 


Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -272,6 +272,19 @@
 sort("# include \"a.h\"\n"
  "#  include \"c.h\"\n"
  "#   include \"b.h\"\n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   " #include \"a.h\"\n"));
+}
+
+TEST_F(SortIncludesTest, TrailingWhitespace) {
+  EXPECT_EQ("#include \"a.h\"\n"
+"#include \"b.h\"\n"
+"#include \"c.h\"\n",
+sort("#include \"a.h\" \n"
+ "#include \"c.h\"  \n"
+ "#include \"b.h\"   \n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   "#include \"a.h\" \n"));
 }
 
 TEST_F(SortIncludesTest, GreaterInComment) {
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -2160,7 +2160,8 @@
   // Deduplicate #includes.
   Indices.erase(std::unique(Indices.begin(), Indices.end(),
 [&](unsigned LHSI, unsigned RHSI) {
-  return Includes[LHSI].Text == Includes[RHSI].Text;
+  return Includes[LHSI].Text.trim() ==
+ Includes[RHSI].Text.trim();
 }),
 Indices.end());
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D88296: [clang-format] De-duplicate includes with leading or trailing whitespace.

2020-09-25 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

Finally I've opted for creating a small revision just fixing this particular 
bug report.
Mind however that the problem is a bit more complex and to solve all possible 
cases we would need to first reformat the source code, then sort the includes 
and then again, possibly reformat parts of the source code modified by sorting, 
so that the comments get re-aligned etc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88296

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


[PATCH] D88140: [clang-tidy] Check for sigaction in cert-sig30-c.

2020-09-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:91
+  hasObjectExpression(ignoringParenImpCasts(declRefExpr(
+  anyOf(hasType(recordDecl(hasName("sigaction"))),
+hasType(pointsTo(recordDecl(hasName("sigaction";

You should be checking for the fully-qualified name so that this doesn't trip 
it up:
```
namespace awesome {
struct sigaction {
  const char *terrible = "haha";
};
}
```



Comment at: clang-tools-extra/clang-tidy/cert/SignalHandlerCheck.cpp:92
+  anyOf(hasType(recordDecl(hasName("sigaction"))),
+hasType(pointsTo(recordDecl(hasName("sigaction";
+  auto HandlerMember = member(hasName("sa_handler"));

I'd like to see a test case that this works properly with references in C++ (in 
addition to pointers).



Comment at: clang-tools-extra/test/clang-tidy/checkers/cert-sig30-c.cpp:152
+  SA->sa_sigaction = sigaction_handler5;
+}

I'd like to see a test case that shows this works if the `sigaction` object is 
within another structure. e.g.,
```
struct foo {
  struct sigaction act;
};

void test(void) {
  struct foo f;
  f.act.sa_handler = handler_sigaction5;
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88140

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


[PATCH] D88298: Fix MaterializeTemporaryExpr's type when its an incomplete array.

2020-09-25 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.
erichkeane added reviewers: rsmith, rjmccall.
erichkeane requested review of this revision.

Like the VarDecl that gets its type updated based on an init-list, this
patch corrects the MaterializeTemporaryExpr's type to make sure it isn't
creating an incomplete type, which leads to a handful of CodeGen crashes
(see PR 47636).

Based on @rsmith 's comments on D88236 


https://reviews.llvm.org/D88298

Files:
  clang/lib/Sema/SemaInit.cpp
  clang/test/AST/pr47636.cpp
  clang/test/CodeGenCXX/pr47636.cpp


Index: clang/test/CodeGenCXX/pr47636.cpp
===
--- clang/test/CodeGenCXX/pr47636.cpp
+++ clang/test/CodeGenCXX/pr47636.cpp
@@ -8,3 +8,15 @@
   // CHECK: @_ZZ3foovE10intu_rvref = internal constant [4 x i32]* 
@_ZGRZ3foovE10intu_rvref_
   // CHECK: @_ZGRZ3foovE10intu_rvref_ = internal constant [4 x i32] [i32 1, 
i32 2, i32 3, i32 4]
 }
+
+// Example given on review, ensure this doesn't crash as well.
+constexpr int f() {
+  // CHECK: i32 @_Z1fv()
+  int(&&intu_rvref)[]{1, 2, 3, 4};
+  // CHECK: %{{.*}} = alloca [4 x i32]*
+  return intu_rvref[2];
+}
+
+void use_f() {
+  int i = f();
+}
Index: clang/test/AST/pr47636.cpp
===
--- /dev/null
+++ clang/test/AST/pr47636.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -fsyntax-only %s -ast-dump | FileCheck %s
+
+int(&&intu_rvref)[] {1,2,3,4};
+// CHECK: VarDecl 0x[[GLOB_ADDR:[0-9a-f]+]] {{.*}} intu_rvref 'int (&&)[4]' 
listinit
+// CHECK-NEXT: ExprWithCleanups {{.*}} 'int [4]' xvalue
+// CHECK-NEXT: MaterializeTemporaryExpr {{.*}} 'int [4]' xvalue extended by 
Var 0x[[GLOB_ADDR]] 'intu_rvref' 'int (&&)[4]'
+// CHECK-NEXT: InitListExpr {{.*}} 'int [4]'
+
+// CHECK: FunctionDecl {{.*}} static_const
+void static_const() {
+  static const int(&&intu_rvref)[] {1,2,3,4};
+  // CHECK: VarDecl 0x[[STATIC_ADDR:[0-9a-f]+]] {{.*}} intu_rvref 'const int 
(&&)[4]' static listinit
+  // CHECK-NEXT: ExprWithCleanups {{.*}} 'const int [4]' xvalue
+  // CHECK-NEXT: MaterializeTemporaryExpr {{.*}} 'const int [4]' xvalue 
extended by Var 0x[[STATIC_ADDR]] 'intu_rvref' 'const int (&&)[4]'
+  // CHECK-NEXT: InitListExpr {{.*}} 'const int [4]'
+}
+
+// CHECK: FunctionDecl {{.*}} const_expr
+constexpr int const_expr() {
+  int(&&intu_rvref)[]{1, 2, 3, 4};
+  // CHECK: VarDecl 0x[[CE_ADDR:[0-9a-f]+]] {{.*}} intu_rvref 'int (&&)[4]' 
listinit
+  // CHECK-NEXT: ExprWithCleanups {{.*}} 'int [4]' xvalue
+  // CHECK-NEXT: MaterializeTemporaryExpr {{.*}} 'int [4]' xvalue extended by 
Var 0x[[CE_ADDR]] 'intu_rvref' 'int (&&)[4]'
+  // CHECK-NEXT: InitListExpr {{.*}} 'int [4]'
+  return intu_rvref[0];
+}
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -8058,9 +8058,21 @@
   if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
 return ExprError();
 
+  QualType MTETy = Step->Type;
+
+  // When this is an incomplete array type (such as when this is
+  // initializing an array of unknown bounds from an init list), use THAT
+  // type instead so that we propogate the array bounds.
+  if (MTETy->isIncompleteArrayType() &&
+  !CurInit.get()->getType()->isIncompleteArrayType() &&
+  S.Context.hasSameType(
+  MTETy->getPointeeOrArrayElementType(),
+  CurInit.get()->getType()->getPointeeOrArrayElementType()))
+MTETy = CurInit.get()->getType();
+
   // Materialize the temporary into memory.
   MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
-  Step->Type, CurInit.get(), 
Entity.getType()->isLValueReferenceType());
+  MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
   CurInit = MTE;
 
   // If we're extending this temporary to automatic storage duration -- we


Index: clang/test/CodeGenCXX/pr47636.cpp
===
--- clang/test/CodeGenCXX/pr47636.cpp
+++ clang/test/CodeGenCXX/pr47636.cpp
@@ -8,3 +8,15 @@
   // CHECK: @_ZZ3foovE10intu_rvref = internal constant [4 x i32]* @_ZGRZ3foovE10intu_rvref_
   // CHECK: @_ZGRZ3foovE10intu_rvref_ = internal constant [4 x i32] [i32 1, i32 2, i32 3, i32 4]
 }
+
+// Example given on review, ensure this doesn't crash as well.
+constexpr int f() {
+  // CHECK: i32 @_Z1fv()
+  int(&&intu_rvref)[]{1, 2, 3, 4};
+  // CHECK: %{{.*}} = alloca [4 x i32]*
+  return intu_rvref[2];
+}
+
+void use_f() {
+  int i = f();
+}
Index: clang/test/AST/pr47636.cpp
===
--- /dev/null
+++ clang/test/AST/pr47636.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -fsyntax-only %s -ast-dump | FileCheck %s
+
+int(&&intu_rvref)[] {1,2,3,4};
+// CHECK: VarDecl 0x[[GLOB_ADDR:[0-9a-f]+]] {{.*}} intu_rvref 'int (&&)[4]' listinit
+// CHECK-NEXT

[PATCH] D88298: Fix MaterializeTemporaryExpr's type when its an incomplete array.

2020-09-25 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaInit.cpp:8061
 
+  QualType MTETy = Step->Type;
+

It seemed less intrusive/more reliable to fix this during the init-process, and 
perhaps would fix a few additional cases.  The VarDecl gets updated by the 
caller of this, and updating both the ExprWtihCleanups and MTE seemed 
error-prone.


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

https://reviews.llvm.org/D88298

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


[PATCH] D72218: [clang-tidy] new altera kernel name restriction check

2020-09-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/altera/KernelNameRestrictionCheck.cpp:53
+void KernelNameRestrictionCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  PP->addPPCallbacks(

You can elide the identifier `ModuleExpanderPP` since it's not used in the call.



Comment at: 
clang-tools-extra/clang-tidy/altera/KernelNameRestrictionCheck.cpp:74-76
+StringRef FileName = FilePath.substr(FilePath.find_last_of("/\\") + 1);
+if (FileName.equals_lower("kernel.cl") ||
+FileName.equals_lower("verilog.cl") || 
FileName.equals_lower("vhdl.cl"))

Rather than do path manipulations manually, I'd rather use 
`llvm::sys::path::filename()`



Comment at: 
clang-tools-extra/clang-tidy/altera/KernelNameRestrictionCheck.cpp:78
+  Check.diag(ID.Loc,
+ "The imported kernel source file is named 'kernel.cl',"
+ "'Verilog.cl', or 'VHDL.cl', which could cause compilation "

clang-tidy diagnostics are not meant to be grammatically correct, so I think 
this should be something more like: `including '%0' may cause additional 
compilation errors due to the name of the file; consider renaming the included 
file` and pass in the name of the file being included.



Comment at: 
clang-tools-extra/clang-tidy/altera/KernelNameRestrictionCheck.cpp:86-88
+  StringRef FileName = FilePath.substr(FilePath.find_last_of("/\\") + 1);
+  if (FileName.equals_lower("kernel.cl") ||
+  FileName.equals_lower("verilog.cl") || FileName.equals_lower("vhdl.cl"))

Similar here about using filesystem utilities.



Comment at: 
clang-tools-extra/clang-tidy/altera/KernelNameRestrictionCheck.cpp:90
+Check.diag(SM.getLocForStartOfFile(SM.getMainFileID()),
+   "Naming your OpenCL kernel source file 'kernel.cl', 
'Verilog.cl'"
+   ", or 'VHDL.cl' could cause compilation errors.");

Similar here, I would word it something like: `compiling a source file named 
'%0' may result in additional compilation errors due to the name of the file; 
consider renaming the source file`



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/altera-kernel-name-restriction.cpp:40
+// The files can still have the forbidden names in them, so long as they're 
not the entire file name
+#include "some_kernel.cl"
+#include "other_Verilog.cl"

I assume it's also fine if the user does something really weird like: `#include 
"kernel.cl/foo.h"` ?


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

https://reviews.llvm.org/D72218

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


[PATCH] D88299: [clang-format] Add MacroUnexpander.

2020-09-25 Thread Manuel Klimek via Phabricator via cfe-commits
klimek created this revision.
klimek added a reviewer: sammccall.
Herald added subscribers: cfe-commits, mgorny.
Herald added a project: clang.
klimek requested review of this revision.

MacroUnexpander applies the structural formatting of expanded lines into
UnwrappedLines to the corresponding unexpanded macro calls, resulting in
UnwrappedLines for the macro calls the user typed.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88299

Files:
  clang/lib/Format/CMakeLists.txt
  clang/lib/Format/FormatToken.h
  clang/lib/Format/MacroUnexpander.cpp
  clang/lib/Format/Macros.h
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/MacroUnexpanderTest.cpp

Index: clang/unittests/Format/MacroUnexpanderTest.cpp
===
--- /dev/null
+++ clang/unittests/Format/MacroUnexpanderTest.cpp
@@ -0,0 +1,636 @@
+#include "../../lib/Format/Macros.h"
+#include "../../lib/Format/UnwrappedLineParser.h"
+#include "TestLexer.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace format {
+namespace {
+
+using UnexpandedMap = std::map>;
+
+class Expansion {
+public:
+  Expansion(TestLexer &Lex, MacroExpander &Macros) : Lex(Lex), Macros(Macros) {}
+
+  TokenList
+  expand(llvm::StringRef Name,
+ const SmallVector, 1> &Args) {
+auto *ID = Lex.id(Name);
+auto UnexpandedLine = std::make_unique();
+UnexpandedLine->Tokens.push_back(ID);
+if (!Args.empty()) {
+  UnexpandedLine->Tokens.push_back(Lex.id("("));
+  for (auto I = Args.begin(), E = Args.end(); I != E; ++I) {
+if (I != Args.begin())
+  UnexpandedLine->Tokens.push_back(Lex.id(","));
+UnexpandedLine->Tokens.insert(UnexpandedLine->Tokens.end(), I->begin(),
+  I->end());
+  }
+  UnexpandedLine->Tokens.push_back(Lex.id(")"));
+}
+Unexpanded[ID] = std::move(UnexpandedLine);
+
+auto Expanded = uneof(Macros.expand(ID, Args));
+Tokens.append(Expanded.begin(), Expanded.end());
+
+TokenList UnexpandedTokens;
+for (const UnwrappedLineNode &Node : Unexpanded[ID]->Tokens) {
+  UnexpandedTokens.push_back(Node.Tok);
+}
+return UnexpandedTokens;
+  }
+
+  TokenList expand(llvm::StringRef Name,
+   const std::vector &Args = {}) {
+return expand(Name, lexArgs(Args));
+  }
+
+  const UnexpandedMap &getUnexpanded() const { return Unexpanded; }
+
+  const TokenList &getTokens() const { return Tokens; }
+
+private:
+  llvm::SmallVector
+  lexArgs(const std::vector &Args) {
+llvm::SmallVector Result;
+for (const auto &Arg : Args) {
+  Result.push_back(uneof(Lex.lex(Arg)));
+}
+return Result;
+  }
+  std::map> Unexpanded;
+  llvm::SmallVector Tokens;
+  TestLexer &Lex;
+  MacroExpander &Macros;
+};
+
+struct Chunk {
+  Chunk(llvm::ArrayRef Tokens)
+  : Tokens(Tokens.begin(), Tokens.end()) {}
+  Chunk(llvm::ArrayRef Children)
+  : Children(Children.begin(), Children.end()) {}
+  llvm::SmallVector Tokens;
+  llvm::SmallVector Children;
+};
+
+bool tokenMatches(const FormatToken *Left, const FormatToken *Right) {
+  if (Left->getType() == Right->getType() &&
+  Left->TokenText == Right->TokenText)
+return true;
+  llvm::dbgs() << Left->TokenText << " != " << Right->TokenText << "\n";
+  return false;
+}
+
+struct Matcher {
+  Matcher(const TokenList &Tokens) : Tokens(Tokens), It(this->Tokens.begin()) {}
+
+  Chunk consume(const TokenList &Tokens) {
+TokenList Result;
+for (const FormatToken *Token : Tokens) {
+  assert(tokenMatches(*It, Token));
+  Result.push_back(*It);
+  ++It;
+}
+return Chunk(Result);
+  }
+
+  TokenList Tokens;
+  TokenList::iterator It;
+};
+
+UnexpandedMap mergeUnexpanded(const UnexpandedMap &M1,
+  const UnexpandedMap &M2) {
+  UnexpandedMap Result;
+  for (const auto &KV : M1) {
+Result[KV.first] = std::make_unique(*KV.second);
+  }
+  for (const auto &KV : M2) {
+Result[KV.first] = std::make_unique(*KV.second);
+  }
+  return Result;
+}
+
+class MacroUnexpanderTest : public ::testing::Test {
+public:
+  std::unique_ptr
+  create(const std::vector &MacroDefinitions) {
+return std::make_unique(MacroDefinitions,
+   Lex.SourceMgr.get(), Lex.Style,
+   Lex.Allocator, Lex.IdentTable);
+  }
+
+  UnwrappedLine line(llvm::ArrayRef Tokens) {
+UnwrappedLine Result;
+for (FormatToken *Tok : Tokens) {
+  Result.Tokens.push_back(UnwrappedLineNode(Tok));
+}
+return Result;
+  }
+
+  UnwrappedLine line(llvm::StringRef Text) { return line({lex(Text)}); }
+
+  UnwrappedLine line(llvm::ArrayRef Chunks) {
+UnwrappedLine Result;
+for (const Chunk &Chunk : Chunks) {
+  Result.Tokens.

[PATCH] D87946: [OpenMP] Add Location Fields to Libomptarget Runtime for Debugging

2020-09-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 294296.
jhuber6 added a comment.

Added definition for the ident_t struct from kmp.h along with a method to 
extract the source location information. Checking the target outcome now prints 
the file location if ident_t location is available.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87946

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/capturing_in_templates.cpp
  clang/test/OpenMP/declare_target_link_codegen.cpp
  clang/test/OpenMP/distribute_codegen.cpp
  clang/test/OpenMP/distribute_firstprivate_codegen.cpp
  clang/test/OpenMP/distribute_lastprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_firstprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_if_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_lastprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_num_threads_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_private_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_proc_bind_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_reduction_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_firstprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_if_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_lastprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_num_threads_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_private_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_proc_bind_codegen.cpp
  clang/test/OpenMP/distribute_private_codegen.cpp
  clang/test/OpenMP/distribute_simd_codegen.cpp
  clang/test/OpenMP/distribute_simd_firstprivate_codegen.cpp
  clang/test/OpenMP/distribute_simd_lastprivate_codegen.cpp
  clang/test/OpenMP/distribute_simd_private_codegen.cpp
  clang/test/OpenMP/distribute_simd_reduction_codegen.cpp
  clang/test/OpenMP/nvptx_lambda_capturing.cpp
  clang/test/OpenMP/nvptx_lambda_pointer_capturing.cpp
  clang/test/OpenMP/nvptx_target_requires_unified_shared_memory.cpp
  clang/test/OpenMP/openmp_offload_codegen.cpp
  clang/test/OpenMP/target_codegen.cpp
  clang/test/OpenMP/target_data_codegen.cpp
  clang/test/OpenMP/target_data_use_device_addr_codegen.cpp
  clang/test/OpenMP/target_defaultmap_codegen.cpp
  clang/test/OpenMP/target_device_codegen.cpp
  clang/test/OpenMP/target_enter_data_codegen.cpp
  clang/test/OpenMP/target_enter_data_depend_codegen.cpp
  clang/test/OpenMP/target_exit_data_codegen.cpp
  clang/test/OpenMP/target_exit_data_depend_codegen.cpp
  clang/test/OpenMP/target_firstprivate_codegen.cpp
  clang/test/OpenMP/target_is_device_ptr_codegen.cpp
  clang/test/OpenMP/target_map_codegen_00.cpp
  clang/test/OpenMP/target_map_codegen_01.cpp
  clang/test/OpenMP/target_map_codegen_02.cpp
  clang/test/OpenMP/target_map_codegen_03.cpp
  clang/test/OpenMP/target_map_codegen_04.cpp
  clang/test/OpenMP/target_map_codegen_05.cpp
  clang/test/OpenMP/target_map_codegen_06.cpp
  clang/test/OpenMP/target_map_codegen_07.cpp
  clang/test/OpenMP/target_map_codegen_08.cpp
  clang/test/OpenMP/target_map_codegen_09.cpp
  clang/test/OpenMP/target_map_codegen_10.cpp
  clang/test/OpenMP/target_map_codegen_11.cpp
  clang/test/OpenMP/target_map_codegen_12.cpp
  clang/test/OpenMP/target_map_codegen_13.cpp
  clang/test/OpenMP/target_map_codegen_14.cpp
  clang/test/OpenMP/target_map_codegen_15.cpp
  clang/test/OpenMP/target_map_codegen_16.cpp
  clang/test/OpenMP/target_map_codegen_17.cpp
  clang/test/OpenMP/target_map_codegen_18.inc
  clang/test/OpenMP/target_map_codegen_19.cpp
  clang/test/OpenMP/target_map_codegen_20.cpp
  clang/test/OpenMP/target_map_codegen_21.cpp
  clang/test/OpenMP/target_map_codegen_22.cpp
  clang/test/OpenMP/target_map_codegen_23.cpp
  clang/test/OpenMP/target_map_codegen_24.cpp
  clang/test/OpenMP/target_map_codegen_25.cpp
  clang/test/OpenMP/target_map_codegen_26.cpp
  clang/test/OpenMP/target_map_codegen_27.cpp
  clang/test/OpenMP/target_map_codegen_28.cpp
  clang/test/OpenMP/target_map_codegen_29.cpp
  clang/test/OpenMP/target_map_codegen_30.cpp
  clang/test/OpenMP/target_map_codegen_31.cpp
  clang/test/OpenMP/target_map_codegen_32.cpp
  clang/test/OpenMP/target_map_codegen_33.cpp
  clang/test/OpenMP/target_map_member_expr_array_section_codegen.cpp
  clang/test/OpenMP/target_parallel_codegen.cpp
  clang/test/OpenMP/target_parallel_depend_codegen.cpp
  clang/test/OpenMP/target_parallel_for_codegen.cpp
  clang/test/OpenMP/target_parallel_for_depend_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_depend_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_parallel_for_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_parallel_if_codegen.cpp
  clang/tes

[PATCH] D88297: [clangd] Trivial setter support when moving items to fields

2020-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Nice, thanks!




Comment at: clang-tools-extra/clangd/Hover.cpp:461
+  if (auto *CE = llvm::dyn_cast(RHS->IgnoreCasts())) {
+// Make sure we get the version of move with 1 arg, the other is for moving
+// ranges.

nit: you could skip this check if you like, the other variant isn't going to be 
on the RHS of an assignment :-)



Comment at: clang-tools-extra/clangd/Hover.cpp:468
+  return llvm::None;
+if (ND->getName() != "move" || !ND->isInStdNamespace())
+  return llvm::None;

I guess you want `!ND->getIdentifier() || ND->getName() != "move" || ...` to 
guard against it being a special name somehow - getName() asserts in that case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88297

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


[PATCH] D87225: [clangd] When finding refs for a renaming alias, do not return refs to underlying decls

2020-09-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/XRefs.cpp:1150
+  if (llvm::isa(D) || llvm::isa(D)) {
+Decls = getDeclAtPosition(AST, *CurLoc,
+  Relations | DeclRelation::Underlying);

I think it should not happen in practice (Decls just have 1 element in most 
cases), but the code feels hacky, we are throwing other decls if one of the 
`Decls` is a using decl.

I suppose if we're using the same workaround as `locateASTReferent`, then we 
should follow that way by only adjusting the UsingDecl/UnresolvedValueDecl 
results and keeping others.


In general, I think we probably need to remove this workaround (see the  
`FIXME` in `locateASTReferent`) by refining TargetDecl API. The current 
`DeclRelation::Underlying` enum is not enough to support our use case where we 
only want underlying decls for *non-renaming* alias. One rough idea to fix it 
is to split the `Underlying` to two `RenameAliasUnderlying` and 
`RemainingUnderlying` -- this would need some API design work, so no need to do 
it in this patch.





Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87225

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


[PATCH] D88297: [clangd] Trivial setter support when moving items to fields

2020-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/Hover.cpp:414
 // If CMD is one of the forms:
 //   void foo(T arg) { FieldName = arg; }
 //   R foo(T arg) { FieldName = arg; return *this; }

can you also update the docs?



Comment at: clang-tools-extra/clangd/Hover.cpp:466
+auto *ND = llvm::dyn_cast(CE->getCalleeDecl());
+if (!ND)
+  return llvm::None;

nit: combine with the next condition, and perform the string comparison last, 
i.e.:

`if(!ND || !ND->isInStd || ND->getName() != "move")`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88297

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


[PATCH] D65880: [Driver] Move LIBRARY_PATH before user inputs

2020-09-25 Thread Joachim Protze via Phabricator via cfe-commits
protze.joachim added a comment.

I still see some clang-specific and system link directories listed in the 
linker line before the directories from `LIBRARY_PATH`:

  $ LIBRARY_PATH=test1 /usr/local/clang/bin/clang -Ltest2 -v hello.c
   "/usr/bin/ld" .../crtbegin.o -Ltest2 
-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5 
-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64 -L/lib/../lib64 
-L/usr/lib/../lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../.. 
-L/usr/local/clang/bin/../lib -L/lib -L/usr/lib -Ltest1

I think they are inserted by `ToolChain.AddFilePathLibArgs` in Gnu.cpp. Is this 
the intended ordering? My expectation would be

  $ LIBRARY_PATH=test1 /usr/local/clang/bin/clang -Ltest2 -v hello.c
   "/usr/bin/ld" .../crtbegin.o -Ltest2 -Ltest1 
-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5 
-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64 -L/lib/../lib64 
-L/usr/lib/../lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../.. 
-L/usr/local/clang/bin/../lib -L/lib -L/usr/lib

@hfinkel any opinion?


Repository:
  rL LLVM

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

https://reviews.llvm.org/D65880

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


[PATCH] D88281: [clangd] Use Decision Forest to score code compeltions.

2020-09-25 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz accepted this revision.
adamcz added a comment.
This revision is now accepted and ready to land.

Could you add a test that sets this flag? Perhaps we can run 
CodeCompletionTests.cpp twice, once with this flag, once without? Just to 
exercise these code paths, I think most expectations there are unordered, so it 
should work?




Comment at: clang-tools-extra/clangd/CodeComplete.cpp:1635
+case RM::Heuristics:
+  Scores.Quality = Quality.evaluate();
+  Scores.Relevance = Relevance.evaluate();

Ideally we'd rename the evaluate() here, since SymbolQualitySignals is used for 
both heuristic and DecisionForest version, but evaluate is heuristic-specific. 
I think in pefect world this would be out of SymbolQualitySignals class (which 
would become just storage), but at least it should be renamed to 
evaluateUsingHeuristic().



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:1655
+  // NameMatch should be a multiplier on total score to support rescoring.
+  Scores.Total = Relevance.NameMatch * Scores.ExcludingName;
+  return Scores;

Could we make the weight of Relevance.NameMatch configurable, maybe through 
CodeCompletionOptions or such? I'm worried it may dominate the score too much 
and being able to configure this would allow us to run experiments easily.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88281

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


[PATCH] D88088: WIP [clang] improve accuracy of ExprMutAnalyzer

2020-09-25 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 294300.
JonasToth added a comment.

- address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88088

Files:
  clang/lib/Analysis/ExprMutationAnalyzer.cpp
  clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp

Index: clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
===
--- clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -19,9 +19,7 @@
 
 using namespace clang::ast_matchers;
 using ::testing::ElementsAre;
-using ::testing::IsEmpty;
 using ::testing::ResultOf;
-using ::testing::StartsWith;
 using ::testing::Values;
 
 namespace {
@@ -63,12 +61,16 @@
   const auto *const S = selectFirst("stmt", Results);
   SmallVector Chain;
   ExprMutationAnalyzer Analyzer(*S, AST->getASTContext());
+
   for (const auto *E = selectFirst("expr", Results); E != nullptr;) {
 const Stmt *By = Analyzer.findMutation(E);
-std::string buffer;
-llvm::raw_string_ostream stream(buffer);
-By->printPretty(stream, nullptr, AST->getASTContext().getPrintingPolicy());
-Chain.push_back(StringRef(stream.str()).trim().str());
+if (!By)
+  break;
+
+std::string Buffer;
+llvm::raw_string_ostream Stream(Buffer);
+By->printPretty(Stream, nullptr, AST->getASTContext().getPrintingPolicy());
+Chain.emplace_back(StringRef(Stream.str()).trim().str());
 E = dyn_cast(By);
   }
   return Chain;
@@ -111,7 +113,13 @@
 
 class AssignmentTest : public ::testing::TestWithParam {};
 
+// This test is for the most basic and direct modification of a variable,
+// assignment to it (e.g. `x = 10;`).
+// It additionally tests, that reference to a variable are not only captured
+// directly, but expression that result in the variable are handled, too.
+// This includes the comma operator, parens and the ternary operator.
 TEST_P(AssignmentTest, AssignmentModifies) {
+  // Test the detection of the raw expression modifications.
   {
 const std::string ModExpr = "x " + GetParam() + " 10";
 const auto AST = buildASTFromCode("void f() { int x; " + ModExpr + "; }");
@@ -120,6 +128,7 @@
 EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
   }
 
+  // Test the detection if the expression is surrounded by parens.
   {
 const std::string ModExpr = "(x) " + GetParam() + " 10";
 const auto AST = buildASTFromCode("void f() { int x; " + ModExpr + "; }");
@@ -127,6 +136,60 @@
 match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
 EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
   }
+
+  // Test the detection if the comma operator yields the expression as result.
+  {
+const std::string ModExpr = "x " + GetParam() + " 10";
+const auto AST = buildASTFromCodeWithArgs(
+"void f() { int x, y; y, " + ModExpr + "; }", {"-Wno-unused-value"});
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
+  }
+
+  // Ensure no detection if t he comma operator does not yield the expression as
+  // result.
+  {
+const std::string ModExpr = "y, x, y " + GetParam() + " 10";
+const auto AST = buildASTFromCodeWithArgs(
+"void f() { int x, y; " + ModExpr + "; }", {"-Wno-unused-value"});
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_FALSE(isMutated(Results, AST.get()));
+  }
+
+  // Test the detection if the a ternary operator can result in the expression.
+  {
+const std::string ModExpr = "(y != 0 ? y : x) " + GetParam() + " 10";
+const auto AST =
+buildASTFromCode("void f() { int y = 0, x; " + ModExpr + "; }");
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
+  }
+
+  // Test the detection if the a ternary operator can result in the expression
+  // through multiple nesting of ternary operators.
+  {
+const std::string ModExpr =
+"(y != 0 ? (y > 5 ? y : x) : (y)) " + GetParam() + " 10";
+const auto AST =
+buildASTFromCode("void f() { int y = 0, x; " + ModExpr + "; }");
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
+  }
+
+  // Test the detection if the a ternary operator can result in the expression
+  // with additional parens.
+  {
+const std::string ModExpr = "(y != 0 ? (y) : ((x))) " + GetParam() + " 10";
+const auto AST =
+buildASTFromCode("void f() { int y = 0, x; " + ModExpr + "; }");
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTCo

[PATCH] D88088: WIP [clang] improve accuracy of ExprMutAnalyzer

2020-09-25 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 294301.
JonasToth added a comment.

- fix typo that provided wrong argument to AST building


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88088

Files:
  clang/lib/Analysis/ExprMutationAnalyzer.cpp
  clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp

Index: clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
===
--- clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -19,9 +19,7 @@
 
 using namespace clang::ast_matchers;
 using ::testing::ElementsAre;
-using ::testing::IsEmpty;
 using ::testing::ResultOf;
-using ::testing::StartsWith;
 using ::testing::Values;
 
 namespace {
@@ -63,12 +61,16 @@
   const auto *const S = selectFirst("stmt", Results);
   SmallVector Chain;
   ExprMutationAnalyzer Analyzer(*S, AST->getASTContext());
+
   for (const auto *E = selectFirst("expr", Results); E != nullptr;) {
 const Stmt *By = Analyzer.findMutation(E);
-std::string buffer;
-llvm::raw_string_ostream stream(buffer);
-By->printPretty(stream, nullptr, AST->getASTContext().getPrintingPolicy());
-Chain.push_back(StringRef(stream.str()).trim().str());
+if (!By)
+  break;
+
+std::string Buffer;
+llvm::raw_string_ostream Stream(Buffer);
+By->printPretty(Stream, nullptr, AST->getASTContext().getPrintingPolicy());
+Chain.emplace_back(StringRef(Stream.str()).trim().str());
 E = dyn_cast(By);
   }
   return Chain;
@@ -111,7 +113,13 @@
 
 class AssignmentTest : public ::testing::TestWithParam {};
 
+// This test is for the most basic and direct modification of a variable,
+// assignment to it (e.g. `x = 10;`).
+// It additionally tests, that reference to a variable are not only captured
+// directly, but expression that result in the variable are handled, too.
+// This includes the comma operator, parens and the ternary operator.
 TEST_P(AssignmentTest, AssignmentModifies) {
+  // Test the detection of the raw expression modifications.
   {
 const std::string ModExpr = "x " + GetParam() + " 10";
 const auto AST = buildASTFromCode("void f() { int x; " + ModExpr + "; }");
@@ -120,6 +128,7 @@
 EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
   }
 
+  // Test the detection if the expression is surrounded by parens.
   {
 const std::string ModExpr = "(x) " + GetParam() + " 10";
 const auto AST = buildASTFromCode("void f() { int x; " + ModExpr + "; }");
@@ -127,6 +136,60 @@
 match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
 EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
   }
+
+  // Test the detection if the comma operator yields the expression as result.
+  {
+const std::string ModExpr = "x " + GetParam() + " 10";
+const auto AST = buildASTFromCodeWithArgs(
+"void f() { int x, y; y, " + ModExpr + "; }", {"-Wno-unused-value"});
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
+  }
+
+  // Ensure no detection if t he comma operator does not yield the expression as
+  // result.
+  {
+const std::string ModExpr = "y, x, y " + GetParam() + " 10";
+const auto AST = buildASTFromCodeWithArgs(
+"void f() { int x, y; " + ModExpr + "; }", {"-Wno-unused-value"});
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_FALSE(isMutated(Results, AST.get()));
+  }
+
+  // Test the detection if the a ternary operator can result in the expression.
+  {
+const std::string ModExpr = "(y != 0 ? y : x) " + GetParam() + " 10";
+const auto AST =
+buildASTFromCode("void f() { int y = 0, x; " + ModExpr + "; }");
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
+  }
+
+  // Test the detection if the a ternary operator can result in the expression
+  // through multiple nesting of ternary operators.
+  {
+const std::string ModExpr =
+"(y != 0 ? (y > 5 ? y : x) : (y)) " + GetParam() + " 10";
+const auto AST =
+buildASTFromCode("void f() { int y = 0, x; " + ModExpr + "; }");
+const auto Results =
+match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre(ModExpr));
+  }
+
+  // Test the detection if the a ternary operator can result in the expression
+  // with additional parens.
+  {
+const std::string ModExpr = "(y != 0 ? (y) : ((x))) " + GetParam() + " 10";
+const auto AST =
+buildASTFromCode("void f() { int y = 0, x; " + ModExpr + "; }");
+const auto Results =
+match(withEnclosingCompound(

[clang] 85cea77 - Typo fix; NFC

2020-09-25 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2020-09-25T10:26:29-04:00
New Revision: 85cea77ecb7f2ca51198ec1ad1d28845e803ee32

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

LOG: Typo fix; NFC

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index a68d37ace089..d6c3ce50f1b1 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -379,7 +379,7 @@ that appears to be capable of returning to its caller.
 def NoMergeDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
-If a statement is marked ``nomerge`` and contains call experessions, those call
+If a statement is marked ``nomerge`` and contains call expressions, those call
 expressions inside the statement will not be merged during optimization. This 
 attribute can be used to prevent the optimizer from obscuring the source
 location of certain calls. For example, it will prevent tail merging otherwise



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


[PATCH] D87187: [Driver] Perform Linux distribution detection just once

2020-09-25 Thread Dmitry Antipov via Phabricator via cfe-commits
dmantipov updated this revision to Diff 294302.
dmantipov marked an inline comment as done.
dmantipov added a comment.

Well, the problem with tests seems to be a bit wider - tests uses  
llvm::vfs::InMemoryFileSystem, which is not "real", so detection will return  
Distro::UnknownDistro anyway. So I think we can just add fallback branch for 
such pseudo filesystems and live with current tests as is.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87187

Files:
  clang/include/clang/Driver/Distro.h
  clang/lib/Driver/Distro.cpp

Index: clang/lib/Driver/Distro.cpp
===
--- clang/lib/Driver/Distro.cpp
+++ clang/lib/Driver/Distro.cpp
@@ -15,76 +15,106 @@
 #include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/Host.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Threading.h"
 
 using namespace clang::driver;
 using namespace clang;
 
-static Distro::DistroType DetectDistro(llvm::vfs::FileSystem &VFS,
-   const llvm::Triple &TargetOrHost) {
-  // If we don't target Linux, no need to check the distro. This saves a few
-  // OS calls.
-  if (!TargetOrHost.isOSLinux())
+static Distro::DistroType DetectOsRelease(llvm::vfs::FileSystem &VFS) {
+  llvm::ErrorOr> File =
+  VFS.getBufferForFile("/etc/os-release");
+  if (!File)
+File = VFS.getBufferForFile("/usr/lib/os-release");
+  if (!File)
 return Distro::UnknownDistro;
 
-  // If the host is not running Linux, and we're backed by a real file system,
-  // no need to check the distro. This is the case where someone is
-  // cross-compiling from BSD or Windows to Linux, and it would be meaningless
-  // to try to figure out the "distro" of the non-Linux host.
-  IntrusiveRefCntPtr RealFS =
-  llvm::vfs::getRealFileSystem();
-  llvm::Triple HostTriple(llvm::sys::getProcessTriple());
-  if (!HostTriple.isOSLinux() && &VFS == RealFS.get())
-return Distro::UnknownDistro;
+  SmallVector Lines;
+  File.get()->getBuffer().split(Lines, "\n");
+  Distro::DistroType Version = Distro::UnknownDistro;
+
+  // Obviously this can be improved a lot.
+  for (StringRef Line : Lines)
+if (Version == Distro::UnknownDistro && Line.startswith("ID="))
+  Version = llvm::StringSwitch(Line.substr(3))
+.Case("fedora", Distro::Fedora)
+.Case("gentoo", Distro::Gentoo)
+.Case("arch", Distro::ArchLinux)
+// On SLES, /etc/os-release was introduced in SLES 11.
+.Case("sles", Distro::OpenSUSE)
+.Case("opensuse", Distro::OpenSUSE)
+.Case("exherbo", Distro::Exherbo)
+.Default(Distro::UnknownDistro);
+  return Version;
+}
 
+static Distro::DistroType DetectLsbRelease(llvm::vfs::FileSystem &VFS) {
   llvm::ErrorOr> File =
   VFS.getBufferForFile("/etc/lsb-release");
-  if (File) {
-StringRef Data = File.get()->getBuffer();
-SmallVector Lines;
-Data.split(Lines, "\n");
-Distro::DistroType Version = Distro::UnknownDistro;
-for (StringRef Line : Lines)
-  if (Version == Distro::UnknownDistro && Line.startswith("DISTRIB_CODENAME="))
-Version = llvm::StringSwitch(Line.substr(17))
-  .Case("hardy", Distro::UbuntuHardy)
-  .Case("intrepid", Distro::UbuntuIntrepid)
-  .Case("jaunty", Distro::UbuntuJaunty)
-  .Case("karmic", Distro::UbuntuKarmic)
-  .Case("lucid", Distro::UbuntuLucid)
-  .Case("maverick", Distro::UbuntuMaverick)
-  .Case("natty", Distro::UbuntuNatty)
-  .Case("oneiric", Distro::UbuntuOneiric)
-  .Case("precise", Distro::UbuntuPrecise)
-  .Case("quantal", Distro::UbuntuQuantal)
-  .Case("raring", Distro::UbuntuRaring)
-  .Case("saucy", Distro::UbuntuSaucy)
-  .Case("trusty", Distro::UbuntuTrusty)
-  .Case("utopic", Distro::UbuntuUtopic)
-  .Case("vivid", Distro::UbuntuVivid)
-  .Case("wily", Distro::UbuntuWily)
-  .Case("xenial", Distro::UbuntuXenial)
-  .Case("yakkety", Distro::UbuntuYakkety)
-  .Case("zesty", Distro::UbuntuZesty)
-  .Case("artful", Distro::UbuntuArtful)
-  .Case("bionic", Distro::UbuntuBionic)
-  .Case("cosmic", Distro::UbuntuCosmic)
-  .Case("disco", Distro::UbuntuDisco)
-  .Case("eoan", Distro::UbuntuEoan)
-  .Case("focal", Distro::UbuntuFocal)
-  .Case("groovy", Distro::UbuntuGroovy)
-  .Default(Distro::UnknownDistro);
-   

[PATCH] D88303: [clang][codegen] Remove the insertion of `correctly-rounded-divide-sqrt-fp-math` fn-attr.

2020-09-25 Thread Michael Liao via Phabricator via cfe-commits
hliao created this revision.
hliao added a reviewer: yaxunl.
Herald added subscribers: cfe-commits, kerbowa, Anastasia, nhaehnle, jvesely.
Herald added a project: clang.
hliao requested review of this revision.

- `-cl-fp32-correctly-rounded-divide-sqrt` is already handled in a 
per-instruction manner to annotate the accuracy required. There's no need to 
add that fn-attr. So far, there's no backend handling that attr and that option 
is an OpenCL-specific one, which should not be inserted everywhere.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88303

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/test/.clang-format
  clang/test/CodeGen/complex-builtins.c
  clang/test/CodeGen/complex-libcalls.c
  clang/test/CodeGen/math-builtins.c
  clang/test/CodeGen/math-libcalls.c
  clang/test/CodeGenOpenCL/amdgpu-attrs.cl
  clang/test/CodeGenOpenCL/fpmath.cl

Index: clang/test/CodeGenOpenCL/fpmath.cl
===
--- clang/test/CodeGenOpenCL/fpmath.cl
+++ clang/test/CodeGenOpenCL/fpmath.cl
@@ -7,7 +7,6 @@
 
 float spscalardiv(float a, float b) {
   // CHECK: @spscalardiv
-  // CHECK: #[[ATTR:[0-9]+]]
   // CHECK: fdiv{{.*}},
   // NODIVOPT: !fpmath ![[MD:[0-9]+]]
   // DIVOPT-NOT: !fpmath ![[MD:[0-9]+]]
@@ -16,7 +15,6 @@
 
 float4 spvectordiv(float4 a, float4 b) {
   // CHECK: @spvectordiv
-  // CHECK: #[[ATTR2:[0-9]+]]
   // CHECK: fdiv{{.*}},
   // NODIVOPT: !fpmath ![[MD]]
   // DIVOPT-NOT: !fpmath ![[MD]]
@@ -38,18 +36,9 @@
 #pragma OPENCL EXTENSION cl_khr_fp64 : enable
 double dpscalardiv(double a, double b) {
   // CHECK: @dpscalardiv
-  // CHECK: #[[ATTR]]
   // CHECK-NOT: !fpmath
   return a / b;
 }
 #endif
 
-// CHECK: attributes #[[ATTR]] = {
-// NODIVOPT-SAME: "correctly-rounded-divide-sqrt-fp-math"="false"
-// DIVOPT-SAME: "correctly-rounded-divide-sqrt-fp-math"="true"
-// CHECK-SAME: }
-// CHECK: attributes #[[ATTR2]] = {
-// NODIVOPT-SAME: "correctly-rounded-divide-sqrt-fp-math"="false"
-// DIVOPT-SAME: "correctly-rounded-divide-sqrt-fp-math"="true"
-// CHECK-SAME: }
 // NODIVOPT: ![[MD]] = !{float 2.50e+00}
Index: clang/test/CodeGenOpenCL/amdgpu-attrs.cl
===
--- clang/test/CodeGenOpenCL/amdgpu-attrs.cl
+++ clang/test/CodeGenOpenCL/amdgpu-attrs.cl
@@ -190,5 +190,5 @@
 // CHECK-DAG: attributes [[FLAT_WORK_GROUP_SIZE_32_64_WAVES_PER_EU_2_NUM_SGPR_32_NUM_VGPR_64]] = {{.*}} "amdgpu-flat-work-group-size"="32,64" "amdgpu-implicitarg-num-bytes"="56" "amdgpu-num-sgpr"="32" "amdgpu-num-vgpr"="64" "amdgpu-waves-per-eu"="2"
 // CHECK-DAG: attributes [[FLAT_WORK_GROUP_SIZE_32_64_WAVES_PER_EU_2_4_NUM_SGPR_32_NUM_VGPR_64]] = {{.*}} "amdgpu-flat-work-group-size"="32,64" "amdgpu-implicitarg-num-bytes"="56" "amdgpu-num-sgpr"="32" "amdgpu-num-vgpr"="64" "amdgpu-waves-per-eu"="2,4"
 
-// CHECK-DAG: attributes [[A_FUNCTION]] = {{.*}} "correctly-rounded-divide-sqrt-fp-math"="false"
+// CHECK-DAG: attributes [[A_FUNCTION]] = {{.*}}
 // CHECK-DAG: attributes [[DEFAULT_KERNEL_ATTRS]] = {{.*}} "amdgpu-flat-work-group-size"="1,256" "amdgpu-implicitarg-num-bytes"="56"
Index: clang/test/CodeGen/math-libcalls.c
===
--- clang/test/CodeGen/math-libcalls.c
+++ clang/test/CodeGen/math-libcalls.c
@@ -532,13 +532,12 @@
 // HAS_ERRNO: declare x86_fp80 @llvm.trunc.f80(x86_fp80) [[READNONE_INTRINSIC]]
 };
 
-
 // NO__ERRNO: attributes [[READNONE]] = { {{.*}}readnone{{.*}} }
 // NO__ERRNO: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
-// NO__ERRNO: attributes [[NOT_READNONE]] = { nounwind "correctly{{.*}} }
+// NO__ERRNO: attributes [[NOT_READNONE]] = { nounwind {{.*}} }
 // NO__ERRNO: attributes [[READONLY]] = { {{.*}}readonly{{.*}} }
 
-// HAS_ERRNO: attributes [[NOT_READNONE]] = { nounwind "correctly{{.*}} }
+// HAS_ERRNO: attributes [[NOT_READNONE]] = { nounwind {{.*}} }
 // HAS_ERRNO: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
 // HAS_ERRNO: attributes [[READONLY]] = { {{.*}}readonly{{.*}} }
 // HAS_ERRNO: attributes [[READNONE]] = { {{.*}}readnone{{.*}} }
Index: clang/test/CodeGen/math-builtins.c
===
--- clang/test/CodeGen/math-builtins.c
+++ clang/test/CodeGen/math-builtins.c
@@ -577,13 +577,12 @@
 // HAS_ERRNO: declare x86_fp80 @llvm.trunc.f80(x86_fp80) [[READNONE_INTRINSIC]]
 };
 
-
 // NO__ERRNO: attributes [[READNONE]] = { {{.*}}readnone{{.*}} }
 // NO__ERRNO: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
-// NO__ERRNO: attributes [[NOT_READNONE]] = { nounwind "correctly{{.*}} }
+// NO__ERRNO: attributes [[NOT_READNONE]] = { nounwind {{.*}} }
 // NO__ERRNO: attributes [[PURE]] = { {{.*}}readonly{{.*}} }
 
-// HAS_ERRNO: attributes [[NOT_READNONE]] = { nounwind "correctly{{.*}} }
+// HAS_ERRNO: attributes [[NOT_READNONE]] = { nounwind {{.*}} }
 // HAS_ERRNO: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }

[PATCH] D88296: [clang-format] De-duplicate includes with leading or trailing whitespace.

2020-09-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

This LGTM, generally I think clang-format seems to remove trailing spaces 
anyway so it might be that the duplicate might disappear on the second format. 
but I'm good with this approach

But as a side note I keep wondering who are these people who clang-format once 
and expect it to be perfect!

Firstly I'm clang-format -n checking my 4-5 million lines of code every night, 
secondly the CI system is checking, and thirdly in our company we using 
clang-format on save, and Ctrl-S and :w are like a tick for me.

By the time I check my code in I've clang-formatted it 100's of times. I don't 
even need to use git clang-format I know its perfect already!

This is in my view the resolution to pretty much all those, I have to do it 
twice! bugs..its a non issue for anyone with a zero tolerance policy to 
un-clang-formtted code!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88296

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


[clang] a51d51a - Fix some of the more egregious 80-col and whitespace issues; NFC

2020-09-25 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2020-09-25T10:37:38-04:00
New Revision: a51d51a0d4d72ab423b11da4c5c877bc6e89a580

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

LOG: Fix some of the more egregious 80-col and whitespace issues; NFC

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index d6c3ce50f1b1..9c16fecfeaa8 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -87,12 +87,12 @@ def InitSegDocs : Documentation {
   let Category = DocCatVariable;
   let Content = [{
 The attribute applied by ``pragma init_seg()`` controls the section into
-which global initialization function pointers are emitted.  It is only
-available with ``-fms-extensions``.  Typically, this function pointer is
-emitted into ``.CRT$XCU`` on Windows.  The user can change the order of
+which global initialization function pointers are emitted. It is only
+available with ``-fms-extensions``. Typically, this function pointer is
+emitted into ``.CRT$XCU`` on Windows. The user can change the order of
 initialization by using a 
diff erent section name with the same
 ``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
-after the standard ``.CRT$XCU`` sections.  See the init_seg_
+after the standard ``.CRT$XCU`` sections. See the init_seg_
 documentation on MSDN for more information.
 
 .. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx
@@ -118,10 +118,10 @@ def DLLExportDocs : Documentation {
   let Category = DocCatVariable;
   let Content = [{
 The ``__declspec(dllexport)`` attribute declares a variable, function, or
-Objective-C interface to be exported from the module.  It is available under 
the
-``-fdeclspec`` flag for compatibility with various compilers.  The primary use
+Objective-C interface to be exported from the module. It is available under the
+``-fdeclspec`` flag for compatibility with various compilers. The primary use
 is for COFF object files which explicitly specify what interfaces are available
-for external use.  See the dllexport_ documentation on MSDN for more
+for external use. See the dllexport_ documentation on MSDN for more
 information.
 
 .. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
@@ -132,10 +132,10 @@ def DLLImportDocs : Documentation {
   let Category = DocCatVariable;
   let Content = [{
 The ``__declspec(dllimport)`` attribute declares a variable, function, or
-Objective-C interface to be imported from an external module.  It is available
-under the ``-fdeclspec`` flag for compatibility with various compilers.  The
+Objective-C interface to be imported from an external module. It is available
+under the ``-fdeclspec`` flag for compatibility with various compilers. The
 primary use is for COFF object files which explicitly specify what interfaces
-are imported from external modules.  See the dllimport_ documentation on MSDN
+are imported from external modules. See the dllimport_ documentation on MSDN
 for more information.
 
 .. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
@@ -146,14 +146,14 @@ def ThreadDocs : Documentation {
   let Category = DocCatVariable;
   let Content = [{
 The ``__declspec(thread)`` attribute declares a variable with thread local
-storage.  It is available under the ``-fms-extensions`` flag for MSVC
-compatibility.  See the documentation for `__declspec(thread)`_ on MSDN.
+storage. It is available under the ``-fms-extensions`` flag for MSVC
+compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
 
 .. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
 
 In Clang, ``__declspec(thread)`` is generally equivalent in functionality to 
the
-GNU ``__thread`` keyword.  The variable must not have a destructor and must 
have
-a constant initializer, if any.  The attribute only applies to variables
+GNU ``__thread`` keyword. The variable must not have a destructor and must have
+a constant initializer, if any. The attribute only applies to variables
 declared with static storage duration, such as globals, class static data
 members, and static locals.
   }];
@@ -305,7 +305,7 @@ outlining job:
 A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel".
 A SYCL kernel defines the entry point to the "device part" of the code. The
 compiler will emit all symbols accessible from a "kernel". In this code
-example, the compiler will emit "foo" function.  More details about the
+example, the compiler will emit "foo" function. More details about the
 compilation of functions for the device part can be found in the SYCL 1.2.1
 specification Section 6.4.
 To show

[PATCH] D88303: [clang][codegen] Remove the insertion of `correctly-rounded-divide-sqrt-fp-math` fn-attr.

2020-09-25 Thread Michael Liao via Phabricator via cfe-commits
hliao updated this revision to Diff 294307.
hliao added a comment.

Remove the irrelevant change on .clang-format.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88303

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/test/CodeGen/complex-builtins.c
  clang/test/CodeGen/complex-libcalls.c
  clang/test/CodeGen/math-builtins.c
  clang/test/CodeGen/math-libcalls.c
  clang/test/CodeGenOpenCL/amdgpu-attrs.cl
  clang/test/CodeGenOpenCL/fpmath.cl

Index: clang/test/CodeGenOpenCL/fpmath.cl
===
--- clang/test/CodeGenOpenCL/fpmath.cl
+++ clang/test/CodeGenOpenCL/fpmath.cl
@@ -7,7 +7,6 @@
 
 float spscalardiv(float a, float b) {
   // CHECK: @spscalardiv
-  // CHECK: #[[ATTR:[0-9]+]]
   // CHECK: fdiv{{.*}},
   // NODIVOPT: !fpmath ![[MD:[0-9]+]]
   // DIVOPT-NOT: !fpmath ![[MD:[0-9]+]]
@@ -16,7 +15,6 @@
 
 float4 spvectordiv(float4 a, float4 b) {
   // CHECK: @spvectordiv
-  // CHECK: #[[ATTR2:[0-9]+]]
   // CHECK: fdiv{{.*}},
   // NODIVOPT: !fpmath ![[MD]]
   // DIVOPT-NOT: !fpmath ![[MD]]
@@ -38,18 +36,9 @@
 #pragma OPENCL EXTENSION cl_khr_fp64 : enable
 double dpscalardiv(double a, double b) {
   // CHECK: @dpscalardiv
-  // CHECK: #[[ATTR]]
   // CHECK-NOT: !fpmath
   return a / b;
 }
 #endif
 
-// CHECK: attributes #[[ATTR]] = {
-// NODIVOPT-SAME: "correctly-rounded-divide-sqrt-fp-math"="false"
-// DIVOPT-SAME: "correctly-rounded-divide-sqrt-fp-math"="true"
-// CHECK-SAME: }
-// CHECK: attributes #[[ATTR2]] = {
-// NODIVOPT-SAME: "correctly-rounded-divide-sqrt-fp-math"="false"
-// DIVOPT-SAME: "correctly-rounded-divide-sqrt-fp-math"="true"
-// CHECK-SAME: }
 // NODIVOPT: ![[MD]] = !{float 2.50e+00}
Index: clang/test/CodeGenOpenCL/amdgpu-attrs.cl
===
--- clang/test/CodeGenOpenCL/amdgpu-attrs.cl
+++ clang/test/CodeGenOpenCL/amdgpu-attrs.cl
@@ -190,5 +190,5 @@
 // CHECK-DAG: attributes [[FLAT_WORK_GROUP_SIZE_32_64_WAVES_PER_EU_2_NUM_SGPR_32_NUM_VGPR_64]] = {{.*}} "amdgpu-flat-work-group-size"="32,64" "amdgpu-implicitarg-num-bytes"="56" "amdgpu-num-sgpr"="32" "amdgpu-num-vgpr"="64" "amdgpu-waves-per-eu"="2"
 // CHECK-DAG: attributes [[FLAT_WORK_GROUP_SIZE_32_64_WAVES_PER_EU_2_4_NUM_SGPR_32_NUM_VGPR_64]] = {{.*}} "amdgpu-flat-work-group-size"="32,64" "amdgpu-implicitarg-num-bytes"="56" "amdgpu-num-sgpr"="32" "amdgpu-num-vgpr"="64" "amdgpu-waves-per-eu"="2,4"
 
-// CHECK-DAG: attributes [[A_FUNCTION]] = {{.*}} "correctly-rounded-divide-sqrt-fp-math"="false"
+// CHECK-DAG: attributes [[A_FUNCTION]] = {{.*}}
 // CHECK-DAG: attributes [[DEFAULT_KERNEL_ATTRS]] = {{.*}} "amdgpu-flat-work-group-size"="1,256" "amdgpu-implicitarg-num-bytes"="56"
Index: clang/test/CodeGen/math-libcalls.c
===
--- clang/test/CodeGen/math-libcalls.c
+++ clang/test/CodeGen/math-libcalls.c
@@ -532,13 +532,12 @@
 // HAS_ERRNO: declare x86_fp80 @llvm.trunc.f80(x86_fp80) [[READNONE_INTRINSIC]]
 };
 
-
 // NO__ERRNO: attributes [[READNONE]] = { {{.*}}readnone{{.*}} }
 // NO__ERRNO: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
-// NO__ERRNO: attributes [[NOT_READNONE]] = { nounwind "correctly{{.*}} }
+// NO__ERRNO: attributes [[NOT_READNONE]] = { nounwind {{.*}} }
 // NO__ERRNO: attributes [[READONLY]] = { {{.*}}readonly{{.*}} }
 
-// HAS_ERRNO: attributes [[NOT_READNONE]] = { nounwind "correctly{{.*}} }
+// HAS_ERRNO: attributes [[NOT_READNONE]] = { nounwind {{.*}} }
 // HAS_ERRNO: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
 // HAS_ERRNO: attributes [[READONLY]] = { {{.*}}readonly{{.*}} }
 // HAS_ERRNO: attributes [[READNONE]] = { {{.*}}readnone{{.*}} }
Index: clang/test/CodeGen/math-builtins.c
===
--- clang/test/CodeGen/math-builtins.c
+++ clang/test/CodeGen/math-builtins.c
@@ -577,13 +577,12 @@
 // HAS_ERRNO: declare x86_fp80 @llvm.trunc.f80(x86_fp80) [[READNONE_INTRINSIC]]
 };
 
-
 // NO__ERRNO: attributes [[READNONE]] = { {{.*}}readnone{{.*}} }
 // NO__ERRNO: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
-// NO__ERRNO: attributes [[NOT_READNONE]] = { nounwind "correctly{{.*}} }
+// NO__ERRNO: attributes [[NOT_READNONE]] = { nounwind {{.*}} }
 // NO__ERRNO: attributes [[PURE]] = { {{.*}}readonly{{.*}} }
 
-// HAS_ERRNO: attributes [[NOT_READNONE]] = { nounwind "correctly{{.*}} }
+// HAS_ERRNO: attributes [[NOT_READNONE]] = { nounwind {{.*}} }
 // HAS_ERRNO: attributes [[READNONE_INTRINSIC]] = { {{.*}}readnone{{.*}} }
 // HAS_ERRNO: attributes [[PURE]] = { {{.*}}readonly{{.*}} }
 // HAS_ERRNO: attributes [[READNONE]] = { {{.*}}readnone{{.*}} }
Index: clang/test/CodeGen/complex-libcalls.c
===
--- clang/test/CodeGen/complex-libcalls.c
+++ clang/test/CodeGen/complex-libcalls.c
@@ -197,10 +197,8 @@
 // HA

[PATCH] D84306: [clang-format][NFC] Be more careful about the layout of FormatToken.

2020-09-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Which bit to you find more complex? adding something to the FormatToken or the 
use of the `is()` calls?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84306

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


[PATCH] D88275: [ASTMatchers] Add matcher `hasParentIgnoringImplicit`.

2020-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 294312.
ymandel added a comment.

update dynamic registry and the ast matcher doc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88275

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -3190,6 +3190,26 @@
compoundStmt(hasParent(recordDecl();
 }
 
+TEST(HasParentIgnoringImplicit, MatchesExplicitParents) {
+  std::string Input = R"cc(
+float f() {
+int x = 3;
+int y = 3.0;
+return y;
+}
+  )cc";
+  EXPECT_TRUE(
+  matches(Input, declRefExpr(hasParentIgnoringImplicit(returnStmt();
+  EXPECT_TRUE(
+  matches(Input, floatLiteral(hasParentIgnoringImplicit(varDecl();
+  EXPECT_TRUE(
+  matches(Input, integerLiteral(hasParentIgnoringImplicit(varDecl();
+
+  // Make sure it only ignores implicit ancestors.
+  EXPECT_TRUE(
+  notMatches(Input, integerLiteral(hasParentIgnoringImplicit(declStmt();
+}
+
 TEST(HasParent, NoDuplicateParents) {
   class HasDuplicateParents : public BoundNodesCallback {
   public:
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -311,6 +311,7 @@
   REGISTER_MATCHER(hasOverloadedOperatorName);
   REGISTER_MATCHER(hasParameter);
   REGISTER_MATCHER(hasParent);
+  REGISTER_MATCHER(hasParentIgnoringImplicit);
   REGISTER_MATCHER(hasQualifier);
   REGISTER_MATCHER(hasRHS);
   REGISTER_MATCHER(hasRangeInit);
Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -544,9 +544,14 @@
 // don't invalidate any iterators.
 if (ResultCache.size() > MaxMemoizationEntries)
   ResultCache.clear();
-if (MatchMode == AncestorMatchMode::AMM_ParentOnly)
+switch (MatchMode) {
+case AncestorMatchMode::AMM_ParentOnly:
   return matchesParentOf(Node, Matcher, Builder);
-return matchesAnyAncestorOf(Node, Ctx, Matcher, Builder);
+case AncestorMatchMode::AMM_FirstExplicitOnly:
+  return matchesFirstExplicitAncestorOf(Node, Matcher, Builder);
+case AncestorMatchMode::AMM_All:
+  return matchesAnyAncestorOf(Node, Ctx, Matcher, Builder);
+}
   }
 
   // Matches all registered matchers on the given node and calls the
@@ -714,6 +719,33 @@
 return false;
   }
 
+  // Returns whether the first explicit (`Expr`) ancestor of \p Node matches \p
+  // Matcher. That is, like matchesParentOf but skipping implicit parents.
+  // Unlike matchesAnyAncestorOf there's no memoization: it doesn't save much.
+  bool matchesFirstExplicitAncestorOf(const DynTypedNode &Node,
+  const DynTypedMatcher &Matcher,
+  BoundNodesTreeBuilder *Builder) {
+for (const auto &Parent : ActiveASTContext->getParents(Node)) {
+  if (const auto *E = Parent.get())
+// If the parent is an implicit node, match on *its* parents
+// instead. Use DFS, since we expect that expressions are relatively
+// shallow.
+if (clang::isa(E) || clang::isa(E) ||
+clang::isa(E) ||
+clang::isa(E)) {
+  if (matchesFirstExplicitAncestorOf(Parent, Matcher, Builder))
+return true;
+  continue;
+}
+  BoundNodesTreeBuilder BuilderCopy = *Builder;
+  if (Matcher.matches(Parent, this, &BuilderCopy)) {
+*Builder = std::move(BuilderCopy);
+return true;
+  }
+}
+return false;
+  }
+
   // Returns whether an ancestor of \p Node matches \p Matcher.
   //
   // The order of matching (which can lead to different nodes being bound in
Index: clang/include/clang/ASTMatchers/ASTMatchersInternal.h
===
--- clang/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ clang/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -985,7 +985,11 @@
 AMM_All,
 
 /// Direct parent only.
-AMM_ParentOnly
+AMM_ParentOnly,
+
+/// Considers the first non-implicit `Expr` ancestor. Intuitively, like
+/// `ignoringImplicit` for matching parents.
+AMM_FirstExplicitOnly
   };
 
   virtual ~ASTMatchFinder() = default;
@@ -1515,6 +1519,26 @@
   }
 };
 
+/// 

[PATCH] D87528: Enable '#pragma STDC FENV_ACCESS' in frontend cf. D69272 - Work in Progress

2020-09-25 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added a comment.

In D87528#2270502 , @sepavloff wrote:

>> @sepavloff Is it OK if I continue work on this item? Not sure about the 
>> protocol when continuing someone else's patch.
>
> It is OK for me. There is also an action in Phabricator "Commandeer Revision" 
> to transfer ownership on a revision item.
>
> I don't think however that the implementation in frontend is the main 
> obstacle for enabling the pragma. It is the part of the standard and is user 
> visible, so clang must provide satisfactory support so that users could try 
> this feature in real applications. This support mainly depends on the support 
> of constrained intrinsics in IR and codegen.
>
> One of the probable ways to confirm the support is to build some pretty large 
> project that uses floating point operations extensively, build it with option 
> `-fp-model=strict` and check if it works. A good choice could be SPEC 
> benchmarks. It would provide us with not only evidence of support but also 
> with number how strict operations slow down execution. Maybe other projects 
> may be used for this purpose, but I don't know such.

I tried using the 0924 version of the patch on an internal workload SPEC 
"cpu2017" and found that a few files failed to compile because of an error 
message on static initializer, like this: struct s { float f; }; static struct 
s x = {0.63};   Compiled with ffp-model=strict "initializer..is not a 
compile-time constant"


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

https://reviews.llvm.org/D87528

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


[PATCH] D87225: [clangd] When finding refs for a renaming alias, do not return refs to underlying decls

2020-09-25 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/XRefs.cpp:1150
+  if (llvm::isa(D) || llvm::isa(D)) {
+Decls = getDeclAtPosition(AST, *CurLoc,
+  Relations | DeclRelation::Underlying);

hokein wrote:
> I think it should not happen in practice (Decls just have 1 element in most 
> cases), but the code feels hacky, we are throwing other decls if one of the 
> `Decls` is a using decl.
> 
> I suppose if we're using the same workaround as `locateASTReferent`, then we 
> should follow that way by only adjusting the UsingDecl/UnresolvedValueDecl 
> results and keeping others.
> 
> 
> In general, I think we probably need to remove this workaround (see the  
> `FIXME` in `locateASTReferent`) by refining TargetDecl API. The current 
> `DeclRelation::Underlying` enum is not enough to support our use case where 
> we only want underlying decls for *non-renaming* alias. One rough idea to fix 
> it is to split the `Underlying` to two `RenameAliasUnderlying` and 
> `RemainingUnderlying` -- this would need some API design work, so no need to 
> do it in this patch.
> 
> 
> 
I don't think we're actually throwing out the other results: by calling 
`getDeclAtPosition()` with `Relations | Underlying`, where `Relations` is the 
original flags, the call should find the other results again. If we only 
replaced the UsingDecl/UnresolvedValueDecl results, I think the other results 
would appear in duplicate.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87225

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


[PATCH] D88311: Added llvm-string-referencing check

2020-09-25 Thread Bogdan Serea via Phabricator via cfe-commits
bogser01 created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
bogser01 requested review of this revision.

Clang-tidy pass detecting the use of const std::string& references.

Use of llvm::StringRef is recommended in the LLVM Programmer's Manual instead:
https://llvm.org/docs/ProgrammersManual.html#the-stringref-class


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88311

Files:
  .gitignore
  clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.cpp
  clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
  clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp
@@ -1,23 +1,66 @@
 // RUN: %check_clang_tidy %s llvm-string-referencing %t
 
-namespace std{ 
-class string;
+namespace std {
+class string {};
+class u18_string_t;
+
 } // namespace std
 
-namespace llvm{
-class StringRef;
+namespace llvm {
+class StringRef;
 } // namespace llvm
 
-void f(std::string& P){
-// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: Use of std::string& is against LLVM guidelines [llvm-string-referencing]
-// CHECK-FIXES: void f(llvm::StringRef P){{{$}}
-return;
+class String;
+
+namespace A {
+using namespace std;
+void f(const string &P);
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f(llvm::StringRef P);{{$}}
+} // namespace A
+
+namespace B {
+using std::string;
+void f1(const string &P);
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f1(llvm::StringRef P);{{$}}
+} // namespace B
+
+void f2(std::string, int, const std::string &);
+// CHECK-MESSAGES: :[[@LINE-1]]:27: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f2(std::string, int, llvm::StringRef );{{$}}
+void f2(std::string P, int x, const std::string &P2) {
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+  // CHECK-FIXES: void f2(std::string P, int x, llvm::StringRef P2) {{{$}}
+  return;
 }
 
-void f2(int x, std::string& P){
-// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: Use of std::string& is against LLVM guidelines [llvm-string-referencing]
-// CHECK-FIXES: void f2(int x, llvm::StringRef P){{{$}}
+void f3(const std::string &P1, const std::string &P2);
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-MESSAGES: :[[@LINE-2]]:32: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f3(llvm::StringRef P1, llvm::StringRef P2);{{$}}
+
+struct St {
+  void operator=(const std::string &Val) const {
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void operator=(llvm::StringRef Val) const {{{$}}
 return;
-}
+  }
+};
+
+void f7(const std::string &);
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f7(llvm::StringRef );{{$}}
+
+// Functions below this line should not trigger the check
+void f1(std::string &P);
+
+void f4(std::string *P);
+
+void f5(String &P);
+
+void f6(llvm::StringRef P);
+
+void f9(std::u18_string_t &P);
 
-void f3(llvm::StringRef P);
+void f10(const std::string &&P);
Index: clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
===
--- clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
+++ clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
@@ -10,22 +10,33 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_LLVM_STRINGREFERENCINGCHECK_H
 
 #include "../ClangTidyCheck.h"
+#include "../utils/IncludeInserter.h"
+#include "clang/Frontend/CompilerInstance.h"
 
 namespace clang {
 namespace tidy {
 namespace llvm_check {
 
-
-/// LLVM guidelines say that llvm::StringRef should be used for function parameters instead of references to std::string.
+/// LThe LLVM Programmer's Manual recommends that llvm::StringRef should be
+/// used for function parameters instead of references to const std::string:
+/// https://llvm.org/docs/ProgrammersManual.html#the-stringref-class
 /// For the user-facing documentation see:
 /// http://clang.llvm.org/extra/clang-tidy/checks/llvm-stri

[PATCH] D87737: Add -fprofile-update={atomic,prefer-atomic,single}

2020-09-25 Thread David Li via Phabricator via cfe-commits
davidxl added a comment.

Perhaps also add clang option manual description.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87737

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


[PATCH] D88311: Added llvm-string-referencing check

2020-09-25 Thread Bogdan Serea via Phabricator via cfe-commits
bogser01 updated this revision to Diff 294331.
bogser01 added a comment.
Herald added a subscriber: mgorny.

Changed upstream


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88311

Files:
  clang-tools-extra/clang-tidy/llvm/CMakeLists.txt
  clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
  clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.cpp
  clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/llvm-string-referencing.rst
  clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp
@@ -0,0 +1,66 @@
+// RUN: %check_clang_tidy %s llvm-string-referencing %t
+
+namespace std {
+class string {};
+class u18_string_t;
+
+} // namespace std
+
+namespace llvm {
+class StringRef;
+} // namespace llvm
+
+class String;
+
+namespace A {
+using namespace std;
+void f(const string &P);
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f(llvm::StringRef P);{{$}}
+} // namespace A
+
+namespace B {
+using std::string;
+void f1(const string &P);
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f1(llvm::StringRef P);{{$}}
+} // namespace B
+
+void f2(std::string, int, const std::string &);
+// CHECK-MESSAGES: :[[@LINE-1]]:27: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f2(std::string, int, llvm::StringRef );{{$}}
+void f2(std::string P, int x, const std::string &P2) {
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+  // CHECK-FIXES: void f2(std::string P, int x, llvm::StringRef P2) {{{$}}
+  return;
+}
+
+void f3(const std::string &P1, const std::string &P2);
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-MESSAGES: :[[@LINE-2]]:32: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f3(llvm::StringRef P1, llvm::StringRef P2);{{$}}
+
+struct St {
+  void operator=(const std::string &Val) const {
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void operator=(llvm::StringRef Val) const {{{$}}
+return;
+  }
+};
+
+void f7(const std::string &);
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f7(llvm::StringRef );{{$}}
+
+// Functions below this line should not trigger the check
+void f1(std::string &P);
+
+void f4(std::string *P);
+
+void f5(String &P);
+
+void f6(llvm::StringRef P);
+
+void f9(std::u18_string_t &P);
+
+void f10(const std::string &&P);
Index: clang-tools-extra/docs/clang-tidy/checks/llvm-string-referencing.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/llvm-string-referencing.rst
@@ -0,0 +1,6 @@
+.. title:: clang-tidy - llvm-string-referencing
+
+llvm-string-referencing
+===
+
+FIXME: Describe what patterns does the check detect and why. Give examples.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -192,6 +192,7 @@
`llvm-namespace-comment `_,
`llvm-prefer-isa-or-dyn-cast-in-conditionals `_, "Yes"
`llvm-prefer-register-over-unsigned `_, "Yes"
+   `llvm-string-referencing `_, "Yes"
`llvm-twine-local `_, "Yes"
`llvmlibc-callee-namespace `_,
`llvmlibc-implementation-in-namespace `_,
Index: clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
@@ -0,0 +1,46 @@
+//===--- StringReferencingCheck.h - clang-tidy --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--

[PATCH] D87720: Sema: add support for `__attribute__((__swift_private__))`

2020-09-25 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/D87720/new/

https://reviews.llvm.org/D87720

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


[PATCH] D88312: "ErrorReturn checker" WIP review

2020-09-25 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: cfe-commits, martong, Charusso, gamesh411, Szelethus, 
dkrupp.
Herald added a reviewer: Szelethus.
Herald added a project: clang.
balazske requested review of this revision.

This is a testing version for the checker that is implemented in
D72705 . It is extended to make it usable on 
large projects.

This change it not intended to land, it is here only for
pre-evaluating the code.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88312

Files:
  clang/lib/StaticAnalyzer/Checkers/ErrorReturnChecker.cpp
  clang/test/Analysis/error-return.c

Index: clang/test/Analysis/error-return.c
===
--- clang/test/Analysis/error-return.c
+++ clang/test/Analysis/error-return.c
@@ -91,7 +91,8 @@
 }
 
 void badcheck(int X) {
-  if (X == 0) { } // expected-warning{{Use of return value that was not checked}}
+  if (X == 0) {
+  } // expected-warning{{Use of return value that was not checked}}
 }
 
 void test_EOFOrNeg_Call() {
Index: clang/lib/StaticAnalyzer/Checkers/ErrorReturnChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ErrorReturnChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ErrorReturnChecker.cpp
@@ -54,15 +54,23 @@
 public:
   /// Test if an encountered binary operator where the return value is involved
   /// is a valid check statement. The return value appears in one side of the
-  /// operator (`ChildIsLHS` indicates if it is on the LHS). If the other side
-  /// contains a known (mostly constant) value, it is already calculated in
-  /// `KnownValue`. `RetTy` is the type of the return value (return type of the
-  /// function call in the code to check).
+  /// operator (`ChildIsLHS` indicates if it is on the LHS). The other side is
+  /// the value to test against, its "known value" is passed in
+  /// `ValueToTestAgainst. `RetTy` is the return type of the function.
+  // testAppearanceInBinOp
   virtual bool testBinOpForCheckStatement(BasicValueFactory &BVF,
   const BinaryOperator *BinOp,
-  const llvm::APSInt *KnownValue,
+  const llvm::APSInt *ValueToTestAgainst,
   QualType RetTy,
   bool ChildIsLHS) const = 0;
+
+  virtual bool testUnaryOp(BasicValueFactory &BVF,
+  const UnaryOperator *UnOp,
+  QualType RetTy) const = 0;
+
+  /// Tell if the bare appearance of the return value in place of a condition (for example 'X' in 'if (X)') can be taken as a check for error return value.
+  // testAppearanceInCondition
+  virtual bool testConditionForCheckStatement() const = 0;
 };
 
 /// Error return is a -1 or any negative value (both is accepted).
@@ -73,28 +81,28 @@
 public:
   bool testBinOpForCheckStatement(BasicValueFactory &BVF,
   const BinaryOperator *BinOp,
-  const llvm::APSInt *KnownValue,
+  const llvm::APSInt *ValueToTestAgainst,
   QualType RetTy,
   bool ChildIsLHS) const override {
-if (!KnownValue)
-  return false;
+if (!ValueToTestAgainst)
+  return true;
 
-bool KnownNull = KnownValue->isNullValue();
-bool KnownEOF = ((*KnownValue) == BVF.getValue(-1, RetTy));
+bool NullFound = ValueToTestAgainst->isNullValue();
+bool EOFFound = ((*ValueToTestAgainst) == BVF.getValue(-1, RetTy));
 
 if (ChildIsLHS) {
   switch (BinOp->getOpcode()) {
   case BO_EQ: // 'X == -1'
   case BO_NE: // 'X != -1'
-return KnownEOF;
+return EOFFound;
   case BO_LT: // 'X < 0'
-return KnownNull;
+return NullFound;
   case BO_GE: // 'X >= 0'
-return KnownNull;
+return NullFound;
   case BO_LE: // 'X <= -1'
-return KnownEOF;
+return EOFFound;
   case BO_GT: // 'X > -1'
-return KnownEOF;
+return EOFFound;
   default:
 return false;
   }
@@ -102,21 +110,77 @@
   switch (BinOp->getOpcode()) {
   case BO_EQ: // '-1 == X'
   case BO_NE: // '-1 != X'
-return KnownEOF;
+return EOFFound;
   case BO_GT: // '0 > X'
-return KnownNull;
+return NullFound;
   case BO_LE: // '0 <= X'
-return KnownNull;
+return NullFound;
   case BO_GE: // '-1 >= X'
-return KnownEOF;
+return EOFFound;
   case BO_LT: // '-1 < X'
-return KnownEOF;
+return EOFFound;
   default:
 return false;
   }
 }
 return false;
   }
+
+  bool testUnaryOp(BasicValueFactory &BVF, const UnaryOperator *UnOp,
+

[PATCH] D72705: [analyzer] Added new checker 'alpha.unix.ErrorReturn'.

2020-09-25 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

A improved version of the checker is added for further discussion (or should 
continue here?) and to show the improved checker code.
See D88312 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72705

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


[PATCH] D88312: "ErrorReturn checker" WIP review

2020-09-25 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Here are the results 

 with this checker on project 'emacs`.
Still more evaluation is needed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88312

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


[PATCH] D65880: [Driver] Move LIBRARY_PATH before user inputs

2020-09-25 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D65880#2294871 , @protze.joachim 
wrote:

> I still see some clang-specific and system link directories listed in the 
> linker line before the directories from `LIBRARY_PATH`:
>
>   $ LIBRARY_PATH=test1 /usr/local/clang/bin/clang -Ltest2 -v hello.c
>"/usr/bin/ld" .../crtbegin.o -Ltest2 
> -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5 
> -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64 -L/lib/../lib64 
> -L/usr/lib/../lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../.. 
> -L/usr/local/clang/bin/../lib -L/lib -L/usr/lib -Ltest1
>
> I think they are inserted by `ToolChain.AddFilePathLibArgs` in Gnu.cpp. Is 
> this the intended ordering? My expectation would be
>
>   $ LIBRARY_PATH=test1 /usr/local/clang/bin/clang -Ltest2 -v hello.c
>"/usr/bin/ld" .../crtbegin.o -Ltest2 -Ltest1 
> -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5 
> -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64 -L/lib/../lib64 
> -L/usr/lib/../lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../.. 
> -L/usr/local/clang/bin/../lib -L/lib -L/usr/lib
>
> @hfinkel any opinion?

In GCC, some system directories precede LIBRARY_PATH. I don't know the exact 
rule yet (but this patch made the behavior more similar)

  % mkdir test1
  % LIBRARY_PATH=test1 gcc-10 -Ltest2 -v a.c
  ...
  
LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/10/:/usr/lib/gcc/x86_64-linux-gnu/10/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/10/../../../../lib/:/l
  
ib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:test1/:/usr/lib/gcc/x86_64-linux-gnu/10/../../../:/lib/:/usr/lib/


Repository:
  rL LLVM

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

https://reviews.llvm.org/D65880

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


[PATCH] D88314: Added llvm-string-referencing check

2020-09-25 Thread Bogdan Serea via Phabricator via cfe-commits
bogser01 created this revision.
Herald added subscribers: cfe-commits, mgorny.
Herald added a project: clang.
bogser01 requested review of this revision.

Clang-tidy pass detecting the use of const std::string& references.

Use of llvm::StringRef is recommended in the LLVM Programmer's Manual instead:
https://llvm.org/docs/ProgrammersManual.html#the-stringref-class


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88314

Files:
  clang-tools-extra/clang-tidy/llvm/CMakeLists.txt
  clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
  clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.cpp
  clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/llvm-string-referencing.rst
  clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/llvm-string-referencing.cpp
@@ -0,0 +1,66 @@
+// RUN: %check_clang_tidy %s llvm-string-referencing %t
+
+namespace std {
+class string {};
+class u18_string_t;
+
+} // namespace std
+
+namespace llvm {
+class StringRef;
+} // namespace llvm
+
+class String;
+
+namespace A {
+using namespace std;
+void f(const string &P);
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f(llvm::StringRef P);{{$}}
+} // namespace A
+
+namespace B {
+using std::string;
+void f1(const string &P);
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f1(llvm::StringRef P);{{$}}
+} // namespace B
+
+void f2(std::string, int, const std::string &);
+// CHECK-MESSAGES: :[[@LINE-1]]:27: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f2(std::string, int, llvm::StringRef );{{$}}
+void f2(std::string P, int x, const std::string &P2) {
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+  // CHECK-FIXES: void f2(std::string P, int x, llvm::StringRef P2) {{{$}}
+  return;
+}
+
+void f3(const std::string &P1, const std::string &P2);
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-MESSAGES: :[[@LINE-2]]:32: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f3(llvm::StringRef P1, llvm::StringRef P2);{{$}}
+
+struct St {
+  void operator=(const std::string &Val) const {
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void operator=(llvm::StringRef Val) const {{{$}}
+return;
+  }
+};
+
+void f7(const std::string &);
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: Use of const std::string & is discouraged in the LLVM Programmer's Manual [llvm-string-referencing]
+// CHECK-FIXES: void f7(llvm::StringRef );{{$}}
+
+// Functions below this line should not trigger the check
+void f1(std::string &P);
+
+void f4(std::string *P);
+
+void f5(String &P);
+
+void f6(llvm::StringRef P);
+
+void f9(std::u18_string_t &P);
+
+void f10(const std::string &&P);
Index: clang-tools-extra/docs/clang-tidy/checks/llvm-string-referencing.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/llvm-string-referencing.rst
@@ -0,0 +1,6 @@
+.. title:: clang-tidy - llvm-string-referencing
+
+llvm-string-referencing
+===
+
+FIXME: Describe what patterns does the check detect and why. Give examples.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -192,6 +192,7 @@
`llvm-namespace-comment `_,
`llvm-prefer-isa-or-dyn-cast-in-conditionals `_, "Yes"
`llvm-prefer-register-over-unsigned `_, "Yes"
+   `llvm-string-referencing `_, "Yes"
`llvm-twine-local `_, "Yes"
`llvmlibc-callee-namespace `_,
`llvmlibc-implementation-in-namespace `_,
Index: clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/llvm/StringReferencingCheck.h
@@ -0,0 +1,46 @@
+//===--- StringReferencingCheck.h - clang-tidy --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 

[PATCH] D87946: [OpenMP] Add Location Fields to Libomptarget Runtime for Debugging

2020-09-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

One minor remark from me, otherwise LGTM. @grokos Any concerns or is this OK?




Comment at: openmp/libomptarget/src/interface.cpp:73-76
+  FATAL_MESSAGE0(1, "failure of target construct while offloading is 
mandatory");
+}
+else 
+  FATAL_MESSAGE0(1, "failure of target construct while offloading is 
mandatory");

also check if `info` has an actual location please. If line and column are 0, 
print a message that `-g` can help provide source location information.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87946

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


[PATCH] D87187: [Driver] Perform Linux distribution detection just once

2020-09-25 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea accepted this revision.
aganea added a comment.

Makes sense, you cache the commonly taken path, but not the (very uncommon) VFS 
codepath.

LGTM, with some minor comments. Thanks again!




Comment at: clang/include/clang/Driver/Distro.h:117
 
-  bool IsOpenSUSE() const {
-return DistroVal == OpenSUSE;
-  }
+  bool IsOpenSUSE() const { return DistroVal == OpenSUSE; }
 

Please leave out code that doesn't participate in the patch. You can always 
commit NFC patches afterward with just `clang-format` changes if you wish. It's 
fine though if you move code around.



Comment at: clang/lib/Driver/Distro.cpp:225
+static Distro::DistroType LinuxDistro = Distro::UninitializedDistro;
+static llvm::once_flag DistroDetectFlag;
+// If we're backed by a real file system, perform

You can leave out the `once_flag`/`call_once` and simply apply Reid's 
suggestion, since  they are equivalent (static initialization is thread safe 
[1]):
```
if (onRealFS) {
  static Distro::DistroType LinuxDistro = DetectDistro(VFS);
  return LinuxDistro;
}
```
[1] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf, section 
6.7.4 "If control enters the declaration concurrently while the variable is 
being initialized, the concurrent execution shall wait for completion of the 
initialization"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87187

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


[PATCH] D87528: Enable '#pragma STDC FENV_ACCESS' in frontend cf. D69272 - Work in Progress

2020-09-25 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added inline comments.



Comment at: clang/test/CodeGen/fp-floatcontrol-pragma.cpp:154
+  if (i<0)
+  return 1.0 + 2.0;
+  // Check that floating point constant folding doesn't occur if

sepavloff wrote:
> In this particular case we know for sure that the result does not depend on 
> rounding mode and no FP exceptions occurs, so it is safe to constfold the 
> expression.
> 
> Expressions like `1.0 / 0.0` or `1.0F + 0x0.01p0F` indeed may require 
> execution in runtime, depending on the required exception handling. I would 
> propose to connect their const-evaluability with `FPExceptionMode` and set 
> the latter to `strict` whenever `AllowFEnvAccess` is set to `true`. 
Thank you, I will study these remarks.  BTW I had inserted checks to verify 
semantic rules about the use of pragma float_control and fenv_access, to follow 
what Microsoft describes on this page, 
https://docs.microsoft.com/en-us/cpp/preprocessor/fenv-access?view=vs-2019 
Quoting:
There are restrictions on the ways you can use the fenv_access pragma in 
combination with other floating-point settings:

You can't enable fenv_access unless precise semantics are enabled. Precise 
semantics can be enabled either by the float_control pragma, or by using the 
/fp:precise or /fp:strict compiler options. The compiler defaults to 
/fp:precise if no other floating-point command-line option is specified.

You can't use float_control to disable precise semantics when fenv_access(on) 
is set.


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

https://reviews.llvm.org/D87528

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


[PATCH] D88275: [ASTMatchers] Add matcher `hasParentIgnoringImplicit`.

2020-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 294348.
ymandel added a comment.

Fixed to use more standard type adaptors. Registration now works.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88275

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -3190,6 +3190,26 @@
compoundStmt(hasParent(recordDecl();
 }
 
+TEST(HasParentIgnoringImplicit, MatchesExplicitParents) {
+  std::string Input = R"cc(
+float f() {
+int x = 3;
+int y = 3.0;
+return y;
+}
+  )cc";
+  EXPECT_TRUE(
+  matches(Input, declRefExpr(hasParentIgnoringImplicit(returnStmt();
+  EXPECT_TRUE(
+  matches(Input, floatLiteral(hasParentIgnoringImplicit(varDecl();
+  EXPECT_TRUE(
+  matches(Input, integerLiteral(hasParentIgnoringImplicit(varDecl();
+
+  // Make sure it only ignores implicit ancestors.
+  EXPECT_TRUE(
+  notMatches(Input, integerLiteral(hasParentIgnoringImplicit(declStmt();
+}
+
 TEST(HasParent, NoDuplicateParents) {
   class HasDuplicateParents : public BoundNodesCallback {
   public:
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -311,6 +311,7 @@
   REGISTER_MATCHER(hasOverloadedOperatorName);
   REGISTER_MATCHER(hasParameter);
   REGISTER_MATCHER(hasParent);
+  REGISTER_MATCHER(hasParentIgnoringImplicit);
   REGISTER_MATCHER(hasQualifier);
   REGISTER_MATCHER(hasRHS);
   REGISTER_MATCHER(hasRangeInit);
Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -544,9 +544,14 @@
 // don't invalidate any iterators.
 if (ResultCache.size() > MaxMemoizationEntries)
   ResultCache.clear();
-if (MatchMode == AncestorMatchMode::AMM_ParentOnly)
+switch (MatchMode) {
+case AncestorMatchMode::AMM_ParentOnly:
   return matchesParentOf(Node, Matcher, Builder);
-return matchesAnyAncestorOf(Node, Ctx, Matcher, Builder);
+case AncestorMatchMode::AMM_FirstExplicitOnly:
+  return matchesFirstExplicitAncestorOf(Node, Matcher, Builder);
+case AncestorMatchMode::AMM_All:
+  return matchesAnyAncestorOf(Node, Ctx, Matcher, Builder);
+}
   }
 
   // Matches all registered matchers on the given node and calls the
@@ -714,6 +719,33 @@
 return false;
   }
 
+  // Returns whether the first explicit (`Expr`) ancestor of \p Node matches \p
+  // Matcher. That is, like matchesParentOf but skipping implicit parents.
+  // Unlike matchesAnyAncestorOf there's no memoization: it doesn't save much.
+  bool matchesFirstExplicitAncestorOf(const DynTypedNode &Node,
+  const DynTypedMatcher &Matcher,
+  BoundNodesTreeBuilder *Builder) {
+for (const auto &Parent : ActiveASTContext->getParents(Node)) {
+  if (const auto *E = Parent.get())
+// If the parent is an implicit node, match on *its* parents
+// instead. Use DFS, since we expect that expressions are relatively
+// shallow.
+if (clang::isa(E) || clang::isa(E) ||
+clang::isa(E) ||
+clang::isa(E)) {
+  if (matchesFirstExplicitAncestorOf(Parent, Matcher, Builder))
+return true;
+  continue;
+}
+  BoundNodesTreeBuilder BuilderCopy = *Builder;
+  if (Matcher.matches(Parent, this, &BuilderCopy)) {
+*Builder = std::move(BuilderCopy);
+return true;
+  }
+}
+return false;
+  }
+
   // Returns whether an ancestor of \p Node matches \p Matcher.
   //
   // The order of matching (which can lead to different nodes being bound in
Index: clang/include/clang/ASTMatchers/ASTMatchersInternal.h
===
--- clang/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ clang/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -985,7 +985,11 @@
 AMM_All,
 
 /// Direct parent only.
-AMM_ParentOnly
+AMM_ParentOnly,
+
+/// Considers the first non-implicit `Expr` ancestor. Intuitively, like
+/// `ignoringImplicit` for matching parents.
+AMM_FirstExplicitOnly
   };
 
   virtual ~ASTMatchFinder() = default;
@@ -1515,6 +1519,33 @@

[clang] 62c3727 - [profile] Add %t LLVM_PROFILE_FILE option to substitute $TMPDIR

2020-09-25 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-09-25T09:39:40-07:00
New Revision: 62c372770d2e87f3e882a20d43c6814e6c4fe0f5

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

LOG: [profile] Add %t LLVM_PROFILE_FILE option to substitute $TMPDIR

Add support for expanding the %t filename specifier in LLVM_PROFILE_FILE
to the TMPDIR environment variable. This is supported on all platforms.

On Darwin, TMPDIR is used to specify a temporary application-specific
scratch directory. When testing apps on remote devices, it can be
challenging for the host device to determine the correct TMPDIR, so it's
helpful to have the runtime do this work.

rdar://68524185

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

Added: 
compiler-rt/test/profile/instrprof-tmpdir.c

Modified: 
clang/docs/SourceBasedCodeCoverage.rst
compiler-rt/lib/profile/InstrProfilingFile.c

Removed: 




diff  --git a/clang/docs/SourceBasedCodeCoverage.rst 
b/clang/docs/SourceBasedCodeCoverage.rst
index 0e9c364fbf6b..f5b3d05262e9 100644
--- a/clang/docs/SourceBasedCodeCoverage.rst
+++ b/clang/docs/SourceBasedCodeCoverage.rst
@@ -79,6 +79,9 @@ directory structure will be created.  Additionally, the 
following special
 
 * "%h" expands out to the hostname of the machine running the program.
 
+* "%t" expands out to the value of the ``TMPDIR`` environment variable. On
+  Darwin, this is typically set to a temporary scratch directory.
+
 * "%Nm" expands out to the instrumented binary's signature. When this pattern
   is specified, the runtime creates a pool of N raw profiles which are used for
   on-line profile merging. The runtime takes care of selecting a raw profile

diff  --git a/compiler-rt/lib/profile/InstrProfilingFile.c 
b/compiler-rt/lib/profile/InstrProfilingFile.c
index 8c7bb0c25de1..b43f91794e28 100644
--- a/compiler-rt/lib/profile/InstrProfilingFile.c
+++ b/compiler-rt/lib/profile/InstrProfilingFile.c
@@ -72,6 +72,7 @@ typedef struct lprofFilename {
   unsigned OwnsFilenamePat;
   const char *ProfilePathPrefix;
   char PidChars[MAX_PID_SIZE];
+  char *TmpDir;
   char Hostname[COMPILER_RT_MAX_HOSTLEN];
   unsigned NumPids;
   unsigned NumHosts;
@@ -86,8 +87,8 @@ typedef struct lprofFilename {
   ProfileNameSpecifier PNS;
 } lprofFilename;
 
-static lprofFilename lprofCurFilename = {0, 0, 0, {0},{0},
- 0, 0, 0, PNS_unknown};
+static lprofFilename lprofCurFilename = {0,   0, 0, {0}, NULL,
+ {0}, 0, 0, 0,   PNS_unknown};
 
 static int ProfileMergeRequested = 0;
 static int isProfileMergeRequested() { return ProfileMergeRequested; }
@@ -744,6 +745,14 @@ static int parseFilenamePattern(const char *FilenamePat,
   FilenamePat);
 return -1;
   }
+  } else if (FilenamePat[I] == 't') {
+lprofCurFilename.TmpDir = getenv("TMPDIR");
+if (!lprofCurFilename.TmpDir) {
+  PROF_WARN("Unable to get the TMPDIR environment variable, referenced 
"
+"in %s. Using the default path.",
+FilenamePat);
+  return -1;
+}
   } else if (FilenamePat[I] == 'c') {
 if (__llvm_profile_is_continuous_mode_enabled()) {
   PROF_WARN("%%c specifier can only be specified once in %s.\n",
@@ -827,12 +836,13 @@ static int getCurFilenameLength() {
 return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-lprofCurFilename.MergePoolSize))
+lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize))
 return strlen(lprofCurFilename.FilenamePat);
 
   Len = strlen(lprofCurFilename.FilenamePat) +
 lprofCurFilename.NumPids * (strlen(lprofCurFilename.PidChars) - 2) +
-lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2);
+lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2) +
+(lprofCurFilename.TmpDir ? (strlen(lprofCurFilename.TmpDir) - 1) : 0);
   if (lprofCurFilename.MergePoolSize)
 Len += SIGLEN;
   return Len;
@@ -844,14 +854,14 @@ static int getCurFilenameLength() {
  * current filename pattern string is directly returned, unless ForceUseBuf
  * is enabled. */
 static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
-  int I, J, PidLength, HostNameLength, FilenamePatLength;
+  int I, J, PidLength, HostNameLength, TmpDirLength, FilenamePatLength;
   const char *FilenamePat = lprofCurFilename.FilenamePat;
 
   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
 return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-lprofCurFilename.MergePoolSize ||
+lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize ||
 __llvm_profile_is_continuous_mode_

[PATCH] D87332: [profile] Add %t LLVM_PROFILE_FILE option to substitute $TMPDIR

2020-09-25 Thread Vedant Kumar via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG62c372770d2e: [profile] Add %t LLVM_PROFILE_FILE option to 
substitute $TMPDIR (authored by vsk).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87332

Files:
  clang/docs/SourceBasedCodeCoverage.rst
  compiler-rt/lib/profile/InstrProfilingFile.c
  compiler-rt/test/profile/instrprof-tmpdir.c

Index: compiler-rt/test/profile/instrprof-tmpdir.c
===
--- /dev/null
+++ compiler-rt/test/profile/instrprof-tmpdir.c
@@ -0,0 +1,22 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: cd %t
+// RUN: %clang_profgen -o %t/binary %s
+//
+// Check that a dir separator is appended after %t is subsituted.
+// RUN: env TMPDIR="%t" LLVM_PROFILE_FILE="%%traw1.profraw" %run ./binary
+// RUN: llvm-profdata show ./raw1.profraw | FileCheck %s -check-prefix TMPDIR
+//
+// Check that substitution works even if a redundant dir separator is added.
+// RUN: env TMPDIR="%t" LLVM_PROFILE_FILE="%%t/raw2.profraw" %run ./binary
+// RUN: llvm-profdata show ./raw2.profraw | FileCheck %s -check-prefix TMPDIR
+//
+// Check that we fall back to the default path if TMPDIR is missing.
+// RUN: env -u TMPDIR LLVM_PROFILE_FILE="%%t/raw3.profraw" %run ./binary 2>&1 | FileCheck %s -check-prefix MISSING
+// RUN: llvm-profdata show ./default.profraw | FileCheck %s -check-prefix TMPDIR
+
+// TMPDIR: Maximum function count: 1
+
+// MISSING: Unable to get the TMPDIR environment variable, referenced in {{.*}}raw3.profraw. Using the default path.
+
+int main() { return 0; }
Index: compiler-rt/lib/profile/InstrProfilingFile.c
===
--- compiler-rt/lib/profile/InstrProfilingFile.c
+++ compiler-rt/lib/profile/InstrProfilingFile.c
@@ -72,6 +72,7 @@
   unsigned OwnsFilenamePat;
   const char *ProfilePathPrefix;
   char PidChars[MAX_PID_SIZE];
+  char *TmpDir;
   char Hostname[COMPILER_RT_MAX_HOSTLEN];
   unsigned NumPids;
   unsigned NumHosts;
@@ -86,8 +87,8 @@
   ProfileNameSpecifier PNS;
 } lprofFilename;
 
-static lprofFilename lprofCurFilename = {0, 0, 0, {0},{0},
- 0, 0, 0, PNS_unknown};
+static lprofFilename lprofCurFilename = {0,   0, 0, {0}, NULL,
+ {0}, 0, 0, 0,   PNS_unknown};
 
 static int ProfileMergeRequested = 0;
 static int isProfileMergeRequested() { return ProfileMergeRequested; }
@@ -744,6 +745,14 @@
   FilenamePat);
 return -1;
   }
+  } else if (FilenamePat[I] == 't') {
+lprofCurFilename.TmpDir = getenv("TMPDIR");
+if (!lprofCurFilename.TmpDir) {
+  PROF_WARN("Unable to get the TMPDIR environment variable, referenced "
+"in %s. Using the default path.",
+FilenamePat);
+  return -1;
+}
   } else if (FilenamePat[I] == 'c') {
 if (__llvm_profile_is_continuous_mode_enabled()) {
   PROF_WARN("%%c specifier can only be specified once in %s.\n",
@@ -827,12 +836,13 @@
 return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-lprofCurFilename.MergePoolSize))
+lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize))
 return strlen(lprofCurFilename.FilenamePat);
 
   Len = strlen(lprofCurFilename.FilenamePat) +
 lprofCurFilename.NumPids * (strlen(lprofCurFilename.PidChars) - 2) +
-lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2);
+lprofCurFilename.NumHosts * (strlen(lprofCurFilename.Hostname) - 2) +
+(lprofCurFilename.TmpDir ? (strlen(lprofCurFilename.TmpDir) - 1) : 0);
   if (lprofCurFilename.MergePoolSize)
 Len += SIGLEN;
   return Len;
@@ -844,14 +854,14 @@
  * current filename pattern string is directly returned, unless ForceUseBuf
  * is enabled. */
 static const char *getCurFilename(char *FilenameBuf, int ForceUseBuf) {
-  int I, J, PidLength, HostNameLength, FilenamePatLength;
+  int I, J, PidLength, HostNameLength, TmpDirLength, FilenamePatLength;
   const char *FilenamePat = lprofCurFilename.FilenamePat;
 
   if (!lprofCurFilename.FilenamePat || !lprofCurFilename.FilenamePat[0])
 return 0;
 
   if (!(lprofCurFilename.NumPids || lprofCurFilename.NumHosts ||
-lprofCurFilename.MergePoolSize ||
+lprofCurFilename.TmpDir || lprofCurFilename.MergePoolSize ||
 __llvm_profile_is_continuous_mode_enabled())) {
 if (!ForceUseBuf)
   return lprofCurFilename.FilenamePat;
@@ -864,6 +874,7 @@
 
   PidLength = strlen(lprofCurFilename.PidChars);
   HostNameLength = strlen(lprofCurFilename.Hostname);
+  TmpDirLength = lprofCurFilename.TmpDir ? strlen(lprofCurFilename.TmpDir) : 0;
   /* Construct the new filename. */
   for (I = 0, J = 0; FilenameP

[PATCH] D87946: [OpenMP] Add Location Fields to Libomptarget Runtime for Debugging

2020-09-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 294352.
jhuber6 added a comment.

Adding message to build with debugging symbols if source location is not found.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87946

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/capturing_in_templates.cpp
  clang/test/OpenMP/declare_target_link_codegen.cpp
  clang/test/OpenMP/distribute_codegen.cpp
  clang/test/OpenMP/distribute_firstprivate_codegen.cpp
  clang/test/OpenMP/distribute_lastprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_firstprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_if_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_lastprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_num_threads_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_private_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_proc_bind_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_reduction_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_firstprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_if_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_lastprivate_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_num_threads_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_private_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_proc_bind_codegen.cpp
  clang/test/OpenMP/distribute_private_codegen.cpp
  clang/test/OpenMP/distribute_simd_codegen.cpp
  clang/test/OpenMP/distribute_simd_firstprivate_codegen.cpp
  clang/test/OpenMP/distribute_simd_lastprivate_codegen.cpp
  clang/test/OpenMP/distribute_simd_private_codegen.cpp
  clang/test/OpenMP/distribute_simd_reduction_codegen.cpp
  clang/test/OpenMP/nvptx_lambda_capturing.cpp
  clang/test/OpenMP/nvptx_lambda_pointer_capturing.cpp
  clang/test/OpenMP/nvptx_target_requires_unified_shared_memory.cpp
  clang/test/OpenMP/openmp_offload_codegen.cpp
  clang/test/OpenMP/target_codegen.cpp
  clang/test/OpenMP/target_data_codegen.cpp
  clang/test/OpenMP/target_data_use_device_addr_codegen.cpp
  clang/test/OpenMP/target_defaultmap_codegen.cpp
  clang/test/OpenMP/target_device_codegen.cpp
  clang/test/OpenMP/target_enter_data_codegen.cpp
  clang/test/OpenMP/target_enter_data_depend_codegen.cpp
  clang/test/OpenMP/target_exit_data_codegen.cpp
  clang/test/OpenMP/target_exit_data_depend_codegen.cpp
  clang/test/OpenMP/target_firstprivate_codegen.cpp
  clang/test/OpenMP/target_is_device_ptr_codegen.cpp
  clang/test/OpenMP/target_map_codegen_00.cpp
  clang/test/OpenMP/target_map_codegen_01.cpp
  clang/test/OpenMP/target_map_codegen_02.cpp
  clang/test/OpenMP/target_map_codegen_03.cpp
  clang/test/OpenMP/target_map_codegen_04.cpp
  clang/test/OpenMP/target_map_codegen_05.cpp
  clang/test/OpenMP/target_map_codegen_06.cpp
  clang/test/OpenMP/target_map_codegen_07.cpp
  clang/test/OpenMP/target_map_codegen_08.cpp
  clang/test/OpenMP/target_map_codegen_09.cpp
  clang/test/OpenMP/target_map_codegen_10.cpp
  clang/test/OpenMP/target_map_codegen_11.cpp
  clang/test/OpenMP/target_map_codegen_12.cpp
  clang/test/OpenMP/target_map_codegen_13.cpp
  clang/test/OpenMP/target_map_codegen_14.cpp
  clang/test/OpenMP/target_map_codegen_15.cpp
  clang/test/OpenMP/target_map_codegen_16.cpp
  clang/test/OpenMP/target_map_codegen_17.cpp
  clang/test/OpenMP/target_map_codegen_18.inc
  clang/test/OpenMP/target_map_codegen_19.cpp
  clang/test/OpenMP/target_map_codegen_20.cpp
  clang/test/OpenMP/target_map_codegen_21.cpp
  clang/test/OpenMP/target_map_codegen_22.cpp
  clang/test/OpenMP/target_map_codegen_23.cpp
  clang/test/OpenMP/target_map_codegen_24.cpp
  clang/test/OpenMP/target_map_codegen_25.cpp
  clang/test/OpenMP/target_map_codegen_26.cpp
  clang/test/OpenMP/target_map_codegen_27.cpp
  clang/test/OpenMP/target_map_codegen_28.cpp
  clang/test/OpenMP/target_map_codegen_29.cpp
  clang/test/OpenMP/target_map_codegen_30.cpp
  clang/test/OpenMP/target_map_codegen_31.cpp
  clang/test/OpenMP/target_map_codegen_32.cpp
  clang/test/OpenMP/target_map_codegen_33.cpp
  clang/test/OpenMP/target_map_member_expr_array_section_codegen.cpp
  clang/test/OpenMP/target_parallel_codegen.cpp
  clang/test/OpenMP/target_parallel_depend_codegen.cpp
  clang/test/OpenMP/target_parallel_for_codegen.cpp
  clang/test/OpenMP/target_parallel_for_depend_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_depend_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_parallel_for_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_parallel_if_codegen.cpp
  clang/test/OpenMP/target_parallel_num_threads_codegen.cpp
  clang/test/OpenMP/target_parallel_uses_allocators_codegen.cpp
  clang/test/Op

[PATCH] D88319: [AST] Delete broken, unused template.

2020-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: gribozavr2.
Herald added a project: clang.
ymandel requested review of this revision.

The `const*` overload of `IgnoreExprNodes` can't compile. Moreover, this didn't
turn up because it's unused.  There's no obvious fix, so I've deleted it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88319

Files:
  clang/include/clang/AST/IgnoreExpr.h


Index: clang/include/clang/AST/IgnoreExpr.h
===
--- clang/include/clang/AST/IgnoreExpr.h
+++ clang/include/clang/AST/IgnoreExpr.h
@@ -39,11 +39,6 @@
   return E;
 }
 
-template 
-const Expr *IgnoreExprNodes(const Expr *E, FnTys &&...Fns) {
-  return const_cast(IgnoreExprNodes(E, std::forward(Fns)...));
-}
-
 inline Expr *IgnoreImplicitCastsSingleStep(Expr *E) {
   if (auto *ICE = dyn_cast(E))
 return ICE->getSubExpr();


Index: clang/include/clang/AST/IgnoreExpr.h
===
--- clang/include/clang/AST/IgnoreExpr.h
+++ clang/include/clang/AST/IgnoreExpr.h
@@ -39,11 +39,6 @@
   return E;
 }
 
-template 
-const Expr *IgnoreExprNodes(const Expr *E, FnTys &&...Fns) {
-  return const_cast(IgnoreExprNodes(E, std::forward(Fns)...));
-}
-
 inline Expr *IgnoreImplicitCastsSingleStep(Expr *E) {
   if (auto *ICE = dyn_cast(E))
 return ICE->getSubExpr();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87946: [OpenMP] Add Location Fields to Libomptarget Runtime for Debugging

2020-09-25 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

Should we wait until the next OpenMP LLVM meeting to push this?




Comment at: openmp/libomptarget/include/Ident.h:48-51
+auto removePath = [](const std::string &path) {
+std::size_t pos = path.rfind('/');
+return path.substr(pos + 1);
+};

This will probably break with a Windows file path, but I don't think you can 
even build most offloading if you're on Windows. Should I just add a processor 
check?

```
#ifdef _WIN32
#define PATH_DELIMITER '\\'
#else
#define PATH_DELIMITER '/'
#endif
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87946

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


[PATCH] D87989: [Flang][Driver] Add InputOutputTest frontend action with new -test-IO flag

2020-09-25 Thread Caroline via Phabricator via cfe-commits
CarolineConcatto updated this revision to Diff 294356.
CarolineConcatto added a comment.

Rebase on top of master


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87989

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/lib/Driver/Types.cpp
  clang/test/Driver/immediate-options.c
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/include/flang/Frontend/FrontendAction.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/include/flang/FrontendTool/Utils.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInstance.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendAction.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/FrontendOptions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Flang-Driver/driver-help-hidden.f90
  flang/test/Flang-Driver/driver-help.f90
  flang/test/Flang-Driver/emit-obj.f90
  flang/test/Frontend/Inputs/hello-world.f90
  flang/test/Frontend/input-output-file.f90
  flang/test/Frontend/multiple-input-files.f90
  flang/test/lit.cfg.py
  flang/tools/flang-driver/fc1_main.cpp
  flang/unittests/Frontend/CMakeLists.txt
  flang/unittests/Frontend/CompilerInstanceTest.cpp
  flang/unittests/Frontend/InputOutputTest.cpp
  llvm/lib/Option/OptTable.cpp

Index: llvm/lib/Option/OptTable.cpp
===
--- llvm/lib/Option/OptTable.cpp
+++ llvm/lib/Option/OptTable.cpp
@@ -639,6 +639,7 @@
   continue;
 
 unsigned Flags = getInfo(Id).Flags;
+
 if (FlagsToInclude && !(Flags & FlagsToInclude))
   continue;
 if (Flags & FlagsToExclude)
Index: flang/unittests/Frontend/InputOutputTest.cpp
===
--- /dev/null
+++ flang/unittests/Frontend/InputOutputTest.cpp
@@ -0,0 +1,65 @@
+//===- unittests/Frontend/OutputStreamTest.cpp --- FrontendAction tests --===//
+//
+// 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 "flang/Frontend/CompilerInstance.h"
+#include "flang/Frontend/CompilerInvocation.h"
+#include "flang/Frontend/FrontendOptions.h"
+#include "flang/FrontendTool/Utils.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/raw_ostream.h"
+#include "gtest/gtest.h"
+
+using namespace Fortran::frontend;
+#include 
+
+namespace {
+
+TEST(FrontendOutputTests, TestInputOutputStreamOwned) {
+  // 1. Prepare the input file to be used by IO
+  // Create the file to be used by AllSources
+  // Flang function 'FortranAllSources.Open' needs a physical file
+  // and the full path to work with
+  std::string inputFilename = "io-file-test.f";
+  std::error_code ec;
+  std::unique_ptr os{
+  new llvm::raw_fd_ostream(inputFilename, ec, llvm::sys::fs::OF_None)};
+  if (ec)
+llvm::errs() << "Fail to create the file need by the test";
+  *(os) << "End Program arithmetic";
+  os.reset();
+  std::string getFileFullPath = std::filesystem::current_path().c_str();
+  getFileFullPath = getFileFullPath + "/" + inputFilename;
+
+  // 2. Prepare the compiler (Invocation + Instance)
+  CompilerInstance compInst;
+  compInst.CreateDiagnostics();
+  auto invocation = std::make_shared();
+  invocation->GetFrontendOpts().programAction_ = InputOutputTest;
+  compInst.SetInvocation(std::move(invocation));
+  compInst.GetFrontendOpts().inputs_.push_back(
+  FrontendInputFile(/*File=*/getFileFullPath, Language::Fortran));
+
+  // 3. Set-up the output stream. Using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst.SetOutputStream(std::move(outputFileStream));
+
+  // 4. Run the earlier defined FrontendAction
+  bool success = ExecuteCompilerInvocation(&compInst);
+
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .startswith("End Program arithmetic"));
+
+  // 5. Remove files
+  compInst.ClearOutputFiles(/*EraseFiles=*/false);
+}
+} // namespace
\ No newline at end of file
Index: flang/unittests/Frontend/CompilerInstanceTest.cpp
===
--- flang/unittests/Frontend/CompilerInstanceTest.cpp
+++ flang/unittests/Frontend/CompilerInstanceTest.cpp
@@ -9,14 +9,52 @@
 #include "flang/Frontend/CompilerInstance.h"
 #includ

[PATCH] D88297: [clangd] Trivial setter support when moving items to fields

2020-09-25 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 294357.
njames93 marked 2 inline comments as done.
njames93 added a comment.

Updated function doc
Fix potential assertion


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88297

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -698,6 +698,26 @@
  HI.Parameters->back().Name = "v";
  HI.AccessSpecifier = "public";
}},
+  {// Setter (move)
+   R"cpp(
+  namespace std { template T&& move(T&& t); }
+  struct X { int Y; void [[^setY]](float v) { Y = std::move(v); } };
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "setY";
+ HI.Kind = index::SymbolKind::InstanceMethod;
+ HI.NamespaceScope = "";
+ HI.Definition = "void setY(float v)";
+ HI.LocalScope = "X::";
+ HI.Documentation = "Trivial setter for `Y`.";
+ HI.Type = "void (float)";
+ HI.ReturnType = "void";
+ HI.Parameters.emplace();
+ HI.Parameters->emplace_back();
+ HI.Parameters->back().Type = "float";
+ HI.Parameters->back().Name = "v";
+ HI.AccessSpecifier = "public";
+   }},
   {// Field type initializer.
R"cpp(
   struct X { int x = 2; };
@@ -802,8 +822,8 @@
  HI.Type = "int";
  HI.AccessSpecifier = "public";
}},
-   {// No crash on InitListExpr.
-R"cpp(
+  {// No crash on InitListExpr.
+   R"cpp(
   struct Foo {
 int a[10];
   };
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -413,6 +413,8 @@
 // If CMD is one of the forms:
 //   void foo(T arg) { FieldName = arg; }
 //   R foo(T arg) { FieldName = arg; return *this; }
+//   void foo(T arg) { FieldName = std::move(arg); }
+//   R foo(T arg) { FieldName = std::move(arg); return *this; }
 // then returns "FieldName"
 llvm::Optional setterVariableName(const CXXMethodDecl *CMD) {
   assert(CMD->hasBody());
@@ -455,6 +457,18 @@
   } else {
 return llvm::None;
   }
+
+  // Detect the case when the item is moved into the field.
+  if (auto *CE = llvm::dyn_cast(RHS->IgnoreCasts())) {
+if (CE->getNumArgs() != 1)
+  return llvm::None;
+auto *ND = llvm::dyn_cast(CE->getCalleeDecl());
+if (!ND || !ND->getIdentifier() || ND->getName() != "move" ||
+!ND->isInStdNamespace())
+  return llvm::None;
+RHS = CE->getArg(0);
+  }
+
   auto *DRE = llvm::dyn_cast(RHS->IgnoreCasts());
   if (!DRE || DRE->getDecl() != Arg)
 return llvm::None;


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -698,6 +698,26 @@
  HI.Parameters->back().Name = "v";
  HI.AccessSpecifier = "public";
}},
+  {// Setter (move)
+   R"cpp(
+  namespace std { template T&& move(T&& t); }
+  struct X { int Y; void [[^setY]](float v) { Y = std::move(v); } };
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "setY";
+ HI.Kind = index::SymbolKind::InstanceMethod;
+ HI.NamespaceScope = "";
+ HI.Definition = "void setY(float v)";
+ HI.LocalScope = "X::";
+ HI.Documentation = "Trivial setter for `Y`.";
+ HI.Type = "void (float)";
+ HI.ReturnType = "void";
+ HI.Parameters.emplace();
+ HI.Parameters->emplace_back();
+ HI.Parameters->back().Type = "float";
+ HI.Parameters->back().Name = "v";
+ HI.AccessSpecifier = "public";
+   }},
   {// Field type initializer.
R"cpp(
   struct X { int x = 2; };
@@ -802,8 +822,8 @@
  HI.Type = "int";
  HI.AccessSpecifier = "public";
}},
-   {// No crash on InitListExpr.
-R"cpp(
+  {// No crash on InitListExpr.
+   R"cpp(
   struct Foo {
 int a[10];
   };
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -413,6 +413,8 @@
 // If CMD is one of the forms:
 //   void foo(T arg) { FieldName = arg; }
 //   R foo(T arg) { FieldName = arg; return *this; }
+//   void foo(T arg) { FieldName = std::move(arg); }
+//   R foo(T arg) { FieldName = std::move(arg); return *this; }
 // then returns "FieldName"
 llvm::Optional setterVariableName

[PATCH] D88297: [clangd] Trivial setter support when moving items to fields

2020-09-25 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clangd/Hover.cpp:461
+  if (auto *CE = llvm::dyn_cast(RHS->IgnoreCasts())) {
+// Make sure we get the version of move with 1 arg, the other is for moving
+// ranges.

sammccall wrote:
> nit: you could skip this check if you like, the other variant isn't going to 
> be on the RHS of an assignment :-)
You never know what crazy code people could concoct. It could be argued that 
this has a performance win by easily filtering out some bad candidates quickly 
and avoid needing to run the (slightly) more expensive checks on the name later 
down the line :-)



Comment at: clang-tools-extra/clangd/Hover.cpp:466
+auto *ND = llvm::dyn_cast(CE->getCalleeDecl());
+if (!ND)
+  return llvm::None;

kadircet wrote:
> nit: combine with the next condition, and perform the string comparison last, 
> i.e.:
> 
> `if(!ND || !ND->isInStd || ND->getName() != "move")`
Can you explain the reasoning for moving the comparison to the end?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88297

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


[clang] 76eb163 - Sema: remove unnecessary parameter for SwiftName handling (NFCI)

2020-09-25 Thread Saleem Abdulrasool via cfe-commits

Author: Saleem Abdulrasool
Date: 2020-09-25T17:01:06Z
New Revision: 76eb163259c46171559a49111a394a3e48d1e523

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

LOG: Sema: remove unnecessary parameter for SwiftName handling (NFCI)

This code never actually did anything in the implementation.

`mergeDeclAttribute` is declared as `static`, and referenced exactly
once in the file: from `Sema::mergeDeclAttributes`.

`Sema::mergeDeclAttributes` sets `LocalAMK` to `AMK_None`.  If the
attribute is `DeprecatedAttr`, `UnavailableAttr`, or `AvailabilityAttr`
then the `LocalAMK` is updated.  However, because we are dealing with a
`SwiftNameDeclAttr` here, `LocalAMK` remains `AMK_None`.  This is then
passed to the function which will as a result pass the value of
`AMK_None == AMK_Override` aka `false`.  Simply propagate the value
through and erase the dead codepath.

Thanks to Aaron Ballman for flagging the use of the availability merge
kind here leading to this simplification!

Differential Revision: https://reviews.llvm.org/D88263
Reviewed By: Aaron Ballman

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 10b8e7838e47..9559075935d8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3070,7 +3070,7 @@ class Sema final {
   mergeSpeculativeLoadHardeningAttr(Decl *D,
 const SpeculativeLoadHardeningAttr &AL);
   SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
-StringRef Name, bool Override);
+StringRef Name);
   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
   const AttributeCommonInfo &CI);
   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 434f13e38e3c..2599e3b46e4e 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2593,8 +2593,7 @@ static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
   } else if (const auto *MA = dyn_cast(Attr))
 NewAttr = S.mergeMinSizeAttr(D, *MA);
   else if (const auto *SNA = dyn_cast(Attr))
-NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName(),
-   AMK == Sema::AMK_Override);
+NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
   else if (const auto *OA = dyn_cast(Attr))
 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
   else if (const auto *InternalLinkageA = dyn_cast(Attr))

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 00cad5c11c32..d5f08faccc92 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -4282,13 +4282,8 @@ NoSpeculativeLoadHardeningAttr 
*Sema::mergeNoSpeculativeLoadHardeningAttr(
 }
 
 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
-StringRef Name, bool Override) {
+StringRef Name) {
   if (const auto *PrevSNA = D->getAttr()) {
-if (Override) {
-  // FIXME: warn about incompatible override
-  return nullptr;
-}
-
 if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
   Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
   << PrevSNA << &SNA;



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


[PATCH] D88263: Sema: remove unnecessary parameter for SwiftName handling (NFCI)

2020-09-25 Thread Saleem Abdulrasool via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG76eb163259c4: Sema: remove unnecessary parameter for 
SwiftName handling (NFCI) (authored by compnerd).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88263

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp


Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -4282,13 +4282,8 @@
 }
 
 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
-StringRef Name, bool Override) {
+StringRef Name) {
   if (const auto *PrevSNA = D->getAttr()) {
-if (Override) {
-  // FIXME: warn about incompatible override
-  return nullptr;
-}
-
 if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
   Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
   << PrevSNA << &SNA;
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -2593,8 +2593,7 @@
   } else if (const auto *MA = dyn_cast(Attr))
 NewAttr = S.mergeMinSizeAttr(D, *MA);
   else if (const auto *SNA = dyn_cast(Attr))
-NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName(),
-   AMK == Sema::AMK_Override);
+NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
   else if (const auto *OA = dyn_cast(Attr))
 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
   else if (const auto *InternalLinkageA = dyn_cast(Attr))
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -3070,7 +3070,7 @@
   mergeSpeculativeLoadHardeningAttr(Decl *D,
 const SpeculativeLoadHardeningAttr &AL);
   SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
-StringRef Name, bool Override);
+StringRef Name);
   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
   const AttributeCommonInfo &CI);
   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);


Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -4282,13 +4282,8 @@
 }
 
 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
-StringRef Name, bool Override) {
+StringRef Name) {
   if (const auto *PrevSNA = D->getAttr()) {
-if (Override) {
-  // FIXME: warn about incompatible override
-  return nullptr;
-}
-
 if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
   Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
   << PrevSNA << &SNA;
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -2593,8 +2593,7 @@
   } else if (const auto *MA = dyn_cast(Attr))
 NewAttr = S.mergeMinSizeAttr(D, *MA);
   else if (const auto *SNA = dyn_cast(Attr))
-NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName(),
-   AMK == Sema::AMK_Override);
+NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
   else if (const auto *OA = dyn_cast(Attr))
 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
   else if (const auto *InternalLinkageA = dyn_cast(Attr))
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -3070,7 +3070,7 @@
   mergeSpeculativeLoadHardeningAttr(Decl *D,
 const SpeculativeLoadHardeningAttr &AL);
   SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
-StringRef Name, bool Override);
+StringRef Name);
   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
   const AttributeCommonInfo &CI);
   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54222: [clang-tidy] Add a check to detect returning static locals in public headers

2020-09-25 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

In D54222#2294123 , 
@jranieri-grammatech wrote:

> In D54222#1290789 , @JonasToth wrote:
>
>> I agree with @Eugene.Zelenko that this check should rather live in 
>> `bugprone-` as the issue its diagnosing is not LLVM specific. It is ok to 
>> add an alias into the llvm module.
>
> Here are the warnings it issues with the patch's matcher:
>
>   clang/include/clang/StaticAnalyzer/Core/CheckerManager.h:625:43: warning: 
> address of static local variable 'tag' may not be identical across library 
> boundaries [llvm-problematic-statics]
>   
> clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h:219:1:
>  warning: address of static local variable 'Index' may not be identical 
> across library boundaries [llvm-problematic-statics]
>   
> clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h:25:1:
>  warning: address of static local variable 'Index' may not be identical 
> across library boundaries [llvm-problematic-statics]
>
> And here are the additional warnings it issues when relaxing the matcher (to 
> be `unless(isExpansionInMainFile())`):
>
>   clang/lib/StaticAnalyzer/Checkers/Iterator.h:130:47: warning: address of 
> static local variable 'Index' may not be identical across library boundaries 
> [llvm-problematic-statics]
>   clang/lib/StaticAnalyzer/Checkers/Iterator.h:136:47: warning: address of 
> static local variable 'Index' may not be identical across library boundaries 
> [llvm-problematic-statics]
>   clang/lib/StaticAnalyzer/Checkers/Iterator.h:142:47: warning: address of 
> static local variable 'Index' may not be identical across library boundaries 
> [llvm-problematic-statics]
>   clang/lib/StaticAnalyzer/Checkers/MPI-Checker/MPITypes.h:60:5: warning: 
> address of static local variable 'index' may not be identical across library 
> boundaries [llvm-problematic-statics]
>   llvm/utils/unittest/googletest/src/gtest.cc:3989:3: warning: address of 
> static local variable 'instance' may not be identical across library 
> boundaries [llvm-problematic-statics]
>
> And also this one, which was hidden by default but made running tidy noisier 
> by always saying there was a hidden warning:
>
>   /usr/bin/../include/c++/v1/functional:1960:9: warning: address of static 
> local variable '__policy_' may not be identical across library boundaries 
> [llvm-problematic-statics]
>
> All of the first set of warnings might be actual problems, but the second set 
> definitely aren't problems because they aren't going to be used across shared 
> library boundaries. By making this be a LLVM-specific check, we can avoid the 
> noise of these false positives. Also, I looked through the C++ Core 
> Guidelines for any rules that might address this but didn't see anything 
> relevant.
>
> Thoughts?

Do you have data for other projects? As this is not a very common thing and 
probably different for code-bases with plugins and so on, the "chattiness" of 
the check would be interesting to know.
If the check is usually quiet, then i would think its ok to have it as a 
general check together with proper documentation explaining why these statics 
can be a problem.

I would still like to have it in `bugprone-`, because this is a real problem 
that can arise and the check is more likely to be ignored if considered to be 
"just for llvm".
The decision for true vs false positive is not possible to decide within 
clang-tidy, is it? I think this should then be left to the developer (as it is 
probably not that much?).


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54222

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


[PATCH] D88275: [ASTMatchers] Add matcher `hasParentIgnoringImplicit`.

2020-09-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

This seems to be strongly related to the `TK_IgnoreUnlessSpelledInSource` 
traversal behavior; is there a reason you can't use that traversal mode with 
`hasParent()` (does it behave differently)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88275

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


[PATCH] D88275: [ASTMatchers] Add matcher `hasParentIgnoringImplicit`.

2020-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

In D88275#2295379 , @aaron.ballman 
wrote:

> This seems to be strongly related to the `TK_IgnoreUnlessSpelledInSource` 
> traversal behavior; is there a reason you can't use that traversal mode with 
> `hasParent()` (does it behave differently)?

Aaron, that's a good point.  I hadn't realized that the traversal mode 
supported parent traversal. That said, even with it available, I have strong 
reservations about modal matching, especially given that it had severe issues 
when `TK_IgnoreUnlessSpelledInSource` went live a few months ago as the default 
setting. I don't know what the resolution of those discussions were, but I 
thought we simply agreed to restore the default, and left fixing the underlying 
issues as future work.

But, even it if worked as desired, to achieve the same effect, you would have 
to restore the current mode as well once you're reached your desired 
destination. e.g. inspired by the tests, given some matcher `m`,

  integerLiteral(hasParentIgnoringImplicit(varDecl(m)))

becomes

  integerLiteral(traversal(TK_IgnoreUnlessSpelledInSource, 
hasParent(varDecl(traversal(TK_AsIs, m)

which seems a lot worse to me. We could however implement this new one in terms 
of `traverse`, but that would go back to the question of whether it is working 
correctly and also gets somewhat tricky (specifically, restoring the ambient 
traversal mode).  Do you know the current status?

thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88275

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


[PATCH] D88275: [ASTMatchers] Add matcher `hasParentIgnoringImplicit`.

2020-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 294363.
ymandel added a comment.

restored changes to unrelated parts of html docs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88275

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -3190,6 +3190,26 @@
compoundStmt(hasParent(recordDecl();
 }
 
+TEST(HasParentIgnoringImplicit, MatchesExplicitParents) {
+  std::string Input = R"cc(
+float f() {
+int x = 3;
+int y = 3.0;
+return y;
+}
+  )cc";
+  EXPECT_TRUE(
+  matches(Input, declRefExpr(hasParentIgnoringImplicit(returnStmt();
+  EXPECT_TRUE(
+  matches(Input, floatLiteral(hasParentIgnoringImplicit(varDecl();
+  EXPECT_TRUE(
+  matches(Input, integerLiteral(hasParentIgnoringImplicit(varDecl();
+
+  // Make sure it only ignores implicit ancestors.
+  EXPECT_TRUE(
+  notMatches(Input, integerLiteral(hasParentIgnoringImplicit(declStmt();
+}
+
 TEST(HasParent, NoDuplicateParents) {
   class HasDuplicateParents : public BoundNodesCallback {
   public:
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -311,6 +311,7 @@
   REGISTER_MATCHER(hasOverloadedOperatorName);
   REGISTER_MATCHER(hasParameter);
   REGISTER_MATCHER(hasParent);
+  REGISTER_MATCHER(hasParentIgnoringImplicit);
   REGISTER_MATCHER(hasQualifier);
   REGISTER_MATCHER(hasRHS);
   REGISTER_MATCHER(hasRangeInit);
Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -544,9 +544,14 @@
 // don't invalidate any iterators.
 if (ResultCache.size() > MaxMemoizationEntries)
   ResultCache.clear();
-if (MatchMode == AncestorMatchMode::AMM_ParentOnly)
+switch (MatchMode) {
+case AncestorMatchMode::AMM_ParentOnly:
   return matchesParentOf(Node, Matcher, Builder);
-return matchesAnyAncestorOf(Node, Ctx, Matcher, Builder);
+case AncestorMatchMode::AMM_FirstExplicitOnly:
+  return matchesFirstExplicitAncestorOf(Node, Matcher, Builder);
+case AncestorMatchMode::AMM_All:
+  return matchesAnyAncestorOf(Node, Ctx, Matcher, Builder);
+}
   }
 
   // Matches all registered matchers on the given node and calls the
@@ -714,6 +719,33 @@
 return false;
   }
 
+  // Returns whether the first explicit (`Expr`) ancestor of \p Node matches \p
+  // Matcher. That is, like matchesParentOf but skipping implicit parents.
+  // Unlike matchesAnyAncestorOf there's no memoization: it doesn't save much.
+  bool matchesFirstExplicitAncestorOf(const DynTypedNode &Node,
+  const DynTypedMatcher &Matcher,
+  BoundNodesTreeBuilder *Builder) {
+for (const auto &Parent : ActiveASTContext->getParents(Node)) {
+  if (const auto *E = Parent.get())
+// If the parent is an implicit node, match on *its* parents
+// instead. Use DFS, since we expect that expressions are relatively
+// shallow.
+if (clang::isa(E) || clang::isa(E) ||
+clang::isa(E) ||
+clang::isa(E)) {
+  if (matchesFirstExplicitAncestorOf(Parent, Matcher, Builder))
+return true;
+  continue;
+}
+  BoundNodesTreeBuilder BuilderCopy = *Builder;
+  if (Matcher.matches(Parent, this, &BuilderCopy)) {
+*Builder = std::move(BuilderCopy);
+return true;
+  }
+}
+return false;
+  }
+
   // Returns whether an ancestor of \p Node matches \p Matcher.
   //
   // The order of matching (which can lead to different nodes being bound in
Index: clang/include/clang/ASTMatchers/ASTMatchersInternal.h
===
--- clang/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ clang/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -985,7 +985,11 @@
 AMM_All,
 
 /// Direct parent only.
-AMM_ParentOnly
+AMM_ParentOnly,
+
+/// Considers the first non-implicit `Expr` ancestor. Intuitively, like
+/// `ignoringImplicit` for matching parents.
+AMM_FirstExplicitOnly
   };
 
   virtual ~ASTMatchFinder() = default;
@@ -1515,6 +1519,33 @@
   }
 };
 
+///

[PATCH] D78075: [Clang][OpenMP] Added support for nowait target in CodeGen

2020-09-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LGTM. Nice to get async through "regular" tasks :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78075

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


[PATCH] D87956: [WIP][IR] add fn attr for no_stack_protector; prevent inlining ssp into no-ssp

2020-09-25 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added inline comments.



Comment at: clang/test/CodeGen/stack-protector.c:39
 // SAFESTACK-NOSSP: attributes #[[A]] = {{.*}} safestack
-// SAFESTACK-NOSSP-NOT: ssp
+// SAFESTACK-NOSSP-NOT: attribute #[[A]] = {{.*}} ssp
 

should be `attributes` plural.



Comment at: llvm/include/llvm/Bitcode/LLVMBitCodes.h:610
+  // TODO: reorder
+  ATTR_KIND_NO_STACK_PROTECT = 70,
   ATTR_KIND_STACK_PROTECT = 26,

any comments from reviewers before I go and do a tedious reordering of these 
enum values?



Comment at: llvm/lib/IR/Attributes.cpp:1901-1902
+  // caller was explicitly annotated as nossp.
+  if (Caller.hasFnAttribute(Attribute::NoStackProtect))
+return;
   // If upgrading the SSP attribute, clear out the old SSP Attributes first.

This should be an anomalous situation due to the added verifier check. Should I 
make it an assert instead?



Comment at: llvm/lib/Transforms/Utils/InlineFunction.cpp:1687
+  return InlineResult::failure(
+  "non-stack-protected caller would inline stack-protected callee");
+

Is there a better way to emit an OptimizationRemark? Having this feedback in 
`-Rpass=inline` might be nice.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87956

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


[PATCH] D88329: [objc] Consolidate ObjC name mangle code to AST

2020-09-25 Thread Ellis Hoag via Phabricator via cfe-commits
ellis created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
ellis requested review of this revision.

This reduces code duplication between CGObjCMac.cpp and Mangle.cpp for 
generating the mangled name of an Objective-C method.

This has no intended functionality change.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88329

Files:
  clang/include/clang/AST/Mangle.h
  clang/lib/AST/Mangle.cpp
  clang/lib/CodeGen/CGObjCMac.cpp

Index: clang/lib/CodeGen/CGObjCMac.cpp
===
--- clang/lib/CodeGen/CGObjCMac.cpp
+++ clang/lib/CodeGen/CGObjCMac.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/Attr.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/AST/Mangle.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/StmtObjC.h"
 #include "clang/Basic/CodeGenOptions.h"
@@ -924,13 +925,6 @@
 
   llvm::StringMap NSConstantStringMap;
 
-  /// GetNameForMethod - Return a name for the given method.
-  /// \param[out] NameOut - The return value.
-  void GetNameForMethod(const ObjCMethodDecl *OMD,
-const ObjCContainerDecl *CD,
-SmallVectorImpl &NameOut,
-bool ignoreCategoryNamespace = false);
-
   /// GetMethodVarName - Return a unique constant for the given
   /// selector's name. The return value has type char *.
   llvm::Constant *GetMethodVarName(Selector Sel);
@@ -4008,7 +4002,10 @@
 Method = GenerateDirectMethod(OMD, CD);
   } else {
 SmallString<256> Name;
-GetNameForMethod(OMD, CD, Name);
+llvm::raw_svector_ostream OS(Name);
+const auto &MC = CGM.getContext().createMangleContext();
+MC->mangleObjCMethodNameWithoutSize(OMD, OS, /*includePrefixByte=*/true,
+/*includeCategoryNamespace=*/true);
 
 CodeGenTypes &Types = CGM.getTypes();
 llvm::FunctionType *MethodTy =
@@ -4061,7 +4058,10 @@
 I->second = Fn;
   } else {
 SmallString<256> Name;
-GetNameForMethod(OMD, CD, Name, /*ignoreCategoryNamespace*/ true);
+llvm::raw_svector_ostream OS(Name);
+const auto &MC = CGM.getContext().createMangleContext();
+MC->mangleObjCMethodNameWithoutSize(OMD, OS, /*includePrefixByte=*/true,
+/*includeCategoryNamespace=*/false);
 
 Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage,
 Name.str(), &CGM.getModule());
@@ -5715,21 +5715,6 @@
   return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
 }
 
-void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
-   const ObjCContainerDecl *CD,
-   SmallVectorImpl &Name,
-   bool ignoreCategoryNamespace) {
-  llvm::raw_svector_ostream OS(Name);
-  assert (CD && "Missing container decl in GetNameForMethod");
-  OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
- << '[' << CD->getName();
-  if (!ignoreCategoryNamespace)
-if (const ObjCCategoryImplDecl *CID =
-dyn_cast(D->getDeclContext()))
-  OS << '(' << *CID << ')';
-  OS << ' ' << D->getSelector().getAsString() << ']';
-}
-
 void CGObjCMac::FinishModule() {
   EmitModuleInfo();
 
Index: clang/lib/AST/Mangle.cpp
===
--- clang/lib/AST/Mangle.cpp
+++ clang/lib/AST/Mangle.cpp
@@ -304,17 +304,23 @@
   mangleFunctionBlock(*this, Buffer, BD, Out);
 }
 
-void MangleContext::mangleObjCMethodNameWithoutSize(const ObjCMethodDecl *MD,
-raw_ostream &OS) {
-  const ObjCContainerDecl *CD =
-  dyn_cast(MD->getDeclContext());
-  assert (CD && "Missing container decl in GetNameForMethod");
+void MangleContext::mangleObjCMethodNameWithoutSize(
+const ObjCMethodDecl *MD, raw_ostream &OS, bool includePrefixByte,
+bool includeCategoryNamespace) {
+  // \01+[ContainerName(CategoryName) SelectorName]
+  if (includePrefixByte) {
+OS << '\01';
+  }
   OS << (MD->isInstanceMethod() ? '-' : '+') << '[';
-  if (const ObjCCategoryImplDecl *CID = dyn_cast(CD)) {
+  if (auto *CID = dyn_cast(MD->getDeclContext())) {
 OS << CID->getClassInterface()->getName();
-OS << '(' << *CID << ')';
-  } else {
+if (includeCategoryNamespace) {
+  OS << '(' << *CID << ')';
+}
+  } else if (auto *CD = dyn_cast(MD->getDeclContext())) {
 OS << CD->getName();
+  } else {
+assert(false && "Unexpected ObjC method decl context");
   }
   OS << ' ';
   MD->getSelector().print(OS);
@@ -326,7 +332,8 @@
   SmallString<64> Name;
   llvm::raw_svector_ostream OS(Name);
 
-  mangleObjCMethodNameWithoutSize(MD, OS);
+  mangleObjCMethodNameWithoutSize(MD, OS, /*includePrefixByte=*/false,
+  /*includeCategoryNamespace=*/true);
   Out << OS.str().size() << OS.str();
 }
 
@@ -

[PATCH] D88329: [objc] Consolidate ObjC name mangle code to AST

2020-09-25 Thread Ellis Hoag via Phabricator via cfe-commits
ellis updated this revision to Diff 294395.
ellis added a comment.

Fix variable name


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88329

Files:
  clang/include/clang/AST/Mangle.h
  clang/lib/AST/Mangle.cpp
  clang/lib/CodeGen/CGObjCMac.cpp

Index: clang/lib/CodeGen/CGObjCMac.cpp
===
--- clang/lib/CodeGen/CGObjCMac.cpp
+++ clang/lib/CodeGen/CGObjCMac.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/Attr.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/AST/Mangle.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/StmtObjC.h"
 #include "clang/Basic/CodeGenOptions.h"
@@ -924,13 +925,6 @@
 
   llvm::StringMap NSConstantStringMap;
 
-  /// GetNameForMethod - Return a name for the given method.
-  /// \param[out] NameOut - The return value.
-  void GetNameForMethod(const ObjCMethodDecl *OMD,
-const ObjCContainerDecl *CD,
-SmallVectorImpl &NameOut,
-bool ignoreCategoryNamespace = false);
-
   /// GetMethodVarName - Return a unique constant for the given
   /// selector's name. The return value has type char *.
   llvm::Constant *GetMethodVarName(Selector Sel);
@@ -4008,7 +4002,10 @@
 Method = GenerateDirectMethod(OMD, CD);
   } else {
 SmallString<256> Name;
-GetNameForMethod(OMD, CD, Name);
+llvm::raw_svector_ostream OS(Name);
+const auto &MC = CGM.getContext().createMangleContext();
+MC->mangleObjCMethodNameWithoutSize(OMD, OS, /*includePrefixByte=*/true,
+/*includeCategoryNamespace=*/true);
 
 CodeGenTypes &Types = CGM.getTypes();
 llvm::FunctionType *MethodTy =
@@ -4061,7 +4058,10 @@
 I->second = Fn;
   } else {
 SmallString<256> Name;
-GetNameForMethod(OMD, CD, Name, /*ignoreCategoryNamespace*/ true);
+llvm::raw_svector_ostream OS(Name);
+const auto &MC = CGM.getContext().createMangleContext();
+MC->mangleObjCMethodNameWithoutSize(OMD, OS, /*includePrefixByte=*/true,
+/*includeCategoryNamespace=*/false);
 
 Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage,
 Name.str(), &CGM.getModule());
@@ -5715,21 +5715,6 @@
   return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
 }
 
-void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
-   const ObjCContainerDecl *CD,
-   SmallVectorImpl &Name,
-   bool ignoreCategoryNamespace) {
-  llvm::raw_svector_ostream OS(Name);
-  assert (CD && "Missing container decl in GetNameForMethod");
-  OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
- << '[' << CD->getName();
-  if (!ignoreCategoryNamespace)
-if (const ObjCCategoryImplDecl *CID =
-dyn_cast(D->getDeclContext()))
-  OS << '(' << *CID << ')';
-  OS << ' ' << D->getSelector().getAsString() << ']';
-}
-
 void CGObjCMac::FinishModule() {
   EmitModuleInfo();
 
Index: clang/lib/AST/Mangle.cpp
===
--- clang/lib/AST/Mangle.cpp
+++ clang/lib/AST/Mangle.cpp
@@ -304,17 +304,23 @@
   mangleFunctionBlock(*this, Buffer, BD, Out);
 }
 
-void MangleContext::mangleObjCMethodNameWithoutSize(const ObjCMethodDecl *MD,
-raw_ostream &OS) {
-  const ObjCContainerDecl *CD =
-  dyn_cast(MD->getDeclContext());
-  assert (CD && "Missing container decl in GetNameForMethod");
+void MangleContext::mangleObjCMethodNameWithoutSize(
+const ObjCMethodDecl *MD, raw_ostream &OS, bool includePrefixByte,
+bool includeCategoryNamespace) {
+  // \01+[ContainerName(CategoryName) SelectorName]
+  if (includePrefixByte) {
+OS << '\01';
+  }
   OS << (MD->isInstanceMethod() ? '-' : '+') << '[';
-  if (const ObjCCategoryImplDecl *CID = dyn_cast(CD)) {
+  if (auto *CID = dyn_cast(MD->getDeclContext())) {
 OS << CID->getClassInterface()->getName();
-OS << '(' << *CID << ')';
-  } else {
+if (includeCategoryNamespace) {
+  OS << '(' << *CID << ')';
+}
+  } else if (auto *CD = dyn_cast(MD->getDeclContext())) {
 OS << CD->getName();
+  } else {
+assert(false && "Unexpected ObjC method decl context");
   }
   OS << ' ';
   MD->getSelector().print(OS);
@@ -326,7 +332,8 @@
   SmallString<64> Name;
   llvm::raw_svector_ostream OS(Name);
 
-  mangleObjCMethodNameWithoutSize(MD, OS);
+  mangleObjCMethodNameWithoutSize(MD, OS, /*includePrefixByte=*/false,
+  /*includeCategoryNamespace=*/true);
   Out << OS.str().size() << OS.str();
 }
 
@@ -352,7 +359,8 @@
   if (writeFuncOrVarName(VD, FrontendBufOS))
 return true;
 } else if (auto *MD = dyn_cast(D)) {
-  MC->mangleObjCMethodNam

[PATCH] D88333: Correctly parse attributes on the declaration of an anonymous bit-field

2020-09-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: hubert.reinterpretcast, rsmith.
aaron.ballman requested review of this revision.

The C++ grammar allows you to specify an attribute list on an anonymous 
bit-field, but we were not properly parsing that case. This would lead to a 
rejects-valid diagnostic with code like:

  struct A {
int x, [[]] : 0;
  };

This patch addresses it by optionally parsing an attribute specifier in the 
case the identifier is elided.


https://reviews.llvm.org/D88333

Files:
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/test/CXX/class/class.bit/p1.cpp


Index: clang/test/CXX/class/class.bit/p1.cpp
===
--- /dev/null
+++ clang/test/CXX/class/class.bit/p1.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+// expected-no-diagnostics
+
+constexpr int foo() { return 1; }
+
+struct A {
+  int a [[]] : 1;
+  int x, [[]] : 0;
+  int [[]] : 0;
+  int b [[]] : 1 = 1;
+  int c [[]] : 1 {1};
+  int d : foo() = foo();
+};
+
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -2308,11 +2308,13 @@
   //   declarator pure-specifier[opt]
   //   declarator requires-clause
   //   declarator brace-or-equal-initializer[opt]
-  //   identifier[opt] ':' constant-expression
-  if (Tok.isNot(tok::colon))
+  //   identifier[opt] attribute-specifier-seq[opt] ':' constant-expression
+  if (Tok.isNot(tok::colon) && !isCXX11AttributeSpecifier())
 ParseDeclarator(DeclaratorInfo);
-  else
+  else {
 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
+MaybeParseCXX11Attributes(DeclaratorInfo);
+  }
 
   if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
 assert(DeclaratorInfo.isPastIdentifier() &&


Index: clang/test/CXX/class/class.bit/p1.cpp
===
--- /dev/null
+++ clang/test/CXX/class/class.bit/p1.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+// expected-no-diagnostics
+
+constexpr int foo() { return 1; }
+
+struct A {
+  int a [[]] : 1;
+  int x, [[]] : 0;
+  int [[]] : 0;
+  int b [[]] : 1 = 1;
+  int c [[]] : 1 {1};
+  int d : foo() = foo();
+};
+
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -2308,11 +2308,13 @@
   //   declarator pure-specifier[opt]
   //   declarator requires-clause
   //   declarator brace-or-equal-initializer[opt]
-  //   identifier[opt] ':' constant-expression
-  if (Tok.isNot(tok::colon))
+  //   identifier[opt] attribute-specifier-seq[opt] ':' constant-expression
+  if (Tok.isNot(tok::colon) && !isCXX11AttributeSpecifier())
 ParseDeclarator(DeclaratorInfo);
-  else
+  else {
 DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
+MaybeParseCXX11Attributes(DeclaratorInfo);
+  }
 
   if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
 assert(DeclaratorInfo.isPastIdentifier() &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >