[PATCH] D87095: [Triple][MachO] Define "arm64e", an AArch64 subarch for Pointer Auth.

2020-09-04 Thread James Henderson via Phabricator via cfe-commits
jhenderson added inline comments.



Comment at: llvm/lib/Object/MachOObjectFile.cpp:2745
 ArrayRef MachOObjectFile::getValidArchs() {
-  static const std::array validArchs = {{
+  static const std::array validArchs = {{
   "i386",   "x86_64", "x86_64h",  "armv4t",  "arm","armv5e",

Nit: it's probably worth fixing these two Linter issues, since this function is 
small anyway.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87095

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


Re: [PATCH] D86874: [analyzer] Fix ArrayBoundCheckerV2 false positive regarding size_t indexer

2020-09-04 Thread Gábor Márton via cfe-commits
Hi Balázs,

Since reviews.llvm.org is offline, I am sending my comments below, inline.
Thanks for your huge effort in explaining all this!

Overall, I have a feeling that this approach targets only one specific
case, which is fine. But I believe we should think about all the other
possible cases, so we could get rid of other false positives too:
1) In case of multidimensional arrays, there may be a symbolic value in any
dimension.
2) What if  there are more symbolic values in the dimensions.

Cheers,
Gábor

On Thu, Sep 3, 2020 at 4:52 PM Balázs Benics via Phabricator <
revi...@reviews.llvm.org> wrote:

> steakhal added a comment.
>
> In D86874#inline-803844 ,
> @martong wrote:
>
> > I really feel that this check would have a better place in the
> implementation of `eval`. This seems really counter-intuitive to do this
> stuff at the Checker's level. Is there any reason why we can't do this in
> `eval`?
> > `evalBinOpNN` could return with Unknown, and the state should remain
> unchanged. Am I missing something?
>
> Ah, sort of.
> To make everything clear, I have to provide examples, building-blocks,
> reasoning and stuff, so please don't be mad if it's too long.
> **I hope you have a warm cup of tee to read through this - seriously - you
> will need that!**
>
Man, this requires a warm lunch and then hot cups(!) of coffee. :D


>
> Diving in
> -
>
> It is really important to make a clear distinction between evaluating an
> expression according to the semantics of the //meta-language// or of the
> //object-language//, because we might get different answers for the same
> expression.
>
> In fact, `evalBinOpNN` evaluates expressions according to the semantics of
> the //object-language//.
>
> In our context, meta-language is //mathematics//, and the
> //object-language// is the semantics of the abstract machine of the c/c++
> language.
> In mathematics, there is no such thing as overflow or value ranges, unlike
> in C++.
>
> Let's see an example:
> Assuming that `x` is in range `[1,UINT_MAX]`.
> `x + 1` will be in range `[2,ULL_MAX+1]` in the //meta-language//.
> `x + 1` will be in range `[0,0]u[2,UINT_MAX]` or in `[2,UINT_MAX+1]`
> weather the type of `x` is capable representing the (+1) value and the
> overflow is well-defined or not.
>
> Another valuable comment is that non-contiguous ranges (range sets) are
> not really useful.
> Knowing that `x` is in range `[0,0]u[2,UINT_MAX]` doesn't help much if you
> want to prove that:
> `x < 5` holds for all possible interpretations of `x`.
> We can not disproof that either.
>
> So, overflow/underflow can really screw the value ranges, preventing us
> from evaluating expressions over relational operators.
> Which is technically accurate, but not satisfiable in all cases - like in
> the checker `ArrayBoundCheckerV2`.
>
> ---
>
> Before describing why is it so problematic in this checker, I should give
> an overview, how this checker works.
>
> Overview of the logic of the ArrayBoundCheckerV2
> 
>
> The checker checks `Location` accesses (aka. pointer dereferences).
> We construct the `RegionRawOffsetV2` object of the access (Which consists
> of the //base region//, and the symbolic //byte offset// expression of the
> access).
>
> Then we check, whether we access an element //preceding// the **first
> valid index** of the //base// memory region.
> In other words, we check if the //byte offset// symbolic expression is
> **less then** 0:
>
> - If YES:   Report that we access an out-of-bounds element.
> - If NO:Infer the range constraints on the symbol and add the
> constraint to make this array access valid.
> - If MAYBE: Infer and constrain, just as you would do in the previous case.
>
> Then we check, whether we access an element //exceeding// the **last valid
> index** of the memory region.
> In other words, we check if the //byte offset// symbolic expression is
> greater then or equal to the //extent// of the region:
>
> - If YES:   Report the bug...
> - If NO:Infer & constrain...
> - If MAYBE: Infer & constrain...
>
> However, in the checker, we don't check `byte offset < 0` directly.
> We //simplify// the left part of the `byte offset < 0` inequality by
> substracting/dividing both sides with the constant `C`, if the `byte
> offset` is a `SymintExpr` of `SymExpr OP C` over the plus or multiplication
> operator (OP).
> We do this //simplification// recursively.
> In the end, we will have a //symbolic root// (call it `RootSym`)
> expression and a `C'` constant over the right-hand side of the original
> relational operator.
> So, after the //simplification// process we get the `RootSym < C'`
> inequality, which we check.
>
Just for the record, this is in `getSimplifiedOffsets`.


>
> This //simplification// is the //infer// operation in the pseudo-code.
> And the //constrain// step is where we assume that the negation of
> `RootSym < C'` holds.
>

> **SPOILER

[PATCH] D81083: [Clang] Allow "vector_size" applied to Booleans

2020-09-04 Thread Simon Moll via Phabricator via cfe-commits
simoll updated this revision to Diff 289893.
simoll added a comment.

Rebased


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81083

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/TargetInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Basic/Targets/Hexagon.h
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/AST/ast-print-vector-size-bool.c
  clang/test/CodeGen/debug-info-vector-bool-hvx64.c
  clang/test/CodeGen/debug-info-vector-bool.c
  clang/test/CodeGen/vector-alignment.c
  clang/test/SemaCXX/constexpr-vectors.cpp
  clang/test/SemaCXX/vector-bool.cpp
  clang/test/SemaCXX/vector-conditional.cpp
  clang/test/SemaCXX/vector.cpp

Index: clang/test/SemaCXX/vector.cpp
===
--- clang/test/SemaCXX/vector.cpp
+++ clang/test/SemaCXX/vector.cpp
@@ -331,8 +331,7 @@
 typedef __attribute__((ext_vector_type(4))) int vi4;
 const int &reference_to_vec_element = vi4(1).x;
 
-// PR12649
-typedef bool bad __attribute__((__vector_size__(16)));  // expected-error {{invalid vector element type 'bool'}}
+typedef bool good __attribute__((__vector_size__(16)));
 
 namespace Templates {
 template 
@@ -350,9 +349,7 @@
 void Init() {
   const TemplateVectorType::type Works = {};
   const TemplateVectorType::type Works2 = {};
-  // expected-error@#1 {{invalid vector element type 'bool'}}
-  // expected-note@+1 {{in instantiation of template class 'Templates::TemplateVectorType' requested here}}
-  const TemplateVectorType::type NoBool = {};
+  const TemplateVectorType::type BoolWorks = {};
   // expected-error@#1 {{invalid vector element type 'int __attribute__((ext_vector_type(4)))' (vector of 4 'int' values)}}
   // expected-note@+1 {{in instantiation of template class 'Templates::TemplateVectorType' requested here}}
   const TemplateVectorType::type NoComplex = {};
Index: clang/test/SemaCXX/vector-conditional.cpp
===
--- clang/test/SemaCXX/vector-conditional.cpp
+++ clang/test/SemaCXX/vector-conditional.cpp
@@ -13,6 +13,7 @@
 using FourFloats = float __attribute__((__vector_size__(16)));
 using TwoDoubles = double __attribute__((__vector_size__(16)));
 using FourDoubles = double __attribute__((__vector_size__(32)));
+using EightBools = bool __attribute__((__vector_size__(2)));
 
 FourShorts four_shorts;
 TwoInts two_ints;
@@ -25,6 +26,8 @@
 FourFloats four_floats;
 TwoDoubles two_doubles;
 FourDoubles four_doubles;
+EightBools eight_bools;
+EightBools other_eight_bools;
 
 enum E {};
 enum class SE {};
@@ -95,6 +98,9 @@
   (void)(four_ints ? four_uints : 3.0f);
   (void)(four_ints ? four_ints : 3.0f);
 
+  // Allow conditional select on bool vectors.
+  (void)(eight_bools ? eight_bools : other_eight_bools);
+
   // When there is a vector and a scalar, conversions must be legal.
   (void)(four_ints ? four_floats : 3); // should work, ints can convert to floats.
   (void)(four_ints ? four_uints : e);  // expected-error {{cannot convert between scalar type 'E' and vector type 'FourUInts'}}
@@ -163,10 +169,10 @@
 void Templates() {
   dependent_cond(two_ints);
   dependent_operand(two_floats);
-  // expected-error@159 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(4 * sizeof(double double' (vector of 4 'double' values))}}}
+  // expected-error@165 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(4 * sizeof(double double' (vector of 4 'double' values))}}}
   all_dependent(four_ints, four_uints, four_doubles); // expected-note {{in instantiation of}}
 
-  // expected-error@159 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(2 * sizeof(unsigned int unsigned int' (vector of 2 'unsigned int' values))}}}
+  // expected-error@165 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(2 * sizeof(unsigned int unsigned int' (vector of 2 'unsigned int' valu

[PATCH] D87097: [analyzer][StdLibraryFunctionsChecker] Do not match based on the restrict qualifier in C++

2020-09-04 Thread Balázs Kéri via Phabricator via cfe-commits
balazske accepted this revision.
balazske 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/D87097/new/

https://reviews.llvm.org/D87097

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


[PATCH] D86621: [clang][Sparc] Default to -mcpu=v9 for SparcV8 on Solaris

2020-09-04 Thread Rainer Orth via Phabricator via cfe-commits
ro added a comment.

Is there anything left to do to get approval?  Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86621

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


[clang] a633da5 - [FPEnv] Partially implement #pragma STDC FENV_ROUND

2020-09-04 Thread Serge Pavlov via cfe-commits

Author: Serge Pavlov
Date: 2020-09-04T16:47:10+07:00
New Revision: a633da5391b0e42c0185132e8b532ae9bc34489f

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

LOG: [FPEnv] Partially implement #pragma STDC FENV_ROUND

This change implements pragma STDC FENV_ROUND, which is introduced by
the extension to standard (TS 18661-1). The pragma is implemented only
in frontend, it sets apprpriate state of FPOptions stored in Sema. Use
of these bits in constant evaluation adn/or code generator is not in the
scope of this change.

Parser issues warning on unsuppored pragma when it encounteres pragma
STDC FENV_ROUND, however it makes syntax checks and updates Sema state
as if the pragma were supported.

Primary purpose of the partial implementation is to facilitate
development of non-default floating poin environment. Previously a
developer cannot set non-default rounding mode in sources, this mades
preparing tests for say constant evaluation  substantially complicated.

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

Added: 
clang/test/Parser/pragma-fenv_round.c

Modified: 
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/include/clang/Basic/TokenKinds.def
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParsePragma.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Parse/Parser.cpp
clang/lib/Sema/SemaAttr.cpp
clang/test/AST/ast-dump-fpfeatures.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 0e51fef8659e..1c8d741ab54f 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1136,6 +1136,12 @@ def ext_stdc_pragma_ignored : ExtWarn<"unknown pragma in 
STDC namespace">,
 def warn_stdc_fenv_access_not_supported :
Warning<"pragma STDC FENV_ACCESS ON is not supported, ignoring pragma">,
InGroup;
+def warn_stdc_fenv_round_not_supported :
+   Warning<"pragma STDC FENV_ROUND is not supported">,
+   InGroup;
+def warn_stdc_unknown_rounding_mode : Warning<
+  "invalid or unsupported rounding mode in '#pragma STDC FENV_ROUND' - 
ignored">,
+  InGroup;
 // - #pragma comment
 def err_pragma_comment_malformed : Error<
   "pragma comment requires parenthesized identifier and optional string">;

diff  --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index daaa54c3db7c..63f1cf9896db 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -829,6 +829,11 @@ PRAGMA_ANNOTATION(pragma_fp_contract)
 // handles them.
 PRAGMA_ANNOTATION(pragma_fenv_access)
 
+// Annotation for #pragma STDC FENV_ROUND
+// The lexer produces these so that they only take effect when the parser
+// handles them.
+PRAGMA_ANNOTATION(pragma_fenv_round)
+
 // Annotation for #pragma float_control
 // The lexer produces these so that they only take effect when the parser
 // handles them.

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 37ca9e893329..af8cf47e5667 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -202,7 +202,8 @@ class Parser : public CodeCompletionHandler {
   std::unique_ptr UnrollAndJamHintHandler;
   std::unique_ptr NoUnrollAndJamHintHandler;
   std::unique_ptr FPHandler;
-  std::unique_ptr STDCFENVHandler;
+  std::unique_ptr STDCFenvAccessHandler;
+  std::unique_ptr STDCFenvRoundHandler;
   std::unique_ptr STDCCXLIMITHandler;
   std::unique_ptr STDCUnknownHandler;
   std::unique_ptr AttributePragmaHandler;
@@ -745,6 +746,10 @@ class Parser : public CodeCompletionHandler {
   /// #pragma STDC FENV_ACCESS...
   void HandlePragmaFEnvAccess();
 
+  /// Handle the annotation token produced for
+  /// #pragma STDC FENV_ROUND...
+  void HandlePragmaFEnvRound();
+
   /// Handle the annotation token produced for
   /// #pragma float_control
   void HandlePragmaFloatControl();

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index ec449d6dd6be..53d0285d3702 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -9749,7 +9749,7 @@ class Sema final {
   /// \#pragma STDC FENV_ACCESS
   void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
 
-  /// Called to set rounding mode for floating point operations.
+  /// Called to set constant rounding mode for floating point operations.
   void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
 
   /// Called to set exception behavior for floating point operations.

diff  --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp
index 6402b31d00b2..572fc7115b87 100644
--- a/clang/lib/

[PATCH] D87097: [analyzer][StdLibraryFunctionsChecker] Do not match based on the restrict qualifier in C++

2020-09-04 Thread Gabor Marton 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 rGfe0972d3e4a6: [analyzer][StdLibraryFunctionsChecker] Do not 
match based on the restrict… (authored by martong).

Changed prior to commit:
  https://reviews.llvm.org/D87097?vs=289752&id=289902#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87097

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-restrict.c
  clang/test/Analysis/std-c-library-functions-restrict.cpp

Index: clang/test/Analysis/std-c-library-functions-restrict.cpp
===
--- /dev/null
+++ clang/test/Analysis/std-c-library-functions-restrict.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-checker=debug.StdCLibraryFunctionsTester \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:DisplayLoadedSummaries=true \
+// RUN:   -triple i686-unknown-linux 2>&1 | FileCheck %s
+
+// The signatures for these functions are the same and they specify their
+// parameter with the restrict qualifier. In C++, however, we are more
+// indulgent and we do not match based on this qualifier. Thus, the given
+// signature should match for both of the declarations below, i.e the summary
+// should be loaded for both of them.
+void __test_restrict_param_0(void *p);
+void __test_restrict_param_1(void *__restrict p);
+// The below declaration is illegal, "restrict" is not a keyword in C++.
+// void __test_restrict_param_2(void *restrict p);
+
+// CHECK: Loaded summary for: void __test_restrict_param_0(void *p)
+// CHECK: Loaded summary for: void __test_restrict_param_1(void *__restrict p)
+
+// Must have at least one call expression to initialize the summary map.
+int bar(void);
+void foo() {
+  bar();
+}
Index: clang/test/Analysis/std-c-library-functions-restrict.c
===
--- /dev/null
+++ clang/test/Analysis/std-c-library-functions-restrict.c
@@ -0,0 +1,24 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-checker=debug.StdCLibraryFunctionsTester \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:DisplayLoadedSummaries=true \
+// RUN:   -triple i686-unknown-linux 2>&1 | FileCheck %s
+
+// The signatures for these functions are the same and they specify their
+// parameter with the restrict qualifier. In C, the signature should match only
+// if the restrict qualifier is there on the parameter. Thus, the summary
+// should be loaded for the last two declarations only.
+void __test_restrict_param_0(void *p);
+void __test_restrict_param_1(void *__restrict p);
+void __test_restrict_param_2(void *restrict p);
+
+// CHECK-NOT: Loaded summary for: void __test_restrict_param_0
+// CHECK: Loaded summary for: void __test_restrict_param_1(void *restrict p)
+// CHECK: Loaded summary for: void __test_restrict_param_2(void *restrict p)
+
+// Must have at least one call expression to initialize the summary map.
+int bar(void);
+void foo() {
+  bar();
+}
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -744,21 +744,38 @@
 bool StdLibraryFunctionsChecker::Signature::matches(
 const FunctionDecl *FD) const {
   assert(!isInvalid());
-  // Check number of arguments:
+  // Check the number of arguments.
   if (FD->param_size() != ArgTys.size())
 return false;
 
-  // Check return type.
-  if (!isIrrelevant(RetTy))
-if (RetTy != FD->getReturnType().getCanonicalType())
+  // The "restrict" keyword is illegal in C++, however, many libc
+  // implementations use the "__restrict" compiler intrinsic in functions
+  // prototypes. The "__restrict" keyword qualifies a type as a restricted type
+  // even in C++.
+  // In case of any non-C99 languages, we don't want to match based on the
+  // restrict qualifier because we cannot know if the given libc implementation
+  // qualifies the paramter type or not.
+  auto RemoveRestrict = [&FD](QualType T) {
+if (!FD->getASTContext().getLangOpts().C99)
+  T.removeLocalRestrict();
+return T;
+  };
+
+  // Check the return type.
+  if (!isIrrelevant(RetTy)) {
+QualType FDRetTy = RemoveRestrict(FD->getReturnType().getCanonicalType());
+if (RetTy != FDRetTy)
   return false;
+  }
 
-  // Check argument types.
+  // Check the argument types.
   for (size_t I = 0, E = ArgTys.size(); I != E; ++I) {
 QualType Arg

[PATCH] D86921: [FPEnv] Partially implement #pragma STDC FENV_ROUND

2020-09-04 Thread Serge Pavlov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa633da5391b0: [FPEnv] Partially implement #pragma STDC 
FENV_ROUND (authored by sepavloff).

Changed prior to commit:
  https://reviews.llvm.org/D86921?vs=289110&id=289901#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86921

Files:
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/test/AST/ast-dump-fpfeatures.cpp
  clang/test/Parser/pragma-fenv_round.c

Index: clang/test/Parser/pragma-fenv_round.c
===
--- /dev/null
+++ clang/test/Parser/pragma-fenv_round.c
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -fsyntax-only -Wignored-pragmas -verify %s
+
+#pragma STDC FENV_ROUND ON   // expected-warning {{invalid or unsupported rounding mode}}
+
+float func_01(int x, float y) {
+  if (x)
+return y + 2;
+  #pragma STDC FENV_ROUND FE_DOWNWARD // expected-error{{'#pragma STDC FENV_ROUND' can only appear at file scope or at the start of a compound statement}}
+  // expected-warning@-1{{pragma STDC FENV_ROUND is not supported}}
+  return x + y;
+}
Index: clang/test/AST/ast-dump-fpfeatures.cpp
===
--- clang/test/AST/ast-dump-fpfeatures.cpp
+++ clang/test/AST/ast-dump-fpfeatures.cpp
@@ -34,4 +34,69 @@
 // CHECK-NEXT:   ParmVarDecl {{.*}} x 'float'
 // CHECK-NEXT: CompoundStmt
 // CHECK-NEXT:   ReturnStmt
-// CHECK-NEXT: CallExpr {{.*}} FPContractMode=0
\ No newline at end of file
+// CHECK-NEXT: CallExpr {{.*}} FPContractMode=0
+
+
+
+
+#pragma STDC FENV_ROUND FE_DOWNWARD
+
+float func_10(float x, float y) {
+  return x + y;
+}
+
+// CHECK-LABEL: FunctionDecl {{.*}} func_10 'float (float, float)'
+// CHECK: BinaryOperator {{.*}} 'float' '+' RoundingMode=3
+
+float func_11(float x, float y) {
+  if (x < 0) {
+#pragma STDC FENV_ROUND FE_UPWARD
+return x + y;
+  }
+  return x - y;
+}
+
+// CHECK-LABEL: FunctionDecl {{.*}} func_11 'float (float, float)'
+// CHECK: BinaryOperator {{.*}} 'float' '+' RoundingMode=2
+// CHECK: BinaryOperator {{.*}} 'float' '-' RoundingMode=3
+
+
+#pragma STDC FENV_ROUND FE_DYNAMIC
+
+float func_12(float x, float y) {
+  return x + y;
+}
+
+// CHECK-LABEL: FunctionDecl {{.*}} func_12 'float (float, float)'
+// CHECK: BinaryOperator {{.*}} 'float' '+' RoundingMode=1
+
+#pragma STDC FENV_ROUND FE_TONEAREST
+
+float func_13(float x, float y) {
+  return x + y;
+}
+
+// CHECK-LABEL: FunctionDecl {{.*}} func_13 'float (float, float)'
+// CHECK: BinaryOperator {{.*}} 'float' '+' RoundingMode=1
+
+
+template 
+T func_14(T x, T y) {
+#pragma STDC FENV_ROUND FE_TOWARDZERO
+  return x + y;
+}
+
+float func_15(float x, float y) {
+#pragma STDC FPENV_ROUND FE_DOWNWARD
+  return func_14(x, y);
+}
+
+// CHECK-LABEL: FunctionTemplateDecl {{.*}} func_14
+// CHECK: FunctionDecl {{.*}} func_14 'T (T, T)'
+// CHECK:   CompoundStmt
+// CHECK-NEXT:ReturnStmt
+// CHECK-NEXT:  BinaryOperator {{.*}} '+' RoundingMode=0
+// CHECK: FunctionDecl {{.*}} func_14 'float (float, float)'
+// CHECK:   CompoundStmt
+// CHECK-NEXT:ReturnStmt
+// CHECK-NEXT:  BinaryOperator {{.*}} 'float' '+' RoundingMode=0
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -979,6 +979,11 @@
 }
 
 void Sema::setRoundingMode(SourceLocation Loc, llvm::RoundingMode FPR) {
+  // C2x: 7.6.2p3  If the FE_DYNAMIC mode is specified and FENV_ACCESS is "off",
+  // the translator may assume that the default rounding mode is in effect.
+  if (FPR == llvm::RoundingMode::Dynamic && !CurFPFeatures.getAllowFEnvAccess())
+FPR = llvm::RoundingMode::NearestTiesToEven;
+
   FPOptionsOverride NewFPFeatures = CurFPFeatureOverrides();
   NewFPFeatures.setRoundingModeOverride(FPR);
   FpPragmaStack.Act(Loc, PSK_Set, StringRef(), NewFPFeatures);
Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -783,6 +783,9 @@
   case tok::annot_pragma_fenv_access:
 HandlePragmaFEnvAccess();
 return nullptr;
+  case tok::annot_pragma_fenv_round:
+HandlePragmaFEnvRound();
+return nullptr;
   case tok::annot_pragma_float_control:
 HandlePragmaFloatControl();
 return nullptr;
Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clan

[clang] fe0972d - [analyzer][StdLibraryFunctionsChecker] Do not match based on the restrict qualifier in C++

2020-09-04 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-09-04T11:48:38+02:00
New Revision: fe0972d3e4a65b4c5f5fa602b17ad30e463050b3

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

LOG: [analyzer][StdLibraryFunctionsChecker] Do not match based on the restrict 
qualifier in C++

The "restrict" keyword is illegal in C++, however, many libc
implementations use the "__restrict" compiler intrinsic in functions
prototypes. The "__restrict" keyword qualifies a type as a restricted type
even in C++.
In case of any non-C99 languages, we don't want to match based on the
restrict qualifier because we cannot know if the given libc implementation
qualifies the paramter type or not.

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

Added: 
clang/test/Analysis/std-c-library-functions-restrict.c
clang/test/Analysis/std-c-library-functions-restrict.cpp

Modified: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index c65d58e49d78..2c20422a9cc4 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -744,21 +744,38 @@ bool StdLibraryFunctionsChecker::evalCall(const CallEvent 
&Call,
 bool StdLibraryFunctionsChecker::Signature::matches(
 const FunctionDecl *FD) const {
   assert(!isInvalid());
-  // Check number of arguments:
+  // Check the number of arguments.
   if (FD->param_size() != ArgTys.size())
 return false;
 
-  // Check return type.
-  if (!isIrrelevant(RetTy))
-if (RetTy != FD->getReturnType().getCanonicalType())
+  // The "restrict" keyword is illegal in C++, however, many libc
+  // implementations use the "__restrict" compiler intrinsic in functions
+  // prototypes. The "__restrict" keyword qualifies a type as a restricted type
+  // even in C++.
+  // In case of any non-C99 languages, we don't want to match based on the
+  // restrict qualifier because we cannot know if the given libc implementation
+  // qualifies the paramter type or not.
+  auto RemoveRestrict = [&FD](QualType T) {
+if (!FD->getASTContext().getLangOpts().C99)
+  T.removeLocalRestrict();
+return T;
+  };
+
+  // Check the return type.
+  if (!isIrrelevant(RetTy)) {
+QualType FDRetTy = RemoveRestrict(FD->getReturnType().getCanonicalType());
+if (RetTy != FDRetTy)
   return false;
+  }
 
-  // Check argument types.
+  // Check the argument types.
   for (size_t I = 0, E = ArgTys.size(); I != E; ++I) {
 QualType ArgTy = ArgTys[I];
 if (isIrrelevant(ArgTy))
   continue;
-if (ArgTy != FD->getParamDecl(I)->getType().getCanonicalType())
+QualType FDArgTy =
+RemoveRestrict(FD->getParamDecl(I)->getType().getCanonicalType());
+if (ArgTy != FDArgTy)
   return false;
   }
 
@@ -989,6 +1006,12 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   for (const Summary &S : Summaries)
 operator()(Name, S);
 }
+// Add the same summary for 
diff erent names with the Signature explicitly
+// given.
+void operator()(std::vector Names, Signature Sign, Summary Sum) 
{
+  for (StringRef Name : Names)
+operator()(Name, Sign, Sum);
+}
   } addToFunctionSummaryMap(ACtx, FunctionSummaryMap, DisplayLoadedSummaries);
 
   // Below are helpers functions to create the summaries.
@@ -2048,6 +2071,11 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 EvalCallAsPure)
 .ArgConstraint(BufferSize(/*Buffer=*/ArgNo(0), 
/*BufSize=*/ArgNo(1),
   /*BufSizeMultiplier=*/ArgNo(2;
+addToFunctionSummaryMap(
+{"__test_restrict_param_0", "__test_restrict_param_1",
+ "__test_restrict_param_2"},
+Signature(ArgTypes{VoidPtrRestrictTy}, RetType{VoidTy}),
+Summary(EvalCallAsPure));
   }
 }
 

diff  --git a/clang/test/Analysis/std-c-library-functions-restrict.c 
b/clang/test/Analysis/std-c-library-functions-restrict.c
new file mode 100644
index ..7cf5f2bc630a
--- /dev/null
+++ b/clang/test/Analysis/std-c-library-functions-restrict.c
@@ -0,0 +1,24 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-checker=debug.StdCLibraryFunctionsTester \
+// RUN:   -analyzer-config 
apiModeling.StdCLibraryFunctions:DisplayLoadedSummaries=true \
+// RUN:   -triple i686-unknown-linux 2>&1 | FileCheck %s
+
+// The signatures for these functions are the same and they specify their
+// parameter with the restrict qualifier. In C, the signature should match only
+// if the restri

[PATCH] D86874: [analyzer] Fix ArrayBoundCheckerV2 false positive regarding size_t indexer

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

In D86874#2255990 , @martong wrote:

> Hi Balázs,
>
> Since reviews.llvm.org is offline, I am sending my comments below, inline.
> Thanks for your huge effort in explaining all this!
>
> Overall, I have a feeling that this approach targets only one specific
> case, which is fine. But I believe we should think about all the other
> possible cases, so we could get rid of other false positives too:
>
> 1. In case of multidimensional arrays, there may be a symbolic value in any
>
> dimension.

Yes, obviously - but it's not a problem. See my next comment.

> 2. What if  there are more symbolic values in the dimensions.

It stops the //simplification// process on the very first `SymExpr` which is 
not a `SymIntExpr`. This //simplification// is done on a //best effort// basis 
only.

Another interesting fact is that we don't generate nested `ElementRegion`s too 
frequently, so don't have to deal with //"What if  there are more symbolic 
values in the dimensions."// :D
The last two lines of the following example are particularly interesting, I'm 
curious why we do that.

Let's see some examples:

  void foo(int x, int y) {
int buf[10][3];
clang_analyzer_dump(&buf[1][2]);   // &Element{Element{buf,1 S64b,int 
[3]},2 S64b,int}
clang_analyzer_dump(&buf[1][y]);   // Unknown
clang_analyzer_dump(&buf[x][2]);   // &Element{Element{buf,reg_$1,int [3]},2 S64b,int}
clang_analyzer_dump(&buf[x][y]);   // Unknown
clang_analyzer_dump(&buf[1][y+1]); // Unknown
clang_analyzer_dump(&buf[x][y+1]); // Unknown
clang_analyzer_dump(&buf[x+1][2]); // &Element{Element{buf,(reg_$1) 
+ 1,int [3]},2 S64b,int}
clang_analyzer_dump(&buf[1+x][2]); // &Element{Element{buf,(reg_$1) 
+ 1,int [3]},2 S64b,int}
clang_analyzer_dump(&buf[x+1][y+2]); // Unknown
  
// Another surprise is that if we assign the pointer value to a variable, 
we get different results...
int *p = &buf[1][x+1];
clang_analyzer_dump(p);// &SymRegion{conj_$2{int *, LC1, S1740, 
#1}}
clang_analyzer_dump(&buf[1][x+1]); // Unknown
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86874

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


[PATCH] D86089: [flang][driver]Add experimental flang driver and frontend with help screen

2020-09-04 Thread Richard Barton via Phabricator via cfe-commits
richard.barton.arm added a comment.

Another random thought that just came to me: what does the new driver do when 
you invoke it with no input files or options? I could imagine a few sensible 
outcomes (error: no input (clang and gcc/gfortran behaviour), print version and 
exit, print help and exit, etc.) and I don't have a strong preference over 
which we chose here but I think there should be a test for it in test/Driver


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86089

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


[PATCH] D86660: Modifying ImportDeclContext(...) to ensure that we also handle the case when the FieldDecl is an ArrayType whose ElementType is a RecordDecl

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

The key question is this: Why exactly does `1735: ExpectedDecl ImportedOrErr = 
import(From);` fails to do the import properly when called from 
ASTImporter::ImportDefinition? Would it be possible to debug that from your 
LLDB test cases? Maybe starting with the simpler tests in D71378 
?

In D86660#2255360 , @shafik wrote:

> @martong I have been experimenting w/ how we pass around 
> `ImportDefinitionKind` and pushing it through to more places does not help. I 
> also tried defaulting most locations to `IDK_Everything` to experiment to see 
> if maybe I was missing some crucial point and no luck. So while it seemed 
> like a good direction it has not worked out, unless I missed something in 
> your idea.

These are bad news, probably I am missing something. Still, we should not give 
up the investigation, or not at least in a long term. I really think we have to 
fix this sooner or later. What about the other approaches (trying to get rid of 
the minimal flag, trying to get rid of the kind, moving the minimal flag to the 
nodeimporter, and could be other ideas as well)?

> So my current approach may be the best we have until we can do some larger 
> refactoring.

Okay, I understand this fixes the immediate issue and we don't have any other 
solution yet without significant more efforts.

> I had explored trying to fix this from the codegen and sema side of things 
> but after discussing this w/ @rsmith there is no simple fix there that would 
> not require some large refactoring on the LLDB side.

There must be a way to fix this in ASTImporter and/or in LLDB. We should be 
able to provide an AST that is meaningful for the codegen. But yeah, some 
refactoring might be needed.


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

https://reviews.llvm.org/D86660

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


[PATCH] D86796: [Sema] Address-space sensitive index check for unbounded arrays

2020-09-04 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:14063
+  if (isUnboundedArray) {
+if (index.isUnsigned() || !index.isNegative()) {
+  const auto &ASTC = getASTContext();

This could be early return to avoid the indentation.



Comment at: clang/lib/Sema/SemaChecking.cpp:13981
+bool overflow;
+llvm::APInt product(index);
+product += 1;

chrish_ericsson_atx wrote:
> ebevhan wrote:
> > What if index is wider than AddrBits, but the active bits are fewer? Then 
> > you might miss out on triggering the overflow case in the multiplication.
> Line 13984 checks for active bits of product being less than AddrBits, which 
> is the same case (since product, by definition, has same width as index).  So 
> I think this is covered.  If I've misunderstood, please re-ping.
The overflow limit for _ovf is determined by the width of the APInt. If index 
is 32 bits wide but only has 14 bits active, and AddrBits is 16, then an 
umul_ovf might overflow past 16 bits but not for 32 bits since the product is 
the same width as the index. Then we won't detect the overflow.



Comment at: clang/lib/Sema/SemaChecking.cpp:13993
+  MaxElems.zext(std::max(AddrBits << 1, apElemBytes.getBitWidth()));
+  MaxElems += 1;
+  if (MaxElems.getBitWidth() < apElemBytes.getBitWidth())

chrish_ericsson_atx wrote:
> ebevhan wrote:
> > Though, why is the +1 here? Isn't this already the maximum number of 
> > elements?
> Initial value of MaxElems is APInt::getMaxValue(AddrBits), which is the index 
> of the last addressable CharUnit in the address space.  Adding 1 makes it the 
> total number of addressable CharUnits in the address space, which is what we 
> want as the numerator for computing total number of elements of a given size 
> that will fit in that address space.
> 
Ah, yes. Got indexes and sizes mixed up again.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86796

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


[PATCH] D75044: [AArch64] __builtin_return_address for PAuth.

2020-09-04 Thread Daniel Kiss via Phabricator via cfe-commits
danielkiss added a comment.

@chill Could you check the latest update? I think it should be submitted with 
D84502  together.


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

https://reviews.llvm.org/D75044

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


[clang] 2c9dbcd - [modules] Correctly parse LateParsedTemplates in case of dependent modules.

2020-09-04 Thread Vassil Vassilev via cfe-commits

Author: Vaibhav Garg
Date: 2020-09-04T11:39:04Z
New Revision: 2c9dbcda4f71497d4a58020bb093af438fb6e967

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

LOG: [modules] Correctly parse LateParsedTemplates in case of dependent modules.

While parsing LateParsedTemplates, Clang assumes that the Global DeclID matches
with the Local DeclID of a Decl. This is not the case when we have multiple
dependent modules , each having their own LateParsedTemplate section. In such a
case, a Local/Global DeclID confusion occurs which leads to improper casting of
FunctionDecl's.

This commit creates a Vector to map the LateParsedTemplate section of each
Module with their module file and therefore resolving the Global/Local DeclID
confusion.

Reviewed By: rsmith

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

Added: 


Modified: 
clang/include/clang/Serialization/ASTReader.h
clang/lib/Serialization/ASTReader.cpp

Removed: 




diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index b6892e295ac7..29c4f15e57b0 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -900,8 +900,9 @@ class ASTReader
   /// Delete expressions to analyze at the end of translation unit.
   SmallVector DelayedDeleteExprs;
 
-  // A list of late parsed template function data.
-  SmallVector LateParsedTemplates;
+  // A list of late parsed template function data with their module files.
+  SmallVector>, 4>
+  LateParsedTemplates;
 
   /// The IDs of all decls to be checked for deferred diags.
   ///

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 55d68a7c6919..6f5fa67117c0 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -3722,7 +3722,9 @@ ASTReader::ReadASTBlock(ModuleFile &F, unsigned 
ClientLoadCapabilities) {
 }
 
 case LATE_PARSED_TEMPLATE:
-  LateParsedTemplates.append(Record.begin(), Record.end());
+  LateParsedTemplates.emplace_back(
+  std::piecewise_construct, std::forward_as_tuple(&F),
+  std::forward_as_tuple(Record.begin(), Record.end()));
   break;
 
 case OPTIMIZE_PRAGMA_OPTIONS:
@@ -8389,25 +8391,28 @@ void ASTReader::ReadPendingInstantiations(
 void ASTReader::ReadLateParsedTemplates(
 llvm::MapVector>
 &LPTMap) {
-  for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
-   /* In loop */) {
-FunctionDecl *FD = cast(GetDecl(LateParsedTemplates[Idx++]));
+  for (auto &LPT : LateParsedTemplates) {
+ModuleFile *FMod = LPT.first;
+RecordDataImpl &LateParsed = LPT.second;
+for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
+ /* In loop */) {
+  FunctionDecl *FD =
+  cast(GetLocalDecl(*FMod, LateParsed[Idx++]));
 
-auto LT = std::make_unique();
-LT->D = GetDecl(LateParsedTemplates[Idx++]);
+  auto LT = std::make_unique();
+  LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
 
-ModuleFile *F = getOwningModuleFile(LT->D);
-assert(F && "No module");
+  ModuleFile *F = getOwningModuleFile(LT->D);
+  assert(F && "No module");
 
-unsigned TokN = LateParsedTemplates[Idx++];
-LT->Toks.reserve(TokN);
-for (unsigned T = 0; T < TokN; ++T)
-  LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
+  unsigned TokN = LateParsed[Idx++];
+  LT->Toks.reserve(TokN);
+  for (unsigned T = 0; T < TokN; ++T)
+LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
 
-LPTMap.insert(std::make_pair(FD, std::move(LT)));
+  LPTMap.insert(std::make_pair(FD, std::move(LT)));
+}
   }
-
-  LateParsedTemplates.clear();
 }
 
 void ASTReader::LoadSelector(Selector Sel) {



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


[PATCH] D86514: Correctly parse LateParsedTemplates in case of multiple dependent modules

2020-09-04 Thread Vassil Vassilev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2c9dbcda4f71: [modules] Correctly parse LateParsedTemplates 
in case of dependent modules. (authored by gargvaibhav64, committed by 
v.g.vassilev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86514

Files:
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Serialization/ASTReader.cpp


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -3722,7 +3722,9 @@
 }
 
 case LATE_PARSED_TEMPLATE:
-  LateParsedTemplates.append(Record.begin(), Record.end());
+  LateParsedTemplates.emplace_back(
+  std::piecewise_construct, std::forward_as_tuple(&F),
+  std::forward_as_tuple(Record.begin(), Record.end()));
   break;
 
 case OPTIMIZE_PRAGMA_OPTIONS:
@@ -8389,25 +8391,28 @@
 void ASTReader::ReadLateParsedTemplates(
 llvm::MapVector>
 &LPTMap) {
-  for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
-   /* In loop */) {
-FunctionDecl *FD = cast(GetDecl(LateParsedTemplates[Idx++]));
+  for (auto &LPT : LateParsedTemplates) {
+ModuleFile *FMod = LPT.first;
+RecordDataImpl &LateParsed = LPT.second;
+for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
+ /* In loop */) {
+  FunctionDecl *FD =
+  cast(GetLocalDecl(*FMod, LateParsed[Idx++]));
 
-auto LT = std::make_unique();
-LT->D = GetDecl(LateParsedTemplates[Idx++]);
+  auto LT = std::make_unique();
+  LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
 
-ModuleFile *F = getOwningModuleFile(LT->D);
-assert(F && "No module");
+  ModuleFile *F = getOwningModuleFile(LT->D);
+  assert(F && "No module");
 
-unsigned TokN = LateParsedTemplates[Idx++];
-LT->Toks.reserve(TokN);
-for (unsigned T = 0; T < TokN; ++T)
-  LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
+  unsigned TokN = LateParsed[Idx++];
+  LT->Toks.reserve(TokN);
+  for (unsigned T = 0; T < TokN; ++T)
+LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
 
-LPTMap.insert(std::make_pair(FD, std::move(LT)));
+  LPTMap.insert(std::make_pair(FD, std::move(LT)));
+}
   }
-
-  LateParsedTemplates.clear();
 }
 
 void ASTReader::LoadSelector(Selector Sel) {
Index: clang/include/clang/Serialization/ASTReader.h
===
--- clang/include/clang/Serialization/ASTReader.h
+++ clang/include/clang/Serialization/ASTReader.h
@@ -900,8 +900,9 @@
   /// Delete expressions to analyze at the end of translation unit.
   SmallVector DelayedDeleteExprs;
 
-  // A list of late parsed template function data.
-  SmallVector LateParsedTemplates;
+  // A list of late parsed template function data with their module files.
+  SmallVector>, 4>
+  LateParsedTemplates;
 
   /// The IDs of all decls to be checked for deferred diags.
   ///


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -3722,7 +3722,9 @@
 }
 
 case LATE_PARSED_TEMPLATE:
-  LateParsedTemplates.append(Record.begin(), Record.end());
+  LateParsedTemplates.emplace_back(
+  std::piecewise_construct, std::forward_as_tuple(&F),
+  std::forward_as_tuple(Record.begin(), Record.end()));
   break;
 
 case OPTIMIZE_PRAGMA_OPTIONS:
@@ -8389,25 +8391,28 @@
 void ASTReader::ReadLateParsedTemplates(
 llvm::MapVector>
 &LPTMap) {
-  for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
-   /* In loop */) {
-FunctionDecl *FD = cast(GetDecl(LateParsedTemplates[Idx++]));
+  for (auto &LPT : LateParsedTemplates) {
+ModuleFile *FMod = LPT.first;
+RecordDataImpl &LateParsed = LPT.second;
+for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
+ /* In loop */) {
+  FunctionDecl *FD =
+  cast(GetLocalDecl(*FMod, LateParsed[Idx++]));
 
-auto LT = std::make_unique();
-LT->D = GetDecl(LateParsedTemplates[Idx++]);
+  auto LT = std::make_unique();
+  LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
 
-ModuleFile *F = getOwningModuleFile(LT->D);
-assert(F && "No module");
+  ModuleFile *F = getOwningModuleFile(LT->D);
+  assert(F && "No module");
 
-unsigned TokN = LateParsedTemplates[Idx++];
-LT->Toks.reserve(TokN);
-for (unsigned T = 0; T < TokN; ++T)
-  LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
+  unsigned TokN = LateParsed[Idx++];
+  LT->Toks.reserve(TokN);
+  for (unsigned T = 0; T < TokN; ++T)
+LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
 
-LPTMap.insert(std::make_pair(FD, std

[PATCH] D86874: [analyzer] Fix ArrayBoundCheckerV2 false positive regarding size_t indexer

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

I am coping my comments that I've sent in mail, just in case.

> However, in the checker, we don't check `byte offset < 0` directly.
> We //simplify// the left part of the `byte offset < 0` inequality by 
> substracting/dividing both sides with the constant `C`, if the `byte offset` 
> is a `SymintExpr` of `SymExpr OP C` over the plus or multiplication operator 
> (OP).
> We do this //simplification// recursively.
> In the end, we will have a //symbolic root// (call it `RootSym`) expression 
> and a `C'` constant over the right-hand side of the original relational 
> operator.
> So, after the //simplification// process we get the `RootSym < C'` 
> inequality, which we check.

Just for the record, this is in `getSimplifiedOffsets`.

> //Note: I don't know what `RegionRawOffset` is, or what that does.//

Seems like that is just a pair of a `MemRegion` plus a concrete int `Offset`. 
And this is the return type for `ElementRegion::getAsArrayOffset()` where we 
handle only `nonloc::ConcreteInt`s. So, this is similar to RegionRawOffsetV2, 
but without the possibility of the symbolic index value.

> Calculation of the RegionRawOffsetV2
> 
>
> Let's see how does these subscript expressions used during the calculation of 
> the `RegionRawOffsetV2`:
> For multi-dimension arrays we //fold// the index expressions of the nested 
> `ElementRegion`s.
> We are doing that by simply calculating the byte-offset of the nested region, 
> and adding the current level's //index*sizeof(Type)//.
> So, the `ByteOffset` that we build up will contain mostly multiplications by 
> a constant OR additions of symbolic expressions (like the `x+1` in the 
> example).

We have these lines in the case of handling the ElementRegion:

  if (!index.getAs())
return RegionRawOffsetV2();

So, if the index is symbolic we give up, don't we? So, how could this work with 
`x+1`? What am I missing here?

>   The resulting `RegionRawOffsetV2` for `p`, `q` will be:
>   p: {BaseRegion: `buf`, ByteOffset: `20 S64b`}
>   q: {BaseRegion: `buf`, ByteOffset: `(((reg_$0) + 1) * 12) + 24`}
> ^^^  ^^
>  |   |
>   `@a` This is an //object-language// expression. --/|
> /
>   `@b` The rest should be //meta-language// expression. ---/
>
> SPOILER: This distinction is really important here.
>
> So, we made an expression, we should not evaluate in either of the worlds.
> We should not evaluate it using the semantics of the //object-language// 
> since only the `@a` is of that world.
> We should model overflow in `@a` if that expression is of //unsigned// type 
> (OR signed but `-fwrapv`...) etc. according to the //abstract machine//.
> BUT modeling the possibility of an overflow of the rest of the expression 
> (`@b`) would be a flaw.

Why? I'd expect that the value of the whole expression `@a@b` could overflow.

> Simplify step, again
> 
>
>   Simplification of the `(((reg_$0) + 1) * 12) + 24` < `0` 
> inequality...
> ^^
>`@b`
>   Result:  `reg_$0 < -3 S64b`
> ^   ^^^
>   `RootSym` --/|
>   /
>   `C'` --/
>
> `#1`: This step supposed to fold **ONLY** the //meta-language// expression 
> parts (`@b`) of the previously aquired `ByteOffset`.
> `#2`: This step requires the expression under simplified to be of 
> //meta-language// to be able to reorder the constants. (aka. to fold into the 
> right hand side's constant).
> `#3`: This also requires the right-hand side to be of the //meta-language//.

Do I understand this correctly, that none of the binary operations can have a 
symbolic RHS, because that would mean we have a VLA?

> We treat the complete expression under //simplification// as an expression of 
> the //meta-language//.
> I'm not changing this, but I probably should though.

Again, I don't understand why you are sure that the value of //whole// 
expression cannot overflow.

> Ideally, after //simplification// we should have this inequality: `x+1 < -2`
> That way we would not fold any subexpression of the //object-language//, so 
> the `#1` requirement would be preserved.
> The right-hand side is of an expression of the //meta-language//.
> It makes sense, to evaluate the `operator<` as the semantics of the 
> //meta-language//.
> But the left-hand side is an expression of the //object-language//.
> We need some sort of //logical// conversion here.

What if the second index is also symbolic? E.g `buf[x+1][y+1]`?
This would result in `(((reg_$0) + 1) * 12) + (reg_$1) + 1)` < 
`0` . And after simplification, the RHS cannot be interpreted as //meta//.

> Check if the resulting //fold

[PATCH] D86874: [analyzer] Fix ArrayBoundCheckerV2 false positive regarding size_t indexer

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

About the whole raw offset and the related warning. There is a fundamental 
question: Should we warn at `&a[0][10]` ?

  void foo() {
int a[10][10];
int *p0 = &a[9][9];   // OK
int *p1 = &a[10][10]; // Out-of-bounds
static_assert(&a[0][10] == &a[1][0]);
int *p2 = &a[0][10];  // Syntactically (or technically) out-of-bounds, We 
should warn here !(?)
int *p3 = &a[1][0];   // Neither syntactically nor semantically 
out-of-bounds, but it aliases with p2 and p2 is flawed
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86874

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


[PATCH] D87138: [analyzer] Introduce refactoring of PthreadLockChecker

2020-09-04 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov created this revision.
ASDenysPetrov added reviewers: steakhal, vsavchenko, xazax.hun, NoQ, 
baloghadamsoftware.
ASDenysPetrov added a project: clang.
Herald added subscribers: cfe-commits, martong, Charusso, dkrupp, donat.nagy, 
Szelethus, mikhail.ramalho, a.sidorin, rnkovacs, szepet.
ASDenysPetrov requested review of this revision.

- Change capitalization of some names due to LLVM naming rules.
- Change names of some variables to make more speaking.
- Rework similar bug reports into one common function.

Prepare code for the next patches to reduce unrelated changes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D87138

Files:
  clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp

Index: clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
@@ -83,7 +83,7 @@
 private:
   typedef void (PthreadLockChecker::*FnCheck)(const CallEvent &Call,
   CheckerContext &C,
-  CheckerKind checkkind) const;
+  CheckerKind CheckKind) const;
   CallDescriptionMap PThreadCallbacks = {
   // Init.
   {{"pthread_mutex_init", 2}, &PthreadLockChecker::InitAnyLock},
@@ -167,46 +167,49 @@
   ProgramStateRef resolvePossiblyDestroyedMutex(ProgramStateRef state,
 const MemRegion *lockR,
 const SymbolRef *sym) const;
-  void reportUseDestroyedBug(const CallEvent &Call, CheckerContext &C,
- unsigned ArgNo, CheckerKind checkKind) const;
+  void reportBug(CheckerContext &C, std::unique_ptr BT[],
+ const Expr *MtxExpr, CheckerKind CheckKind,
+ StringRef Desc) const;
 
   // Init.
   void InitAnyLock(const CallEvent &Call, CheckerContext &C,
-   CheckerKind checkkind) const;
-  void InitLockAux(const CallEvent &Call, CheckerContext &C, unsigned ArgNo,
-   SVal Lock, CheckerKind checkkind) const;
+   CheckerKind CheckKind) const;
+  void InitLockAux(const CallEvent &Call, CheckerContext &C,
+   const Expr *MtxExpr, SVal MtxVal,
+   CheckerKind CheckKind) const;
 
   // Lock, Try-lock.
   void AcquirePthreadLock(const CallEvent &Call, CheckerContext &C,
-  CheckerKind checkkind) const;
+  CheckerKind CheckKind) const;
   void AcquireXNULock(const CallEvent &Call, CheckerContext &C,
-  CheckerKind checkkind) const;
+  CheckerKind CheckKind) const;
   void TryPthreadLock(const CallEvent &Call, CheckerContext &C,
-  CheckerKind checkkind) const;
+  CheckerKind CheckKind) const;
   void TryXNULock(const CallEvent &Call, CheckerContext &C,
-  CheckerKind checkkind) const;
+  CheckerKind CheckKind) const;
   void TryFuchsiaLock(const CallEvent &Call, CheckerContext &C,
-  CheckerKind checkkind) const;
+  CheckerKind CheckKind) const;
   void TryC11Lock(const CallEvent &Call, CheckerContext &C,
-  CheckerKind checkkind) const;
-  void AcquireLockAux(const CallEvent &Call, CheckerContext &C, unsigned ArgNo,
-  SVal lock, bool isTryLock, LockingSemantics semantics,
-  CheckerKind checkkind) const;
+  CheckerKind CheckKind) const;
+  void AcquireLockAux(const CallEvent &Call, CheckerContext &C,
+  const Expr *MtxExpr, SVal MtxVal, bool IsTryLock,
+  LockingSemantics Semantics, CheckerKind CheckKind) const;
 
   // Release.
   void ReleaseAnyLock(const CallEvent &Call, CheckerContext &C,
-  CheckerKind checkkind) const;
-  void ReleaseLockAux(const CallEvent &Call, CheckerContext &C, unsigned ArgNo,
-  SVal lock, CheckerKind checkkind) const;
+  CheckerKind CheckKind) const;
+  void ReleaseLockAux(const CallEvent &Call, CheckerContext &C,
+  const Expr *MtxExpr, SVal MtxVal,
+  CheckerKind CheckKind) const;
 
   // Destroy.
   void DestroyPthreadLock(const CallEvent &Call, CheckerContext &C,
-  CheckerKind checkkind) const;
+  CheckerKind CheckKind) const;
   void DestroyXNULock(const CallEvent &Call, CheckerContext &C,
-  CheckerKind checkkind) const;
-  void DestroyLockAux(const CallEvent &Call, CheckerContext &C, unsigned ArgNo,
-  SVal Lock, LockingSemantics semantics,
-  CheckerKind checkkind) const;
+  CheckerKind Check

[PATCH] D86796: [Sema] Address-space sensitive index check for unbounded arrays

2020-09-04 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:13981
+bool overflow;
+llvm::APInt product(index);
+product += 1;

ebevhan wrote:
> chrish_ericsson_atx wrote:
> > ebevhan wrote:
> > > What if index is wider than AddrBits, but the active bits are fewer? Then 
> > > you might miss out on triggering the overflow case in the multiplication.
> > Line 13984 checks for active bits of product being less than AddrBits, 
> > which is the same case (since product, by definition, has same width as 
> > index).  So I think this is covered.  If I've misunderstood, please re-ping.
> The overflow limit for _ovf is determined by the width of the APInt. If index 
> is 32 bits wide but only has 14 bits active, and AddrBits is 16, then an 
> umul_ovf might overflow past 16 bits but not for 32 bits since the product is 
> the same width as the index. Then we won't detect the overflow.
Scratch this; I missed the second getActiveBits check. With that it should be 
fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86796

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


[PATCH] D87138: [analyzer] Introduce refactoring of PthreadLockChecker

2020-09-04 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

This seems to be a total non-functional-change. Please include [NFC] next time 
with a similar refactoring. Otherwise, Looks good to me, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87138

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


[PATCH] D84604: Thread safety analysis: Consider global variables in scope

2020-09-04 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, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84604

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


[PATCH] D87066: Thread safety analysis: Improve documentation for scoped capabilities

2020-09-04 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.

Ah, this reads more clearly to me, thank you for the additional changes. LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87066

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


[PATCH] D66564: [clang-tidy] new altera struct pack align check

2020-09-04 Thread Frank Derry Wanye via Phabricator via cfe-commits
ffrankies added a comment.

@Eugene.Zelenko I don't have commit access to the repository, could you please 
commit this check on our behalf?


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

https://reviews.llvm.org/D66564

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


[PATCH] D66564: [clang-tidy] new altera struct pack align check

2020-09-04 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

In D66564#2256423 , @ffrankies wrote:

> @Eugene.Zelenko I don't have commit access to the repository, could you 
> please commit this check on our behalf?

Sorry, I don't have it either. @aaron.ballman or @njames93 could do this for 
you.


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

https://reviews.llvm.org/D66564

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


Re: [clang] e6393ee - Canonicalize declaration pointers when forming APValues.

2020-09-04 Thread Nico Weber via cfe-commits
Hi Richard,

this breaks Wunreachable-code which now ignore "weak" on redeclarations:

thakis@thakis:~/src/llvm-project$ cat foo.cc
extern "C" void foo(void);
extern "C" __attribute__((weak)) decltype(foo) foo;

void g(), h();
void f() {
if (foo)
  return g();
h();
}
thakis@thakis:~/src/llvm-project$ out/gn/bin/clang -Wunreachable-code -c
foo.cc
foo.cc:8:5: warning: code will never be executed [-Wunreachable-code]
h();
^

This seems to be a somewhat common pattern for calling new functions.

(Chromium bug: https://crbug.com/1125102)

On Thu, Sep 3, 2020 at 6:35 PM Richard Smith via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

>
> Author: Richard Smith
> Date: 2020-09-03T15:35:12-07:00
> New Revision: e6393ee813178e9d3306b8e3c6949a4f32f8a2cb
>
> URL:
> https://github.com/llvm/llvm-project/commit/e6393ee813178e9d3306b8e3c6949a4f32f8a2cb
> DIFF:
> https://github.com/llvm/llvm-project/commit/e6393ee813178e9d3306b8e3c6949a4f32f8a2cb.diff
>
> LOG: Canonicalize declaration pointers when forming APValues.
>
> References to different declarations of the same entity aren't different
> values, so shouldn't have different representations.
>
> Added:
>
>
> Modified:
> clang/include/clang/AST/APValue.h
> clang/lib/AST/APValue.cpp
> clang/lib/AST/ExprConstant.cpp
> clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p9.cpp
> clang/test/OpenMP/ordered_messages.cpp
>
> Removed:
>
>
>
>
> 
> diff  --git a/clang/include/clang/AST/APValue.h
> b/clang/include/clang/AST/APValue.h
> index 87e4bd7f84c1..485e6c2602cf 100644
> --- a/clang/include/clang/AST/APValue.h
> +++ b/clang/include/clang/AST/APValue.h
> @@ -174,6 +174,7 @@ class APValue {
>return !(LHS == RHS);
>  }
>  friend llvm::hash_code hash_value(const LValueBase &Base);
> +friend struct llvm::DenseMapInfo;
>
>private:
>  PtrTy Ptr;
> @@ -201,8 +202,7 @@ class APValue {
>
>public:
>  LValuePathEntry() : Value() {}
> -LValuePathEntry(BaseOrMemberType BaseOrMember)
> -:
> Value{reinterpret_cast(BaseOrMember.getOpaqueValue())} {}
> +LValuePathEntry(BaseOrMemberType BaseOrMember);
>  static LValuePathEntry ArrayIndex(uint64_t Index) {
>LValuePathEntry Result;
>Result.Value = Index;
>
> diff  --git a/clang/lib/AST/APValue.cpp b/clang/lib/AST/APValue.cpp
> index 2a8834b4db0c..7531229654cf 100644
> --- a/clang/lib/AST/APValue.cpp
> +++ b/clang/lib/AST/APValue.cpp
> @@ -38,7 +38,7 @@ static_assert(
>  "Type is insufficiently aligned");
>
>  APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I, unsigned
> V)
> -: Ptr(P), Local{I, V} {}
> +: Ptr(P ? cast(P->getCanonicalDecl()) : nullptr), Local{I,
> V} {}
>  APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
>  : Ptr(P), Local{I, V} {}
>
> @@ -82,13 +82,19 @@ bool operator==(const APValue::LValueBase &LHS,
>  const APValue::LValueBase &RHS) {
>if (LHS.Ptr != RHS.Ptr)
>  return false;
> -  if (LHS.is())
> +  if (LHS.is() || LHS.is())
>  return true;
>return LHS.Local.CallIndex == RHS.Local.CallIndex &&
>   LHS.Local.Version == RHS.Local.Version;
>  }
>  }
>
> +APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType BaseOrMember) {
> +  if (const Decl *D = BaseOrMember.getPointer())
> +BaseOrMember.setPointer(D->getCanonicalDecl());
> +  Value = reinterpret_cast(BaseOrMember.getOpaqueValue());
> +}
> +
>  namespace {
>struct LVBase {
>  APValue::LValueBase Base;
> @@ -113,14 +119,16 @@ APValue::LValueBase::operator bool () const {
>
>  clang::APValue::LValueBase
>  llvm::DenseMapInfo::getEmptyKey() {
> -  return clang::APValue::LValueBase(
> -  DenseMapInfo::getEmptyKey());
> +  clang::APValue::LValueBase B;
> +  B.Ptr = DenseMapInfo::getEmptyKey();
> +  return B;
>  }
>
>  clang::APValue::LValueBase
>  llvm::DenseMapInfo::getTombstoneKey() {
> -  return clang::APValue::LValueBase(
> -  DenseMapInfo::getTombstoneKey());
> +  clang::APValue::LValueBase B;
> +  B.Ptr = DenseMapInfo::getTombstoneKey();
> +  return B;
>  }
>
>  namespace clang {
> @@ -757,8 +765,10 @@ void APValue::MakeMemberPointer(const ValueDecl
> *Member, bool IsDerivedMember,
>assert(isAbsent() && "Bad state change");
>MemberPointerData *MPD = new ((void*)(char*)Data.buffer)
> MemberPointerData;
>Kind = MemberPointer;
> -  MPD->MemberAndIsDerivedMember.setPointer(Member);
> +  MPD->MemberAndIsDerivedMember.setPointer(
> +  Member ? cast(Member->getCanonicalDecl()) : nullptr);
>MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
>MPD->resizePath(Path.size());
> -  memcpy(MPD->getPath(), Path.data(), Path.size()*sizeof(const
> CXXRecordDecl*));
> +  for (unsigned I = 0; I != Path.size(); ++I)
> +MPD->getPath()[I] = Path[I]->getCanonicalDecl();
>  }
>
> diff  --git a/clang/lib/AST/ExprConstant.cpp
> b/clang/lib/AST/ExprConstant.cpp
> index e8

[clang] 7b03323 - Revert "Canonicalize declaration pointers when forming APValues."

2020-09-04 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2020-09-04T10:13:28-04:00
New Revision: 7b0332389afd705f46b02fcf87ec3414b8dece34

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

LOG: Revert "Canonicalize declaration pointers when forming APValues."

This reverts commit e6393ee813178e9d3306b8e3c6949a4f32f8a2cb.
It breaks Wunreachable for weak attributes, see
http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20200831/336645.html

Added: 


Modified: 
clang/include/clang/AST/APValue.h
clang/lib/AST/APValue.cpp
clang/lib/AST/ExprConstant.cpp
clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p9.cpp
clang/test/OpenMP/ordered_messages.cpp

Removed: 




diff  --git a/clang/include/clang/AST/APValue.h 
b/clang/include/clang/AST/APValue.h
index 485e6c2602cf..87e4bd7f84c1 100644
--- a/clang/include/clang/AST/APValue.h
+++ b/clang/include/clang/AST/APValue.h
@@ -174,7 +174,6 @@ class APValue {
   return !(LHS == RHS);
 }
 friend llvm::hash_code hash_value(const LValueBase &Base);
-friend struct llvm::DenseMapInfo;
 
   private:
 PtrTy Ptr;
@@ -202,7 +201,8 @@ class APValue {
 
   public:
 LValuePathEntry() : Value() {}
-LValuePathEntry(BaseOrMemberType BaseOrMember);
+LValuePathEntry(BaseOrMemberType BaseOrMember)
+: Value{reinterpret_cast(BaseOrMember.getOpaqueValue())} {}
 static LValuePathEntry ArrayIndex(uint64_t Index) {
   LValuePathEntry Result;
   Result.Value = Index;

diff  --git a/clang/lib/AST/APValue.cpp b/clang/lib/AST/APValue.cpp
index 7531229654cf..2a8834b4db0c 100644
--- a/clang/lib/AST/APValue.cpp
+++ b/clang/lib/AST/APValue.cpp
@@ -38,7 +38,7 @@ static_assert(
 "Type is insufficiently aligned");
 
 APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I, unsigned V)
-: Ptr(P ? cast(P->getCanonicalDecl()) : nullptr), Local{I, V} {}
+: Ptr(P), Local{I, V} {}
 APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
 : Ptr(P), Local{I, V} {}
 
@@ -82,19 +82,13 @@ bool operator==(const APValue::LValueBase &LHS,
 const APValue::LValueBase &RHS) {
   if (LHS.Ptr != RHS.Ptr)
 return false;
-  if (LHS.is() || LHS.is())
+  if (LHS.is())
 return true;
   return LHS.Local.CallIndex == RHS.Local.CallIndex &&
  LHS.Local.Version == RHS.Local.Version;
 }
 }
 
-APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType BaseOrMember) {
-  if (const Decl *D = BaseOrMember.getPointer())
-BaseOrMember.setPointer(D->getCanonicalDecl());
-  Value = reinterpret_cast(BaseOrMember.getOpaqueValue());
-}
-
 namespace {
   struct LVBase {
 APValue::LValueBase Base;
@@ -119,16 +113,14 @@ APValue::LValueBase::operator bool () const {
 
 clang::APValue::LValueBase
 llvm::DenseMapInfo::getEmptyKey() {
-  clang::APValue::LValueBase B;
-  B.Ptr = DenseMapInfo::getEmptyKey();
-  return B;
+  return clang::APValue::LValueBase(
+  DenseMapInfo::getEmptyKey());
 }
 
 clang::APValue::LValueBase
 llvm::DenseMapInfo::getTombstoneKey() {
-  clang::APValue::LValueBase B;
-  B.Ptr = DenseMapInfo::getTombstoneKey();
-  return B;
+  return clang::APValue::LValueBase(
+  DenseMapInfo::getTombstoneKey());
 }
 
 namespace clang {
@@ -765,10 +757,8 @@ void APValue::MakeMemberPointer(const ValueDecl *Member, 
bool IsDerivedMember,
   assert(isAbsent() && "Bad state change");
   MemberPointerData *MPD = new ((void*)(char*)Data.buffer) MemberPointerData;
   Kind = MemberPointer;
-  MPD->MemberAndIsDerivedMember.setPointer(
-  Member ? cast(Member->getCanonicalDecl()) : nullptr);
+  MPD->MemberAndIsDerivedMember.setPointer(Member);
   MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
   MPD->resizePath(Path.size());
-  for (unsigned I = 0; I != Path.size(); ++I)
-MPD->getPath()[I] = Path[I]->getCanonicalDecl();
+  memcpy(MPD->getPath(), Path.data(), Path.size()*sizeof(const 
CXXRecordDecl*));
 }

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 8e43b62662ee..e8f132dd4803 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -1978,11 +1978,18 @@ static bool HasSameBase(const LValue &A, const LValue 
&B) {
 return false;
 
   if (A.getLValueBase().getOpaqueValue() !=
-  B.getLValueBase().getOpaqueValue())
-return false;
+  B.getLValueBase().getOpaqueValue()) {
+const Decl *ADecl = GetLValueBaseDecl(A);
+if (!ADecl)
+  return false;
+const Decl *BDecl = GetLValueBaseDecl(B);
+if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
+  return false;
+  }
 
-  return A.getLValueCallIndex() == B.getLValueCallIndex() &&
- A.getLValueVersion() == B.getLValueVersion();
+  return IsGlobalLValue(A.getLValueBase()) ||
+ (A.getLValueCallIndex() == B.getLValueC

Re: [clang] e6393ee - Canonicalize declaration pointers when forming APValues.

2020-09-04 Thread Nico Weber via cfe-commits
To keep the bots greener over the long weekend, I went ahead and reverted
this for now in 7b0332389afd705f46b02fcf87ec3414b8dece34. I'll add a test
for this.

On Fri, Sep 4, 2020 at 10:11 AM Nico Weber  wrote:

> Hi Richard,
>
> this breaks Wunreachable-code which now ignore "weak" on redeclarations:
>
> thakis@thakis:~/src/llvm-project$ cat foo.cc
> extern "C" void foo(void);
> extern "C" __attribute__((weak)) decltype(foo) foo;
>
> void g(), h();
> void f() {
> if (foo)
>   return g();
> h();
> }
> thakis@thakis:~/src/llvm-project$ out/gn/bin/clang -Wunreachable-code -c
> foo.cc
> foo.cc:8:5: warning: code will never be executed [-Wunreachable-code]
> h();
> ^
>
> This seems to be a somewhat common pattern for calling new functions.
>
> (Chromium bug: https://crbug.com/1125102)
>
> On Thu, Sep 3, 2020 at 6:35 PM Richard Smith via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>>
>> Author: Richard Smith
>> Date: 2020-09-03T15:35:12-07:00
>> New Revision: e6393ee813178e9d3306b8e3c6949a4f32f8a2cb
>>
>> URL:
>> https://github.com/llvm/llvm-project/commit/e6393ee813178e9d3306b8e3c6949a4f32f8a2cb
>> DIFF:
>> https://github.com/llvm/llvm-project/commit/e6393ee813178e9d3306b8e3c6949a4f32f8a2cb.diff
>>
>> LOG: Canonicalize declaration pointers when forming APValues.
>>
>> References to different declarations of the same entity aren't different
>> values, so shouldn't have different representations.
>>
>> Added:
>>
>>
>> Modified:
>> clang/include/clang/AST/APValue.h
>> clang/lib/AST/APValue.cpp
>> clang/lib/AST/ExprConstant.cpp
>> clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p9.cpp
>> clang/test/OpenMP/ordered_messages.cpp
>>
>> Removed:
>>
>>
>>
>>
>> 
>> diff  --git a/clang/include/clang/AST/APValue.h
>> b/clang/include/clang/AST/APValue.h
>> index 87e4bd7f84c1..485e6c2602cf 100644
>> --- a/clang/include/clang/AST/APValue.h
>> +++ b/clang/include/clang/AST/APValue.h
>> @@ -174,6 +174,7 @@ class APValue {
>>return !(LHS == RHS);
>>  }
>>  friend llvm::hash_code hash_value(const LValueBase &Base);
>> +friend struct llvm::DenseMapInfo;
>>
>>private:
>>  PtrTy Ptr;
>> @@ -201,8 +202,7 @@ class APValue {
>>
>>public:
>>  LValuePathEntry() : Value() {}
>> -LValuePathEntry(BaseOrMemberType BaseOrMember)
>> -:
>> Value{reinterpret_cast(BaseOrMember.getOpaqueValue())} {}
>> +LValuePathEntry(BaseOrMemberType BaseOrMember);
>>  static LValuePathEntry ArrayIndex(uint64_t Index) {
>>LValuePathEntry Result;
>>Result.Value = Index;
>>
>> diff  --git a/clang/lib/AST/APValue.cpp b/clang/lib/AST/APValue.cpp
>> index 2a8834b4db0c..7531229654cf 100644
>> --- a/clang/lib/AST/APValue.cpp
>> +++ b/clang/lib/AST/APValue.cpp
>> @@ -38,7 +38,7 @@ static_assert(
>>  "Type is insufficiently aligned");
>>
>>  APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I, unsigned
>> V)
>> -: Ptr(P), Local{I, V} {}
>> +: Ptr(P ? cast(P->getCanonicalDecl()) : nullptr),
>> Local{I, V} {}
>>  APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
>>  : Ptr(P), Local{I, V} {}
>>
>> @@ -82,13 +82,19 @@ bool operator==(const APValue::LValueBase &LHS,
>>  const APValue::LValueBase &RHS) {
>>if (LHS.Ptr != RHS.Ptr)
>>  return false;
>> -  if (LHS.is())
>> +  if (LHS.is() || LHS.is())
>>  return true;
>>return LHS.Local.CallIndex == RHS.Local.CallIndex &&
>>   LHS.Local.Version == RHS.Local.Version;
>>  }
>>  }
>>
>> +APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType BaseOrMember)
>> {
>> +  if (const Decl *D = BaseOrMember.getPointer())
>> +BaseOrMember.setPointer(D->getCanonicalDecl());
>> +  Value = reinterpret_cast(BaseOrMember.getOpaqueValue());
>> +}
>> +
>>  namespace {
>>struct LVBase {
>>  APValue::LValueBase Base;
>> @@ -113,14 +119,16 @@ APValue::LValueBase::operator bool () const {
>>
>>  clang::APValue::LValueBase
>>  llvm::DenseMapInfo::getEmptyKey() {
>> -  return clang::APValue::LValueBase(
>> -  DenseMapInfo::getEmptyKey());
>> +  clang::APValue::LValueBase B;
>> +  B.Ptr = DenseMapInfo::getEmptyKey();
>> +  return B;
>>  }
>>
>>  clang::APValue::LValueBase
>>  llvm::DenseMapInfo::getTombstoneKey() {
>> -  return clang::APValue::LValueBase(
>> -  DenseMapInfo::getTombstoneKey());
>> +  clang::APValue::LValueBase B;
>> +  B.Ptr = DenseMapInfo::getTombstoneKey();
>> +  return B;
>>  }
>>
>>  namespace clang {
>> @@ -757,8 +765,10 @@ void APValue::MakeMemberPointer(const ValueDecl
>> *Member, bool IsDerivedMember,
>>assert(isAbsent() && "Bad state change");
>>MemberPointerData *MPD = new ((void*)(char*)Data.buffer)
>> MemberPointerData;
>>Kind = MemberPointer;
>> -  MPD->MemberAndIsDerivedMember.setPointer(Member);
>> +  MPD->MemberAndIsDerivedMember.setPointer(
>> +  Member ? cast(Member->getCanonicalDecl()) : nullptr);
>>

Re: [clang] e6393ee - Canonicalize declaration pointers when forming APValues.

2020-09-04 Thread Nico Weber via cfe-commits
Test added in 85a9f6512a3cff797f1964c36c59d53e97a680c4

On Fri, Sep 4, 2020 at 10:14 AM Nico Weber  wrote:

> To keep the bots greener over the long weekend, I went ahead and reverted
> this for now in 7b0332389afd705f46b02fcf87ec3414b8dece34. I'll add a test
> for this.
>
> On Fri, Sep 4, 2020 at 10:11 AM Nico Weber  wrote:
>
>> Hi Richard,
>>
>> this breaks Wunreachable-code which now ignore "weak" on redeclarations:
>>
>> thakis@thakis:~/src/llvm-project$ cat foo.cc
>> extern "C" void foo(void);
>> extern "C" __attribute__((weak)) decltype(foo) foo;
>>
>> void g(), h();
>> void f() {
>> if (foo)
>>   return g();
>> h();
>> }
>> thakis@thakis:~/src/llvm-project$ out/gn/bin/clang -Wunreachable-code -c
>> foo.cc
>> foo.cc:8:5: warning: code will never be executed [-Wunreachable-code]
>> h();
>> ^
>>
>> This seems to be a somewhat common pattern for calling new functions.
>>
>> (Chromium bug: https://crbug.com/1125102)
>>
>> On Thu, Sep 3, 2020 at 6:35 PM Richard Smith via cfe-commits <
>> cfe-commits@lists.llvm.org> wrote:
>>
>>>
>>> Author: Richard Smith
>>> Date: 2020-09-03T15:35:12-07:00
>>> New Revision: e6393ee813178e9d3306b8e3c6949a4f32f8a2cb
>>>
>>> URL:
>>> https://github.com/llvm/llvm-project/commit/e6393ee813178e9d3306b8e3c6949a4f32f8a2cb
>>> DIFF:
>>> https://github.com/llvm/llvm-project/commit/e6393ee813178e9d3306b8e3c6949a4f32f8a2cb.diff
>>>
>>> LOG: Canonicalize declaration pointers when forming APValues.
>>>
>>> References to different declarations of the same entity aren't different
>>> values, so shouldn't have different representations.
>>>
>>> Added:
>>>
>>>
>>> Modified:
>>> clang/include/clang/AST/APValue.h
>>> clang/lib/AST/APValue.cpp
>>> clang/lib/AST/ExprConstant.cpp
>>> clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p9.cpp
>>> clang/test/OpenMP/ordered_messages.cpp
>>>
>>> Removed:
>>>
>>>
>>>
>>>
>>> 
>>> diff  --git a/clang/include/clang/AST/APValue.h
>>> b/clang/include/clang/AST/APValue.h
>>> index 87e4bd7f84c1..485e6c2602cf 100644
>>> --- a/clang/include/clang/AST/APValue.h
>>> +++ b/clang/include/clang/AST/APValue.h
>>> @@ -174,6 +174,7 @@ class APValue {
>>>return !(LHS == RHS);
>>>  }
>>>  friend llvm::hash_code hash_value(const LValueBase &Base);
>>> +friend struct llvm::DenseMapInfo;
>>>
>>>private:
>>>  PtrTy Ptr;
>>> @@ -201,8 +202,7 @@ class APValue {
>>>
>>>public:
>>>  LValuePathEntry() : Value() {}
>>> -LValuePathEntry(BaseOrMemberType BaseOrMember)
>>> -:
>>> Value{reinterpret_cast(BaseOrMember.getOpaqueValue())} {}
>>> +LValuePathEntry(BaseOrMemberType BaseOrMember);
>>>  static LValuePathEntry ArrayIndex(uint64_t Index) {
>>>LValuePathEntry Result;
>>>Result.Value = Index;
>>>
>>> diff  --git a/clang/lib/AST/APValue.cpp b/clang/lib/AST/APValue.cpp
>>> index 2a8834b4db0c..7531229654cf 100644
>>> --- a/clang/lib/AST/APValue.cpp
>>> +++ b/clang/lib/AST/APValue.cpp
>>> @@ -38,7 +38,7 @@ static_assert(
>>>  "Type is insufficiently aligned");
>>>
>>>  APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I,
>>> unsigned V)
>>> -: Ptr(P), Local{I, V} {}
>>> +: Ptr(P ? cast(P->getCanonicalDecl()) : nullptr),
>>> Local{I, V} {}
>>>  APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
>>>  : Ptr(P), Local{I, V} {}
>>>
>>> @@ -82,13 +82,19 @@ bool operator==(const APValue::LValueBase &LHS,
>>>  const APValue::LValueBase &RHS) {
>>>if (LHS.Ptr != RHS.Ptr)
>>>  return false;
>>> -  if (LHS.is())
>>> +  if (LHS.is() || LHS.is())
>>>  return true;
>>>return LHS.Local.CallIndex == RHS.Local.CallIndex &&
>>>   LHS.Local.Version == RHS.Local.Version;
>>>  }
>>>  }
>>>
>>> +APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType
>>> BaseOrMember) {
>>> +  if (const Decl *D = BaseOrMember.getPointer())
>>> +BaseOrMember.setPointer(D->getCanonicalDecl());
>>> +  Value = reinterpret_cast(BaseOrMember.getOpaqueValue());
>>> +}
>>> +
>>>  namespace {
>>>struct LVBase {
>>>  APValue::LValueBase Base;
>>> @@ -113,14 +119,16 @@ APValue::LValueBase::operator bool () const {
>>>
>>>  clang::APValue::LValueBase
>>>  llvm::DenseMapInfo::getEmptyKey() {
>>> -  return clang::APValue::LValueBase(
>>> -  DenseMapInfo::getEmptyKey());
>>> +  clang::APValue::LValueBase B;
>>> +  B.Ptr = DenseMapInfo::getEmptyKey();
>>> +  return B;
>>>  }
>>>
>>>  clang::APValue::LValueBase
>>>  llvm::DenseMapInfo::getTombstoneKey() {
>>> -  return clang::APValue::LValueBase(
>>> -  DenseMapInfo::getTombstoneKey());
>>> +  clang::APValue::LValueBase B;
>>> +  B.Ptr = DenseMapInfo::getTombstoneKey();
>>> +  return B;
>>>  }
>>>
>>>  namespace clang {
>>> @@ -757,8 +765,10 @@ void APValue::MakeMemberPointer(const ValueDecl
>>> *Member, bool IsDerivedMember,
>>>assert(isAbsent() && "Bad state change");
>>>MemberPointerD

[PATCH] D86796: [Sema] Address-space sensitive index check for unbounded arrays

2020-09-04 Thread Chris Hamilton via Phabricator via cfe-commits
chrish_ericsson_atx added a comment.

Thanks for the excellent feedback, @ebevhan .   @aaron.ballman , @krememek , or 
@rsmith , could one of you take a look at this change and if it's acceptable, 
please approve it?   I have not requested commit privileges yet, either, so I 
will need your assistance to land this change, assuming it's acceptable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86796

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


[PATCH] D87143: Check whether Gentoo-specific configuration directory exists

2020-09-04 Thread Dmitry Antipov via Phabricator via cfe-commits
dmantipov created this revision.
dmantipov added a reviewer: manojgupta.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
dmantipov requested review of this revision.

Check whether /etc/env.d/gcc exists before trying to read from any
file from there. This saves a few OS calls on a non-Gentoo system.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D87143

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Gnu.h


Index: clang/lib/Driver/ToolChains/Gnu.h
===
--- clang/lib/Driver/ToolChains/Gnu.h
+++ clang/lib/Driver/ToolChains/Gnu.h
@@ -212,6 +212,9 @@
 /// The set of multilibs that the detected installation supports.
 MultilibSet Multilibs;
 
+// Gentoo-specific toolchain configurations are stored here.
+const std::string GentooConfigDir = "/etc/env.d/gcc";
+
   public:
 explicit GCCInstallationDetector(const Driver &D) : IsValid(false), D(D) {}
 void init(const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args,
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2534,6 +2534,9 @@
 const llvm::Triple &TargetTriple, const ArgList &Args,
 const SmallVectorImpl &CandidateTriples,
 const SmallVectorImpl &CandidateBiarchTriples) {
+  if (!D.getVFS().exists(GentooConfigDir))
+return false;
+
   for (StringRef CandidateTriple : CandidateTriples) {
 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
   return true;
@@ -2550,8 +2553,8 @@
 const llvm::Triple &TargetTriple, const ArgList &Args,
 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
   llvm::ErrorOr> File =
-  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
-  CandidateTriple.str());
+  D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir +
+  "/config-" + CandidateTriple.str());
   if (File) {
 SmallVector Lines;
 File.get()->getBuffer().split(Lines, "\n");
@@ -2562,8 +2565,8 @@
 continue;
   // Process the config file pointed to by CURRENT.
   llvm::ErrorOr> ConfigFile =
-  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/" +
-  Line.str());
+  D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir +
+  "/" + Line.str());
   std::pair ActiveVersion = Line.rsplit('-');
   // List of paths to scan for libraries.
   SmallVector GentooScanPaths;


Index: clang/lib/Driver/ToolChains/Gnu.h
===
--- clang/lib/Driver/ToolChains/Gnu.h
+++ clang/lib/Driver/ToolChains/Gnu.h
@@ -212,6 +212,9 @@
 /// The set of multilibs that the detected installation supports.
 MultilibSet Multilibs;
 
+// Gentoo-specific toolchain configurations are stored here.
+const std::string GentooConfigDir = "/etc/env.d/gcc";
+
   public:
 explicit GCCInstallationDetector(const Driver &D) : IsValid(false), D(D) {}
 void init(const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args,
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2534,6 +2534,9 @@
 const llvm::Triple &TargetTriple, const ArgList &Args,
 const SmallVectorImpl &CandidateTriples,
 const SmallVectorImpl &CandidateBiarchTriples) {
+  if (!D.getVFS().exists(GentooConfigDir))
+return false;
+
   for (StringRef CandidateTriple : CandidateTriples) {
 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
   return true;
@@ -2550,8 +2553,8 @@
 const llvm::Triple &TargetTriple, const ArgList &Args,
 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
   llvm::ErrorOr> File =
-  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
-  CandidateTriple.str());
+  D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir +
+  "/config-" + CandidateTriple.str());
   if (File) {
 SmallVector Lines;
 File.get()->getBuffer().split(Lines, "\n");
@@ -2562,8 +2565,8 @@
 continue;
   // Process the config file pointed to by CURRENT.
   llvm::ErrorOr> ConfigFile =
-  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/" +
-  Line.str());
+  D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir +
+  "/" + Line.str());
   std::pair ActiveVersion = Line.rsplit('-');
   // List of paths to scan for libraries.
   SmallVector GentooScanPaths;
___
cfe-commits ma

[clang] 2a03f27 - clang: Add test for -Wunreachable-code + weak redeclaration

2020-09-04 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2020-09-04T10:35:50-04:00
New Revision: 2a03f270d69cf1079feb029f84727288e217588a

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

LOG: clang: Add test for -Wunreachable-code + weak redeclaration

This tests what caused the revert in 7b033238.

Added: 


Modified: 
clang/test/SemaCXX/unreachable-code.cpp

Removed: 




diff  --git a/clang/test/SemaCXX/unreachable-code.cpp 
b/clang/test/SemaCXX/unreachable-code.cpp
index fd006c099e7d..0dfc3d5744fb 100644
--- a/clang/test/SemaCXX/unreachable-code.cpp
+++ b/clang/test/SemaCXX/unreachable-code.cpp
@@ -68,3 +68,12 @@ int pr6130(unsigned i) {
   throw PR6130(); // no-warning
   }
 }
+
+extern "C" void foo(void);
+extern "C" __attribute__((weak)) decltype(foo) foo;
+
+void weak_redecl() {
+  if (foo)
+return;
+  bar(); // no-warning
+}



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


Re: [clang] e6393ee - Canonicalize declaration pointers when forming APValues.

2020-09-04 Thread Nico Weber via cfe-commits
Actually in 2a03f270d69cf1079feb029f84727288e217588a

On Fri, Sep 4, 2020 at 10:27 AM Nico Weber  wrote:

> Test added in 85a9f6512a3cff797f1964c36c59d53e97a680c4
>
> On Fri, Sep 4, 2020 at 10:14 AM Nico Weber  wrote:
>
>> To keep the bots greener over the long weekend, I went ahead and reverted
>> this for now in 7b0332389afd705f46b02fcf87ec3414b8dece34. I'll add a test
>> for this.
>>
>> On Fri, Sep 4, 2020 at 10:11 AM Nico Weber  wrote:
>>
>>> Hi Richard,
>>>
>>> this breaks Wunreachable-code which now ignore "weak" on redeclarations:
>>>
>>> thakis@thakis:~/src/llvm-project$ cat foo.cc
>>> extern "C" void foo(void);
>>> extern "C" __attribute__((weak)) decltype(foo) foo;
>>>
>>> void g(), h();
>>> void f() {
>>> if (foo)
>>>   return g();
>>> h();
>>> }
>>> thakis@thakis:~/src/llvm-project$ out/gn/bin/clang -Wunreachable-code
>>> -c foo.cc
>>> foo.cc:8:5: warning: code will never be executed [-Wunreachable-code]
>>> h();
>>> ^
>>>
>>> This seems to be a somewhat common pattern for calling new functions.
>>>
>>> (Chromium bug: https://crbug.com/1125102)
>>>
>>> On Thu, Sep 3, 2020 at 6:35 PM Richard Smith via cfe-commits <
>>> cfe-commits@lists.llvm.org> wrote:
>>>

 Author: Richard Smith
 Date: 2020-09-03T15:35:12-07:00
 New Revision: e6393ee813178e9d3306b8e3c6949a4f32f8a2cb

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

 LOG: Canonicalize declaration pointers when forming APValues.

 References to different declarations of the same entity aren't different
 values, so shouldn't have different representations.

 Added:


 Modified:
 clang/include/clang/AST/APValue.h
 clang/lib/AST/APValue.cpp
 clang/lib/AST/ExprConstant.cpp
 clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p9.cpp
 clang/test/OpenMP/ordered_messages.cpp

 Removed:




 
 diff  --git a/clang/include/clang/AST/APValue.h
 b/clang/include/clang/AST/APValue.h
 index 87e4bd7f84c1..485e6c2602cf 100644
 --- a/clang/include/clang/AST/APValue.h
 +++ b/clang/include/clang/AST/APValue.h
 @@ -174,6 +174,7 @@ class APValue {
return !(LHS == RHS);
  }
  friend llvm::hash_code hash_value(const LValueBase &Base);
 +friend struct llvm::DenseMapInfo;

private:
  PtrTy Ptr;
 @@ -201,8 +202,7 @@ class APValue {

public:
  LValuePathEntry() : Value() {}
 -LValuePathEntry(BaseOrMemberType BaseOrMember)
 -:
 Value{reinterpret_cast(BaseOrMember.getOpaqueValue())} {}
 +LValuePathEntry(BaseOrMemberType BaseOrMember);
  static LValuePathEntry ArrayIndex(uint64_t Index) {
LValuePathEntry Result;
Result.Value = Index;

 diff  --git a/clang/lib/AST/APValue.cpp b/clang/lib/AST/APValue.cpp
 index 2a8834b4db0c..7531229654cf 100644
 --- a/clang/lib/AST/APValue.cpp
 +++ b/clang/lib/AST/APValue.cpp
 @@ -38,7 +38,7 @@ static_assert(
  "Type is insufficiently aligned");

  APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I,
 unsigned V)
 -: Ptr(P), Local{I, V} {}
 +: Ptr(P ? cast(P->getCanonicalDecl()) : nullptr),
 Local{I, V} {}
  APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
  : Ptr(P), Local{I, V} {}

 @@ -82,13 +82,19 @@ bool operator==(const APValue::LValueBase &LHS,
  const APValue::LValueBase &RHS) {
if (LHS.Ptr != RHS.Ptr)
  return false;
 -  if (LHS.is())
 +  if (LHS.is() || LHS.is())
  return true;
return LHS.Local.CallIndex == RHS.Local.CallIndex &&
   LHS.Local.Version == RHS.Local.Version;
  }
  }

 +APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType
 BaseOrMember) {
 +  if (const Decl *D = BaseOrMember.getPointer())
 +BaseOrMember.setPointer(D->getCanonicalDecl());
 +  Value = reinterpret_cast(BaseOrMember.getOpaqueValue());
 +}
 +
  namespace {
struct LVBase {
  APValue::LValueBase Base;
 @@ -113,14 +119,16 @@ APValue::LValueBase::operator bool () const {

  clang::APValue::LValueBase
  llvm::DenseMapInfo::getEmptyKey() {
 -  return clang::APValue::LValueBase(
 -  DenseMapInfo::getEmptyKey());
 +  clang::APValue::LValueBase B;
 +  B.Ptr = DenseMapInfo::getEmptyKey();
 +  return B;
  }

  clang::APValue::LValueBase
  llvm::DenseMapInfo::getTombstoneKey() {
 -  return clang::APValue::LValueBase(
 -  DenseMapInfo::getTombstoneKey());
 +  clang::APValue::LValueBase B;
 +  B.Ptr = DenseMa

[PATCH] D66564: [clang-tidy] new altera struct pack align check

2020-09-04 Thread Frank Derry Wanye via Phabricator via cfe-commits
ffrankies added a comment.

In D66564#2256424 , @Eugene.Zelenko 
wrote:

> In D66564#2256423 , @ffrankies wrote:
>
>> @Eugene.Zelenko I don't have commit access to the repository, could you 
>> please commit this check on our behalf?
>
> Sorry, I don't have it either. @aaron.ballman or @njames93 could do this for 
> you.

No problem. @aaron.ballman @njames93 Could one of you please commit this check 
on our behalf?


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

https://reviews.llvm.org/D66564

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


[PATCH] D86775: [clang-format] Parse __ptr32/__ptr64 as a pointer qualifier

2020-09-04 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay 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/D86775/new/

https://reviews.llvm.org/D86775

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


[PATCH] D86926: FormatTest: Provide real line number in failure messages

2020-09-04 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, I've certainly been bit myself in the past with not knowing which 
test actually failed especially when they are all foo() something.. thank you


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86926

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


[PATCH] D86941: [clang-format] Add a test showing the current config file list parsing

2020-09-04 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay 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/D86941/new/

https://reviews.llvm.org/D86941

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


[PATCH] D87006: [clang-format][NFC] Store FormatToken::Type as an enum instead of bitfield

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

I'm not a C++ language lawyer so I'm not sure which standard introduce enum 
inheritance? (maybe its something we could always do?), if its a recent change 
we just need to ensure we are conforming to the C++ version that is needed to 
build clang.

Apart from that it looks good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87006

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


[PATCH] D86959: [clang-format] Fix formatting of _Atomic() qualifier

2020-09-04 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


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86959

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


[PATCH] D87138: [analyzer][NFC] Introduce refactoring of PthreadLockChecker

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

In D87138#2256360 , @martong wrote:

> This seems to be a total non-functional-change. Please include [NFC] next 
> time with a similar refactoring. Otherwise, Looks good to me, thanks!

Thanks! Added [NFC] to the title.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87138

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


[PATCH] D87101: [X86] Update SSE/AVX ABS intrinsics to emit llvm.abs.* (PR46851)

2020-09-04 Thread Sanjay Patel via Phabricator via cfe-commits
spatel accepted this revision.
spatel added a comment.
This revision is now accepted and ready to land.

LGTM - I think the odds of code that is using intrinsic vector abs inter-mixing 
with auto-vectorized code using the abs idiom are small.

I noticed one other LLVM codegen test that might want to be updated to use the 
IR intrinsics to be more relevant -- 
llvm-project/llvm/test/CodeGen/X86/combine-abs.ll. That can be done with this 
patch or later.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87101

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


[PATCH] D86295: [analyzer] Reorder the layout of MemRegion and cache by hand for optimal size

2020-09-04 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov accepted this revision.
ASDenysPetrov added a comment.
This revision is now accepted and ready to land.

The change LGTM,!. If it really can speed up performance or improve memory 
organization, let's load this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86295

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


[PATCH] D84415: [analyzer][StdLibraryFunctionsChecker] Add POSIX pthread handling functions

2020-09-04 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 289970.
martong added a comment.

- Rebase to master


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84415

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-POSIX.c

Index: clang/test/Analysis/std-c-library-functions-POSIX.c
===
--- clang/test/Analysis/std-c-library-functions-POSIX.c
+++ clang/test/Analysis/std-c-library-functions-POSIX.c
@@ -95,6 +95,20 @@
 // CHECK: Loaded summary for: ssize_t send(int sockfd, const void *buf, size_t len, int flags)
 // CHECK: Loaded summary for: int socketpair(int domain, int type, int protocol, int sv[2])
 // CHECK: Loaded summary for: int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen, char *restrict node, socklen_t nodelen, char *restrict service, socklen_t servicelen, int flags)
+// CHECK: Loaded summary for: int pthread_cond_signal(pthread_cond_t *cond)
+// CHECK: Loaded summary for: int pthread_cond_broadcast(pthread_cond_t *cond)
+// CHECK: Loaded summary for: int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg)
+// CHECK: Loaded summary for: int pthread_attr_destroy(pthread_attr_t *attr)
+// CHECK: Loaded summary for: int pthread_attr_init(pthread_attr_t *attr)
+// CHECK: Loaded summary for: int pthread_attr_getstacksize(const pthread_attr_t *restrict attr, size_t *restrict stacksize)
+// CHECK: Loaded summary for: int pthread_attr_getguardsize(const pthread_attr_t *restrict attr, size_t *restrict guardsize)
+// CHECK: Loaded summary for: int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
+// CHECK: Loaded summary for: int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize)
+// CHECK: Loaded summary for: int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr)
+// CHECK: Loaded summary for: int pthread_mutex_destroy(pthread_mutex_t *mutex)
+// CHECK: Loaded summary for: int pthread_mutex_lock(pthread_mutex_t *mutex)
+// CHECK: Loaded summary for: int pthread_mutex_trylock(pthread_mutex_t *mutex)
+// CHECK: Loaded summary for: int pthread_mutex_unlock(pthread_mutex_t *mutex)
 
 long a64l(const char *str64);
 char *l64a(long value);
@@ -227,6 +241,34 @@
 int socketpair(int domain, int type, int protocol, int sv[2]);
 int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen, char *restrict node, socklen_t nodelen, char *restrict service, socklen_t servicelen, int flags);
 
+typedef union {
+  int x;
+} pthread_cond_t;
+int pthread_cond_signal(pthread_cond_t *cond);
+int pthread_cond_broadcast(pthread_cond_t *cond);
+typedef union {
+  int x;
+} pthread_attr_t;
+typedef unsigned long int pthread_t;
+int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg);
+int pthread_attr_destroy(pthread_attr_t *attr);
+int pthread_attr_init(pthread_attr_t *attr);
+int pthread_attr_getstacksize(const pthread_attr_t *restrict attr, size_t *restrict stacksize);
+int pthread_attr_getguardsize(const pthread_attr_t *restrict attr, size_t *restrict guardsize);
+int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
+int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize);
+typedef union {
+  int x;
+} pthread_mutex_t;
+typedef union {
+  int x;
+} pthread_mutexattr_t;
+int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
+int pthread_mutex_destroy(pthread_mutex_t *mutex);
+int pthread_mutex_lock(pthread_mutex_t *mutex);
+int pthread_mutex_trylock(pthread_mutex_t *mutex);
+int pthread_mutex_unlock(pthread_mutex_t *mutex);
+
 // Must have at least one call expression to initialize the summary map.
 int bar(void);
 void foo() {
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -931,6 +931,8 @@
   const QualType ConstWchar_tPtrTy =
   getPointerTy(getConstTy(WCharTy)); // const wchar_t *
   const QualType ConstVoidPtrRestrictTy = getRestrictTy(ConstVoidPtrTy);
+  const QualType SizePtrTy = getPointerTy(SizeTy);
+  const QualType SizePtrRestrictTy = getRestrictTy(SizePtrTy);
 
   const RangeInt IntMax = BVF.getMaxValue(IntTy).getLimitedValue();
   const RangeInt UnsignedIntMax =
@@ -2036,6 +2038,99 @@
 BufferSize(/*Buffer=*/ArgNo(4), /*BufSize=*/ArgNo(5)))
 .ArgConstraint(
 ArgumentCondition(5, WithinRange, Range(0, Socklen_tMax;
+
+Optional Pthread_cond_tTy = lookupTy("pthread_cond_t");
+Optional Pthread_cond_tPtrTy = 

[PATCH] D84415: [analyzer][StdLibraryFunctionsChecker] Add POSIX pthread handling functions

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

Polite ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84415

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


[PATCH] D87081: [analyzer][StdLibraryFunctionsChecker] Elaborate the summary of fread and fwrite

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

This checker will make an additional assumption on `fread` and `fwrite` with 
the ReturnValueCondition. The return value is constrained by `StreamChecker` 
too but it splits the error (if returned value is less that arg 3) and 
non-error cases into separate branches. I think this causes no problem because 
it will refine the assumption made here (if this assumption is made first) or 
the assumption here has no effect (if the split happened already).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87081

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


[clang] 8c810ac - [clang-format] Parse __ptr32/__ptr64 as a pointer qualifier

2020-09-04 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-04T16:56:21+01:00
New Revision: 8c810acc94ed462238242c04c75ab33fc96da6e8

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

LOG: [clang-format] Parse __ptr32/__ptr64 as a pointer qualifier

Before:
x = (foo *__ptr32) * v;
MACRO(A * __ptr32 a);
x = (foo *__ptr64) * v;
MACRO(A * __ptr64 a);

After:
x = (foo *__ptr32)*v;
MACRO(A *__ptr32 a);
x = (foo *__ptr64)*v;
MACRO(A *__ptr64 a);

Depends on D86721 (to apply cleanly)

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index a54600a478a4..ad72a95062ab 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -442,7 +442,7 @@ struct FormatToken {
   bool canBePointerOrReferenceQualifier() const {
 return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
tok::kw___attribute, tok::kw__Nonnull, tok::kw__Nullable,
-   tok::kw__Null_unspecified);
+   tok::kw__Null_unspecified, tok::kw___ptr32, 
tok::kw___ptr64);
   }
 
   /// Determine whether the token is a simple-type-specifier.

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 14c97784b738..716fe2bf50ae 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8028,6 +8028,8 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("foo();");
@@ -8070,6 +8072,8 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
+  verifyIndependentOfContext("MACRO(A *__ptr32 a);");
+  verifyIndependentOfContext("MACRO(A *__ptr64 a);");
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   // FIXME: Is there a way to make this work?
@@ -8141,6 +8145,8 @@ TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
   verifyFormat("x = (foo *_Nonnull)*v;");
   verifyFormat("x = (foo *[[clang::attr]])*v;");
   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
+  verifyFormat("x = (foo *__ptr32)*v;");
+  verifyFormat("x = (foo *__ptr64)*v;");
 
   // Check that we handle multiple trailing qualifiers and skip them all to
   // determine that the expression is a cast to a pointer type.
@@ -8149,7 +8155,7 @@ TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
   StringRef AllQualifiers =
   "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified 
"
-  "_Nonnull [[clang::attr]]";
+  "_Nonnull [[clang::attr]] __ptr32 __ptr64";
   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), 
LongPointerRight);
   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
 



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


[clang] 2108bce - FormatTest: Provide real line number in failure messages

2020-09-04 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-04T16:57:46+01:00
New Revision: 2108bceceb5e6eca361aaa6b10441d83bd9edc1b

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

LOG: FormatTest: Provide real line number in failure messages

Currently a test failure always reports a line number inside verifyFormat()
which is not very helpful to see which test failed. With this change we now
emit the line number where the verify function was called. When using an
IDE such as CLion, the output now includes a clickable link that points to
the call site.

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 716fe2bf50ae..a2d694947990 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -20,6 +20,7 @@
 
 using clang::tooling::ReplacementTest;
 using clang::tooling::toReplacements;
+using testing::internal::ScopedTrace;
 
 namespace clang {
 namespace format {
@@ -65,8 +66,10 @@ class FormatTest : public ::testing::Test {
 return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
   }
 
-  void verifyFormat(llvm::StringRef Expected, llvm::StringRef Code,
-const FormatStyle &Style = getLLVMStyle()) {
+  void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
+ llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 EXPECT_EQ(Expected.str(), format(Expected, Style))
 << "Expected code is not stable";
 EXPECT_EQ(Expected.str(), format(Code, Style));
@@ -79,24 +82,24 @@ class FormatTest : public ::testing::Test {
 }
   }
 
-  void verifyFormat(llvm::StringRef Code,
-const FormatStyle &Style = getLLVMStyle()) {
-verifyFormat(Code, test::messUp(Code), Style);
+  void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+_verifyFormat(File, Line, Code, test::messUp(Code), Style);
   }
 
-  void verifyIncompleteFormat(llvm::StringRef Code,
-  const FormatStyle &Style = getLLVMStyle()) {
+  void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef 
Code,
+   const FormatStyle &Style = getLLVMStyle()) {
+ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 EXPECT_EQ(Code.str(),
   format(test::messUp(Code), Style, SC_ExpectIncomplete));
   }
 
-  void verifyGoogleFormat(llvm::StringRef Code) {
-verifyFormat(Code, getGoogleStyle());
-  }
-
-  void verifyIndependentOfContext(llvm::StringRef text) {
-verifyFormat(text);
-verifyFormat(llvm::Twine("void f() { " + text + " }").str());
+  void _verifyIndependentOfContext(const char *File, int Line,
+   llvm::StringRef Text,
+   const FormatStyle &Style = getLLVMStyle()) {
+_verifyFormat(File, Line, Text, Style);
+_verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
+  Style);
   }
 
   /// \brief Verify that clang-format does not crash on the given input.
@@ -108,6 +111,13 @@ class FormatTest : public ::testing::Test {
   int ReplacementCount;
 };
 
+#define verifyIndependentOfContext(...)
\
+  _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyIncompleteFormat(...)
\
+  _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
+
 TEST_F(FormatTest, MessUp) {
   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));



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


[PATCH] D86775: [clang-format] Parse __ptr32/__ptr64 as a pointer qualifier

2020-09-04 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8c810acc94ed: [clang-format] Parse __ptr32/__ptr64 as a 
pointer qualifier (authored by arichardson).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86775

Files:
  clang/lib/Format/FormatToken.h
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8028,6 +8028,8 @@
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("foo();");
@@ -8070,6 +8072,8 @@
   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
+  verifyIndependentOfContext("MACRO(A *__ptr32 a);");
+  verifyIndependentOfContext("MACRO(A *__ptr64 a);");
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   // FIXME: Is there a way to make this work?
@@ -8141,6 +8145,8 @@
   verifyFormat("x = (foo *_Nonnull)*v;");
   verifyFormat("x = (foo *[[clang::attr]])*v;");
   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
+  verifyFormat("x = (foo *__ptr32)*v;");
+  verifyFormat("x = (foo *__ptr64)*v;");
 
   // Check that we handle multiple trailing qualifiers and skip them all to
   // determine that the expression is a cast to a pointer type.
@@ -8149,7 +8155,7 @@
   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
   StringRef AllQualifiers =
   "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified 
"
-  "_Nonnull [[clang::attr]]";
+  "_Nonnull [[clang::attr]] __ptr32 __ptr64";
   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), 
LongPointerRight);
   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
 
Index: clang/lib/Format/FormatToken.h
===
--- clang/lib/Format/FormatToken.h
+++ clang/lib/Format/FormatToken.h
@@ -442,7 +442,7 @@
   bool canBePointerOrReferenceQualifier() const {
 return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
tok::kw___attribute, tok::kw__Nonnull, tok::kw__Nullable,
-   tok::kw__Null_unspecified);
+   tok::kw__Null_unspecified, tok::kw___ptr32, 
tok::kw___ptr64);
   }
 
   /// Determine whether the token is a simple-type-specifier.


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8028,6 +8028,8 @@
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("foo();");
@@ -8070,6 +8072,8 @@
   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
+  verifyIndependentOfContext("MACRO(A *__ptr32 a);");
+  verifyIndependentOfContext("MACRO(A *__ptr64 a);");
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   // FIXME: Is there a way to make this work?
@@ -8141,6 +8145,8 @@
   verifyFormat("x = (foo *_Nonnull)*v;");
   verifyFormat("x = (foo *[[clang::attr]])*v;");
   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
+  verifyFormat("x = (foo *__ptr32)*v;");
+  verifyFormat("x = (foo *__ptr64)*v;");
 
   // Check that we handle multiple trailing qualifiers and skip them all to
   // determine that the expression is a cast to a pointer type.
@@ -8149,7 +8155,7 @@
   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
   StringRef AllQualifiers =
   "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
-  "_Nonnull [[clang::attr]]";
+  "_Nonnull [[clang::attr]] __ptr32 __ptr64";
   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
 
Index: clang/lib/Format/FormatToken.h
===
--- clang/lib/Format/FormatToken.h
+++ clang/lib/Format/FormatToken.h
@@ -442,7 +442,7 @@
   bool canBePointerOrReferenceQualifier() const {
 return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
tok::kw___attribute, tok::kw__Nonnull, tok::kw

[clang] e0ff5a8 - [clang-format] Add a test showing the current config file list parsing

2020-09-04 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-04T16:57:46+01:00
New Revision: e0ff5a8410ea58ba3d2e75791789a28ce976a7e7

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

LOG: [clang-format] Add a test showing the current config file list parsing

Currently clang-format starts overriding the default values at index 0
(keeping the existing values) instead of appending or replacing all values.
This patch simply checks the current (IMO surprising) behaviour and does
not attempt to change it.

Reviewed By: MyDeveloperDay

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

Added: 
clang/test/Format/dump-config-list-override.cpp

Modified: 


Removed: 




diff  --git a/clang/test/Format/dump-config-list-override.cpp 
b/clang/test/Format/dump-config-list-override.cpp
new file mode 100644
index ..df4c6ad1333e
--- /dev/null
+++ b/clang/test/Format/dump-config-list-override.cpp
@@ -0,0 +1,24 @@
+/// Check that the ForEachMacros, etc. config entries replace default values 
instead of appending
+/// FIXME: clang-format currently start overriding at index 0 (keeping the 
remaining
+/// values) instead of either appending or completely replacing the values.
+/// This behaviour is highly confusing. For now this test documents the 
current state.
+// RUN: clang-format -style="{BasedOnStyle: LLVM}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,DEFAULT
+// RUN: clang-format -style="{BasedOnStyle: LLVM, ForEachMacros: 
['OVERRIDE_FOREACH']}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,OVERRIDE,FIXME-SHOULD-NOT-BE
+// RUN: clang-format -style="{BasedOnStyle: LLVM, ForEachMacros: ['M1', 'M2', 
'M3', 'M4']}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,MORE-ENTRIES-THAN-DEFAULT
+
+
+// CHECK-LABEL:   ForEachMacros:
+// DEFAULT-NEXT:  {{^  }}- foreach
+// DEFAULT-NEXT:  {{^  }}- Q_FOREACH
+// DEFAULT-NEXT:  {{^  }}- BOOST_FOREACH
+// OVERRIDE-NEXT: {{^  }}- OVERRIDE_FOREACH
+// FIXME-SHOULD-NOT-BE-NEXT:  {{^  }}- Q_FOREACH
+// FIXME-SHOULD-NOT-BE-NEXT:  {{^  }}- BOOST_FOREACH
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M1
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M2
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M3
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M4
+// CHECK-NEXT:{{^[F-Z]}}



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


[PATCH] D86926: FormatTest: Provide real line number in failure messages

2020-09-04 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2108bceceb5e: FormatTest: Provide real line number in 
failure messages (authored by arichardson).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86926

Files:
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -20,6 +20,7 @@
 
 using clang::tooling::ReplacementTest;
 using clang::tooling::toReplacements;
+using testing::internal::ScopedTrace;
 
 namespace clang {
 namespace format {
@@ -65,8 +66,10 @@
 return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
   }
 
-  void verifyFormat(llvm::StringRef Expected, llvm::StringRef Code,
-const FormatStyle &Style = getLLVMStyle()) {
+  void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
+ llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 EXPECT_EQ(Expected.str(), format(Expected, Style))
 << "Expected code is not stable";
 EXPECT_EQ(Expected.str(), format(Code, Style));
@@ -79,24 +82,24 @@
 }
   }
 
-  void verifyFormat(llvm::StringRef Code,
-const FormatStyle &Style = getLLVMStyle()) {
-verifyFormat(Code, test::messUp(Code), Style);
+  void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+_verifyFormat(File, Line, Code, test::messUp(Code), Style);
   }
 
-  void verifyIncompleteFormat(llvm::StringRef Code,
-  const FormatStyle &Style = getLLVMStyle()) {
+  void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef 
Code,
+   const FormatStyle &Style = getLLVMStyle()) {
+ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 EXPECT_EQ(Code.str(),
   format(test::messUp(Code), Style, SC_ExpectIncomplete));
   }
 
-  void verifyGoogleFormat(llvm::StringRef Code) {
-verifyFormat(Code, getGoogleStyle());
-  }
-
-  void verifyIndependentOfContext(llvm::StringRef text) {
-verifyFormat(text);
-verifyFormat(llvm::Twine("void f() { " + text + " }").str());
+  void _verifyIndependentOfContext(const char *File, int Line,
+   llvm::StringRef Text,
+   const FormatStyle &Style = getLLVMStyle()) {
+_verifyFormat(File, Line, Text, Style);
+_verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
+  Style);
   }
 
   /// \brief Verify that clang-format does not crash on the given input.
@@ -108,6 +111,13 @@
   int ReplacementCount;
 };
 
+#define verifyIndependentOfContext(...)
\
+  _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyIncompleteFormat(...)
\
+  _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
+
 TEST_F(FormatTest, MessUp) {
   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -20,6 +20,7 @@
 
 using clang::tooling::ReplacementTest;
 using clang::tooling::toReplacements;
+using testing::internal::ScopedTrace;
 
 namespace clang {
 namespace format {
@@ -65,8 +66,10 @@
 return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
   }
 
-  void verifyFormat(llvm::StringRef Expected, llvm::StringRef Code,
-const FormatStyle &Style = getLLVMStyle()) {
+  void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
+ llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 EXPECT_EQ(Expected.str(), format(Expected, Style))
 << "Expected code is not stable";
 EXPECT_EQ(Expected.str(), format(Code, Style));
@@ -79,24 +82,24 @@
 }
   }
 
-  void verifyFormat(llvm::StringRef Code,
-const FormatStyle &Style = getLLVMStyle()) {
-verifyFormat(Code, test::messUp(Code), Style);
+  void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+_verifyFormat(File, Line, Code, test::messUp(Code), Style);
   }
 
-  void verifyIncomple

[PATCH] D86941: [clang-format] Add a test showing the current config file list parsing

2020-09-04 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe0ff5a8410ea: [clang-format] Add a test showing the current 
config file list parsing (authored by arichardson).

Changed prior to commit:
  https://reviews.llvm.org/D86941?vs=289166&id=289974#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86941

Files:
  clang/test/Format/dump-config-list-override.cpp


Index: clang/test/Format/dump-config-list-override.cpp
===
--- /dev/null
+++ clang/test/Format/dump-config-list-override.cpp
@@ -0,0 +1,24 @@
+/// Check that the ForEachMacros, etc. config entries replace default values 
instead of appending
+/// FIXME: clang-format currently start overriding at index 0 (keeping the 
remaining
+/// values) instead of either appending or completely replacing the values.
+/// This behaviour is highly confusing. For now this test documents the 
current state.
+// RUN: clang-format -style="{BasedOnStyle: LLVM}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,DEFAULT
+// RUN: clang-format -style="{BasedOnStyle: LLVM, ForEachMacros: 
['OVERRIDE_FOREACH']}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,OVERRIDE,FIXME-SHOULD-NOT-BE
+// RUN: clang-format -style="{BasedOnStyle: LLVM, ForEachMacros: ['M1', 'M2', 
'M3', 'M4']}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,MORE-ENTRIES-THAN-DEFAULT
+
+
+// CHECK-LABEL:   ForEachMacros:
+// DEFAULT-NEXT:  {{^  }}- foreach
+// DEFAULT-NEXT:  {{^  }}- Q_FOREACH
+// DEFAULT-NEXT:  {{^  }}- BOOST_FOREACH
+// OVERRIDE-NEXT: {{^  }}- OVERRIDE_FOREACH
+// FIXME-SHOULD-NOT-BE-NEXT:  {{^  }}- Q_FOREACH
+// FIXME-SHOULD-NOT-BE-NEXT:  {{^  }}- BOOST_FOREACH
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M1
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M2
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M3
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M4
+// CHECK-NEXT:{{^[F-Z]}}


Index: clang/test/Format/dump-config-list-override.cpp
===
--- /dev/null
+++ clang/test/Format/dump-config-list-override.cpp
@@ -0,0 +1,24 @@
+/// Check that the ForEachMacros, etc. config entries replace default values instead of appending
+/// FIXME: clang-format currently start overriding at index 0 (keeping the remaining
+/// values) instead of either appending or completely replacing the values.
+/// This behaviour is highly confusing. For now this test documents the current state.
+// RUN: clang-format -style="{BasedOnStyle: LLVM}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,DEFAULT
+// RUN: clang-format -style="{BasedOnStyle: LLVM, ForEachMacros: ['OVERRIDE_FOREACH']}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,OVERRIDE,FIXME-SHOULD-NOT-BE
+// RUN: clang-format -style="{BasedOnStyle: LLVM, ForEachMacros: ['M1', 'M2', 'M3', 'M4']}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,MORE-ENTRIES-THAN-DEFAULT
+
+
+// CHECK-LABEL:   ForEachMacros:
+// DEFAULT-NEXT:  {{^  }}- foreach
+// DEFAULT-NEXT:  {{^  }}- Q_FOREACH
+// DEFAULT-NEXT:  {{^  }}- BOOST_FOREACH
+// OVERRIDE-NEXT: {{^  }}- OVERRIDE_FOREACH
+// FIXME-SHOULD-NOT-BE-NEXT:  {{^  }}- Q_FOREACH
+// FIXME-SHOULD-NOT-BE-NEXT:  {{^  }}- BOOST_FOREACH
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M1
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M2
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M3
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M4
+// CHECK-NEXT:{{^[F-Z]}}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 45c3560 - [HeapProf] Address post-review comments in instrumentation code

2020-09-04 Thread Teresa Johnson via cfe-commits

Author: Teresa Johnson
Date: 2020-09-04T08:59:00-07:00
New Revision: 45c3560384814d04c9813e644efa8e2155ecae52

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

LOG: [HeapProf] Address post-review comments in instrumentation code

Addresses post-review comments from D85948, which can be found here:
https://reviews.llvm.org/rG7ed8124d46f9.

Added: 


Modified: 
clang/include/clang/Basic/CodeGenOptions.def
clang/include/clang/Driver/Options.td
clang/lib/Driver/SanitizerArgs.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/Driver/fmemprof.cpp
llvm/include/llvm/Transforms/Instrumentation/HeapProfiler.h
llvm/lib/Transforms/Instrumentation/HeapProfiler.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 8b89aac8d6d5..ec77f68062e7 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -145,7 +145,7 @@ CODEGENOPT(IncrementalLinkerCompatible, 1, 0) ///< Emit an 
object file which can
   ///< linker.
 CODEGENOPT(MergeAllConstants , 1, 1) ///< Merge identical constants.
 CODEGENOPT(MergeFunctions, 1, 0) ///< Set when -fmerge-functions is 
enabled.
-CODEGENOPT(HeapProf  , 1, 0) ///< Set when -fmemprof is enabled.
+CODEGENOPT(HeapProf  , 1, 0) ///< Set when -fmemory-profile is enabled.
 CODEGENOPT(MSVolatile, 1, 0) ///< Set when /volatile:ms is enabled.
 CODEGENOPT(NoCommon  , 1, 0) ///< Set when -fno-common or C++ is 
enabled.
 CODEGENOPT(NoDwarfDirectoryAsm , 1, 0) ///< Set when -fno-dwarf-directory-asm 
is

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 912192660c14..5f1668e701f1 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -995,7 +995,7 @@ defm cxx_static_destructors : 
OptOutFFlag<"c++-static-destructors", "",
 def fsymbol_partition_EQ : Joined<["-"], "fsymbol-partition=">, Group,
   Flags<[CC1Option]>;
 
-defm memprof : OptInFFlag<"memprof", "Enable", "Disable", " heap memory 
profiling">;
+defm memory_profile : OptInFFlag<"memory-profile", "Enable", "Disable", " heap 
memory profiling">;
 
 // Begin sanitizer flags. These should all be core options exposed in all 
driver
 // modes.

diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index cce0eb557a9c..0f51443010ca 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -866,8 +866,8 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
 LinkCXXRuntimes) ||
 D.CCCIsCXX();
 
-  NeedsHeapProfRt =
-  Args.hasFlag(options::OPT_fmemprof, options::OPT_fno_memprof, false);
+  NeedsHeapProfRt = Args.hasFlag(options::OPT_fmemory_profile,
+ options::OPT_fno_memory_profile, false);
 
   // Finally, initialize the set of available and recoverable sanitizers.
   Sanitizers.Mask |= Kinds;

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bd5a89c2360c..1680f2ad91ea 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4224,8 +4224,9 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   if (Args.getLastArg(options::OPT_save_temps_EQ))
 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
 
-  if (Args.hasFlag(options::OPT_fmemprof, options::OPT_fno_memprof, false))
-Args.AddLastArg(CmdArgs, options::OPT_fmemprof);
+  if (Args.hasFlag(options::OPT_fmemory_profile,
+   options::OPT_fno_memory_profile, false))
+Args.AddLastArg(CmdArgs, options::OPT_fmemory_profile);
 
   // Embed-bitcode option.
   // Only white-listed flags below are allowed to be embedded.

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 9143dd6ca257..fbccff11562c 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -1033,7 +1033,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, 
ArgList &Args, InputKind IK,
   Opts.ThinLinkBitcodeFile =
   std::string(Args.getLastArgValue(OPT_fthin_link_bitcode_EQ));
 
-  Opts.HeapProf = Args.hasArg(OPT_fmemprof);
+  Opts.HeapProf = Args.hasArg(OPT_fmemory_profile);
 
   Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
 

diff  --git a/clang/test/Driver/fmemprof.cpp b/clang/test/Driver/fmemprof.cpp
index 049067803e2b..a2b740e1e6e5 100644
--- a/clang/test/Driver/fmemprof.cpp
+++ b/clang/test/Driver/fmemprof.cpp
@@ -1,6 +1,6 @@
-// RUN: %clangxx -targe

[PATCH] D85091: [Sema, CodeGen] Implement [[likely]] and [[unlikely]] in IfStmt

2020-09-04 Thread Mark de Wever via Phabricator via cfe-commits
Mordante marked an inline comment as done.
Mordante added inline comments.



Comment at: clang/lib/Sema/SemaStmt.cpp:578
+static std::pair
+getLikelihood(const Stmt *Stmt) {
+  if (const auto *AS = dyn_cast(Stmt))

aaron.ballman wrote:
> Mordante wrote:
> > rsmith wrote:
> > > Mordante wrote:
> > > > aaron.ballman wrote:
> > > > > rsmith wrote:
> > > > > > Sema doesn't care about any of this; can you move this code to 
> > > > > > CodeGen and remove the code that stores likelihood data in the AST?
> > > > > FWIW, I asked for it to be moved out of CodeGen and into Sema because 
> > > > > the original implementation in CodeGen was doing a fair amount of 
> > > > > work trying to interrogate the AST for this information. Now that 
> > > > > we've switched the design to only be on the substatement of an 
> > > > > if/else statement (rather than an arbitrary statement), it may be 
> > > > > that CodeGen is a better place for this again (and if so, I'm sorry 
> > > > > for the churn).
> > > > At the moment the Sema cares about it to generate diagnostics about 
> > > > conflicting annotations:
> > > > ```
> > > > if(i) [[ likely]] {}
> > > > else [[likely]] {}
> > > > ```
> > > > This diagnostic only happens for an if statement, for a switch multiple 
> > > > values can be considered likely.
> > > > Do you prefer to have the diagnostic also in the CodeGen?
> > > It looked to me like you'd reached agreement to remove that diagnostic. 
> > > Are you intending to keep it?
> > > 
> > > If so, then I'd suggest you make `getLikelihood` a member of `Stmt` so 
> > > that `CodeGen` and the warning here can both easily call it.
> > @aaron.ballman I thought we wanted to keep this conflict warning, am I 
> > correct?
> > I'll add an extra function to the Stmt to test for a conflict and use that 
> > for the diagnostic in the Sema. This allows me to use `LH_None` for no 
> > attribute or a conflict of attributes in the CodeGen. Then there's no need 
> > for `LH_Conflict` and it can be removed from the enumerate.
> > @aaron.ballman I thought we wanted to keep this conflict warning, am I 
> > correct?
> 
> I want to keep the property that any time the user writes an explicit 
> annotation in their code but we decide to ignore the annotation (for whatever 
> reason), the user gets some sort of diagnostic telling them their 
> expectations may not be met. Because we're ignoring the attributes in the 
> case where they're identical on both branches, I'd like to keep some form of 
> diagnostic.
Good then we're on the same page.


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

https://reviews.llvm.org/D85091

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


[PATCH] D85091: [Sema, CodeGen] Implement [[likely]] and [[unlikely]] in IfStmt

2020-09-04 Thread Mark de Wever via Phabricator via cfe-commits
Mordante updated this revision to Diff 289979.
Mordante marked an inline comment as done.
Mordante added a comment.

Addresses review comments, mainly:

- Improving the documentation
- Removing the AST bits since they're no longer required


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

https://reviews.llvm.org/D85091

Files:
  clang/include/clang/AST/Stmt.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/Stmt.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaStmtAttr.cpp
  clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp
  clang/test/Preprocessor/has_attribute.cpp
  clang/test/Sema/attr-likelihood.c
  clang/test/SemaCXX/attr-likelihood.cpp
  clang/www/cxx_status.html
  llvm/include/llvm/Transforms/Scalar/LowerExpectIntrinsic.h
  llvm/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp

Index: llvm/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp
===
--- llvm/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp
+++ llvm/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp
@@ -24,7 +24,6 @@
 #include "llvm/IR/Metadata.h"
 #include "llvm/InitializePasses.h"
 #include "llvm/Pass.h"
-#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Transforms/Scalar.h"
 #include "llvm/Transforms/Utils/MisExpect.h"
@@ -48,10 +47,10 @@
 // 'select' instructions. It may be worthwhile to hoist these values to some
 // shared space, so they can be used directly by other passes.
 
-static cl::opt LikelyBranchWeight(
+cl::opt llvm::LikelyBranchWeight(
 "likely-branch-weight", cl::Hidden, cl::init(2000),
 cl::desc("Weight of the branch likely to be taken (default = 2000)"));
-static cl::opt UnlikelyBranchWeight(
+cl::opt llvm::UnlikelyBranchWeight(
 "unlikely-branch-weight", cl::Hidden, cl::init(1),
 cl::desc("Weight of the branch unlikely to be taken (default = 1)"));
 
Index: llvm/include/llvm/Transforms/Scalar/LowerExpectIntrinsic.h
===
--- llvm/include/llvm/Transforms/Scalar/LowerExpectIntrinsic.h
+++ llvm/include/llvm/Transforms/Scalar/LowerExpectIntrinsic.h
@@ -17,6 +17,7 @@
 
 #include "llvm/IR/Function.h"
 #include "llvm/IR/PassManager.h"
+#include "llvm/Support/CommandLine.h"
 
 namespace llvm {
 
@@ -31,6 +32,8 @@
   PreservedAnalyses run(Function &F, FunctionAnalysisManager &);
 };
 
+extern cl::opt LikelyBranchWeight;
+extern cl::opt UnlikelyBranchWeight;
 }
 
 #endif
Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -987,7 +987,7 @@
 
   [[likely]] and [[unlikely]] attributes
   https://wg21.link/p0479r5";>P0479R5
-  No
+  Clang 12 (partial)
 
 
   typename optional in more contexts
Index: clang/test/SemaCXX/attr-likelihood.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/attr-likelihood.cpp
@@ -0,0 +1,132 @@
+// RUN: %clang_cc1 %s -fsyntax-only -verify
+// RUN: %clang_cc1 %s -DPEDANTIC -pedantic -fsyntax-only -verify
+
+#if PEDANTIC
+void g() {
+  if (true)
+[[likely]] {} // expected-warning {{use of the 'likely' attribute is a C++20 extension}}
+  else
+[[unlikely]] {} // expected-warning {{use of the 'unlikely' attribute is a C++20 extension}}
+}
+#else
+void a() {
+  if (true)
+[[likely]]; // expected-warning {{conflicting attributes 'likely' are ignored}}
+  else
+[[likely]]; // expected-note {{conflicting attribute is here}}
+}
+
+void b() {
+  if (true)
+[[unlikely]]; // expected-warning {{conflicting attributes 'unlikely' are ignored}}
+  else
+[[unlikely]]; // expected-note {{conflicting attribute is here}}
+}
+
+void c() {
+  if (true)
+[[likely]];
+}
+
+void d() {
+  if (true)
+[[unlikely]];
+}
+
+void g() {
+  if (true)
+[[likely]] {}
+  else
+[[unlikely]] {}
+}
+
+void h() {
+  if (true)
+[[likely]] {}
+  else {
+  }
+}
+
+void i() {
+  if (true)
+[[unlikely]] {}
+  else {
+  }
+}
+
+void j() {
+  if (true) {
+  } else
+[[likely]] {}
+}
+
+void k() {
+  if (true) {
+  } else
+[[likely]] {}
+}
+
+void l() {
+  if (true)
+[[likely]] {}
+  else
+[[unlikely]] if (false) [[likely]] {}
+}
+
+void m() {
+  [[likely]] int x = 42; // expected-error {{'likely' attribute cannot be applied to a declaration}}
+
+  if (x)
+[[unlikely]] {}
+  if (x) {
+[[unlikely]];
+  }
+  switch (x) {
+  case 1:
+[[likely]] {}
+break;
+[[likely]] case 2 : case 3 : {}
+break;
+  }
+
+  do {
+[[unlikely]];
+  } while (x);
+  do
+[[unlikely]] {}
+  while (x);
+  do { // expected-note {{to match this 'do'}}
+  }
+  [

[PATCH] D86782: [clang-format] Allow configuring list of macros that map to attributes

2020-09-04 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson updated this revision to Diff 289980.
arichardson added a comment.

fix configuration parsing test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86782

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8040,7 +8040,20 @@
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  FormatStyle CustomQualifier = getLLVMStyle();
+  // Add indentifers that should not be parsed as a qualifier by default.
+  CustomQualifier.AttributeMacros.push_back("__my_qualifier");
+  CustomQualifier.AttributeMacros.push_back("_My_qualifier");
+  CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
+  verifyFormat("vector parse_as_multiply;");
+  verifyFormat("vector v;", CustomQualifier);
+  verifyFormat("vector parse_as_multiply;");
+  verifyFormat("vector v;", CustomQualifier);
+  verifyFormat("vector parse_as_multiply;");
+  verifyFormat("vector v;", CustomQualifier);
   verifyFormat("vector v;");
+  verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("foo();");
   verifyFormat("foo();");
@@ -8084,10 +8097,23 @@
   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
+  verifyIndependentOfContext("MACRO(A *__capability);");
+  verifyIndependentOfContext("MACRO(A &__capability);");
+  verifyFormat("MACRO(A *__my_qualifier);");   // type declaration
+  verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
+  // If we add __my_qualifier to AttributeMacros it should always be parsed as
+  // a type declaration:
+  verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
+  verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
+
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   // FIXME: Is there a way to make this work?
   // verifyIndependentOfContext("MACRO(A *a);");
+  verifyFormat("MACRO(A &B);");
+  verifyFormat("MACRO(A *B);");
+  verifyFormat("void f() { MACRO(A * B); }");
+  verifyFormat("void f() { MACRO(A & B); }");
 
   verifyFormat("DatumHandle const *operator->() const { return input_; }");
   verifyFormat("return options != nullptr && operator==(*options);");
@@ -8137,10 +8163,47 @@
   verifyFormat("a __attribute__((unused))\n"
"aaa(int i);");
   FormatStyle AfterType = getLLVMStyle();
-  AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
+  AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
   verifyFormat("__attribute__((nodebug)) void\n"
"foo() {}\n",
AfterType);
+  verifyFormat("__unused void\n"
+   "foo() {}",
+   AfterType);
+
+  FormatStyle CustomAttrs = getLLVMStyle();
+  CustomAttrs.AttributeMacros.push_back("__unused");
+  CustomAttrs.AttributeMacros.push_back("__attr1");
+  CustomAttrs.AttributeMacros.push_back("__attr2");
+  CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  // Check that it is parsed as a multiplication without AttributeMacros and
+  // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+
+  // Check that these are not parsed as function declarations:
+  CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
+  CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
+  verifyFormat("SomeType s(InitValue);", CustomAttrs);
+  verifyFormat("SomeType s{InitValue};", CustomAttrs);
+  verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
+  verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
+  verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
+  verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
+  verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
+  verifyFormat("SomeType *__capa

[PATCH] D76590: [Analyzer] Model `empty()` member function of containers

2020-09-04 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware updated this revision to Diff 289981.
baloghadamsoftware added a comment.

`isIterator()` updated because it did not work perfectly with the refactored 
`handleBegin()` after rebase. (Why did it work before the rebase?) The problem 
was that it only looked for the necessary operators in the actual class but not 
in its bases.


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

https://reviews.llvm.org/D76590

Files:
  clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/InvalidatedIteratorChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
  clang/lib/StaticAnalyzer/Checkers/Iterator.h
  clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/STLAlgorithmModeling.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/container-modeling.cpp
  clang/test/Analysis/diagnostics/explicit-suppression.cpp
  clang/test/Analysis/iterator-modeling.cpp
  clang/test/Analysis/smart-ptr-text-output.cpp
  clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp

Index: clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
===
--- clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
+++ clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp
@@ -51,22 +51,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/test/Analysis/smart-ptr-text-output.cpp
===
--- clang/test/Analysis/smart-ptr-text-output.cpp
+++ clang/test/Analysis/smart-ptr-text-output.cpp
@@ -80,7 +80,7 @@
 void derefOnStdSwappedNullPtr() {
   std::unique_ptr P; // expected-note {{Default constructed smart pointer 'P' is null}}
   std::unique_ptr PNull; // expected-note {{Default constructed smart pointer 'PNull' is null}}
-  std::swap(P, PNull); // expected-note@Inputs/system-header-simulator-cxx.h:979 {{Swapped null smart pointer 'PNull' with smart pointer 'P'}}
+  std::swap(P, PNull); // expected-note@Inputs/system-header-simulator-cxx.h:987 {{Swapped null smart pointer 'PNull' with smart pointer 'P'}}
   // expected-note@-1 {{Calling 'swap'}}
   // expected-note@-2 {{Returning from 'swap'}}
   P->foo(); // expected-warning {{Dereference of null smart pointer 'P' [alpha.cplusplus.SmartPtr]}}
Index: clang/test/Analysis/iterator-modeling.cpp
===
--- clang/test/Analysis/iterator-modeling.cpp
+++ clang/test/Analysis/iterator-modeling.cpp
@@ -2026,6 +2026,55 @@
 ++i0;
 }
 
+template 
+struct delegated_ctor_iterator {
+  delegated_ctor_iterator(const T&, int);
+  delegated_ctor_iterator(const T& t) : delegated_ctor_iterator(t, 0) {}
+  delegated_ctor_iterator operator++();
+  delegated_ctor_iterator operator++(int);
+  T& operator*();
+};
+
+template 
+struct container_with_delegated_ctor_iterator {
+  typedef delegated_ctor_iterator iterator;
+  iterator begin() const { return delegated_ctor_iterator(T()); }
+};

[PATCH] D84248: [analyzer][StdLibraryFunctionsChecker] Add POSIX time handling functions

2020-09-04 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 289982.
martong added a comment.

- Rebase to master, ie using optionals everywhere


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84248

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-POSIX.c
  clang/test/Analysis/std-c-library-functions-arg-constraints.c

Index: clang/test/Analysis/std-c-library-functions-arg-constraints.c
===
--- clang/test/Analysis/std-c-library-functions-arg-constraints.c
+++ clang/test/Analysis/std-c-library-functions-arg-constraints.c
@@ -256,6 +256,7 @@
   // bugpath-note{{TRUE}} \
   // bugpath-note{{'s' is <= 2}}
 }
+
 int __buf_size_arg_constraint_mul(const void *, size_t, size_t);
 void test_buf_size_concrete_with_multiplication() {
   short buf[3]; // bugpath-note{{'buf' initialized here}}
@@ -280,3 +281,13 @@
   // bugpath-warning{{TRUE}} \
   // bugpath-note{{TRUE}}
 }
+
+// The minimum buffer size for this function is set to 10.
+int __buf_size_arg_constraint_concrete(const void *);
+void test_min_buf_size() {
+  char buf[9];// bugpath-note{{'buf' initialized here}}
+  __buf_size_arg_constraint_concrete(buf); // \
+  // report-warning{{Function argument constraint is not satisfied}} \
+  // bugpath-warning{{Function argument constraint is not satisfied}} \
+  // bugpath-note{{Function argument constraint is not satisfied}}
+}
Index: clang/test/Analysis/std-c-library-functions-POSIX.c
===
--- clang/test/Analysis/std-c-library-functions-POSIX.c
+++ clang/test/Analysis/std-c-library-functions-POSIX.c
@@ -95,6 +95,19 @@
 // CHECK: Loaded summary for: ssize_t send(int sockfd, const void *buf, size_t len, int flags)
 // CHECK: Loaded summary for: int socketpair(int domain, int type, int protocol, int sv[2])
 // CHECK: Loaded summary for: int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen, char *restrict node, socklen_t nodelen, char *restrict service, socklen_t servicelen, int flags)
+// CHECK: Loaded summary for: int utime(const char *filename, struct utimbuf *buf)
+// CHECK: Loaded summary for: int futimens(int fd, const struct timespec times[2])
+// CHECK: Loaded summary for: int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags)
+// CHECK: Loaded summary for: int utimes(const char *filename, const struct timeval times[2])
+// CHECK: Loaded summary for: int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
+// CHECK: Loaded summary for: struct tm *localtime(const time_t *tp)
+// CHECK: Loaded summary for: struct tm *localtime_r(const time_t *restrict timer, struct tm *restrict result)
+// CHECK: Loaded summary for: char *asctime_r(const struct tm *restrict tm, char *restrict buf)
+// CHECK: Loaded summary for: char *ctime_r(const time_t *timep, char *buf)
+// CHECK: Loaded summary for: struct tm *gmtime_r(const time_t *restrict timer, struct tm *restrict result)
+// CHECK: Loaded summary for: struct tm *gmtime(const time_t *tp)
+// CHECK: Loaded summary for: int clock_gettime(clockid_t clock_id, struct timespec *tp)
+// CHECK: Loaded summary for: int getitimer(int which, struct itimerval *curr_value)
 
 long a64l(const char *str64);
 char *l64a(long value);
@@ -226,6 +239,25 @@
 ssize_t send(int sockfd, const void *buf, size_t len, int flags);
 int socketpair(int domain, int type, int protocol, int sv[2]);
 int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen, char *restrict node, socklen_t nodelen, char *restrict service, socklen_t servicelen, int flags);
+struct utimbuf;
+struct timespec { int x; };
+struct timeval { int x; };
+int utime(const char *filename, struct utimbuf *buf);
+int futimens(int fd, const struct timespec times[2]);
+int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags);
+int utimes(const char *filename, const struct timeval times[2]);
+int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
+typedef unsigned long time_t;
+struct tm *localtime(const time_t *tp);
+struct tm *localtime_r(const time_t *restrict timer, struct tm *restrict result);
+char *asctime_r(const struct tm *restrict tm, char *restrict buf);
+char *ctime_r(const time_t *timep, char *buf);
+struct tm *gmtime_r(const time_t *restrict timer, struct tm *restrict result);
+struct tm *gmtime(const time_t *tp);
+typedef unsigned long clockid_t;
+int clock_gettime(clockid_t clock_id, struct timespec *tp);
+struct itimerval;
+int getitimer(int which, struct itimerval *curr_value);
 
 // Must have at least one call expression to initialize the summary map.
 int bar(void);
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- cl

[PATCH] D84248: [analyzer][StdLibraryFunctionsChecker] Add POSIX time handling functions

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

In D84248#2215519 , @Szelethus wrote:

> Lets make sure we invite the wider community to see whats going on. 
> Otherwise, LGTM!

I am committing this because it already has two accepts, plus I am //very// 
confident with the changes. 
@NoQ @vsavchenko Let me know if you find anything, I am happy to fix 
post-commit or we can even revert.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84248

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


[PATCH] D87143: Check whether Gentoo-specific configuration directory exists

2020-09-04 Thread Manoj Gupta via Phabricator via cfe-commits
manojgupta added a reviewer: mgorny.
manojgupta added inline comments.



Comment at: clang/lib/Driver/ToolChains/Gnu.cpp:2537-2538
 const SmallVectorImpl &CandidateBiarchTriples) {
+  if (!D.getVFS().exists(GentooConfigDir))
+return false;
+

I think it should be D.SysRoot + GentooConfigDir. Otherwise, there is no way to 
test a Gentoo configuration tests on a non-Gentoo machine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87143

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


[clang] baf3c77 - [libclang] Add translateCXRangeToCharRange conversion

2020-09-04 Thread Jan Korous via cfe-commits

Author: Jan Korous
Date: 2020-09-04T09:41:22-07:00
New Revision: baf3c77bd9f6baf60a09ef3625fef84080642b72

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

LOG: [libclang] Add translateCXRangeToCharRange conversion

Add new conversion with clearly specified semantics.

https://reviews.llvm.org/D86990

Added: 


Modified: 
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/CXSourceLocation.h

Removed: 




diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 93f9797a965e..683b517d79fd 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -164,6 +164,12 @@ CXSourceRange cxloc::translateSourceRange(const 
SourceManager &SM,
   return Result;
 }
 
+CharSourceRange cxloc::translateCXRangeToCharRange(CXSourceRange R) {
+  return CharSourceRange::getCharRange(
+  SourceLocation::getFromRawEncoding(R.begin_int_data),
+  SourceLocation::getFromRawEncoding(R.end_int_data));
+}
+
 
//===--===//
 // Cursor visitor.
 
//===--===//

diff  --git a/clang/tools/libclang/CXSourceLocation.h 
b/clang/tools/libclang/CXSourceLocation.h
index 6702d0cf9791..ce3d09e1c9eb 100644
--- a/clang/tools/libclang/CXSourceLocation.h
+++ b/clang/tools/libclang/CXSourceLocation.h
@@ -71,7 +71,11 @@ static inline SourceRange 
translateCXSourceRange(CXSourceRange R) {
  SourceLocation::getFromRawEncoding(R.end_int_data));
 }
 
-
+/// Translates CXSourceRange to CharSourceRange.
+/// The semantics of \p R are:
+/// R.begin_int_data is first character of the range.
+/// R.end_int_data is one character past the end of the range.
+CharSourceRange translateCXRangeToCharRange(CXSourceRange R);
 }} // end namespace: clang::cxloc
 
 #endif



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


[PATCH] D77491: [Sema] Introduce BuiltinAttr, per-declaration builtin-ness

2020-09-04 Thread Raul Tambre via Phabricator via cfe-commits
tambre updated this revision to Diff 289986.
tambre added a comment.

Improve comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77491

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/IdentifierTable.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/Headers/intrin.h
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/AST/ast-dump-attr.cpp
  clang/test/CodeGen/builtin-redeclaration.c
  clang/test/CodeGen/callback_pthread_create.c
  clang/test/Sema/implicit-builtin-decl.c
  clang/test/Sema/warn-fortify-source.c
  clang/test/SemaCXX/cxx11-compat.cpp
  clang/test/SemaCXX/warn-unused-local-typedef.cpp

Index: clang/test/SemaCXX/warn-unused-local-typedef.cpp
===
--- clang/test/SemaCXX/warn-unused-local-typedef.cpp
+++ clang/test/SemaCXX/warn-unused-local-typedef.cpp
@@ -67,10 +67,10 @@
 
 void test() {
   typedef signed long int superint; // no diag
-  printf("%f", (superint) 42);
+  printf("%ld", (superint)42);
 
   typedef signed long int superint2; // no diag
-  printf("%f", static_cast(42));
+  printf("%ld", static_cast(42));
 
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wunused-local-typedef"
Index: clang/test/SemaCXX/cxx11-compat.cpp
===
--- clang/test/SemaCXX/cxx11-compat.cpp
+++ clang/test/SemaCXX/cxx11-compat.cpp
@@ -31,7 +31,7 @@
 s = { n }, // expected-warning {{non-constant-expression cannot be narrowed from type 'int' to 'char' in initializer list in C++11}} expected-note {{explicit cast}}
 t = { 1234 }; // expected-warning {{constant expression evaluates to 1234 which cannot be narrowed to type 'char' in C++11}} expected-warning {{changes value}} expected-note {{explicit cast}}
 
-#define PRIuS "uS"
+#define PRIuS "zu"
 int printf(const char *, ...);
 typedef __typeof(sizeof(int)) size_t;
 void h(size_t foo, size_t bar) {
Index: clang/test/Sema/warn-fortify-source.c
===
--- clang/test/Sema/warn-fortify-source.c
+++ clang/test/Sema/warn-fortify-source.c
@@ -1,8 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 
 typedef unsigned long size_t;
@@ -13,13 +11,7 @@
 
 extern int sprintf(char *str, const char *format, ...);
 
-#if defined(USE_PASS_OBJECT_SIZE)
-void *memcpy(void *dst, const void *src, size_t c);
-static void *memcpy(void *dst __attribute__((pass_object_size(1))), const void *src, size_t c) __attribute__((overloadable)) __asm__("merp");
-static void *memcpy(void *const dst __attribute__((pass_object_size(1))), const void *src, size_t c) __attribute__((overloadable)) {
-  return 0;
-}
-#elif defined(USE_BUILTINS)
+#if defined(USE_BUILTINS)
 #define memcpy(x,y,z) __builtin_memcpy(x,y,z)
 #else
 void *memcpy(void *dst, const void *src, size_t c);
@@ -45,14 +37,7 @@
   };
   struct pair p;
   char buf[20];
-  memcpy(&p.first, buf, 20);
-#ifdef USE_PASS_OBJECT_SIZE
-  // Use the more strict checking mode on the pass_object_size attribute:
-  // expected-warning@-3 {{memcpy' will always overflow; destination buffer has size 4, but size argument is 20}}
-#else
-  // Or just fallback to type 0:
-  // expected-warning@-6 {{memcpy' will always overflow; destination buffer has size 8, but size argument is 20}}
-#endif
+  memcpy(&p.first, buf, 20); // expected-warning {{memcpy' will always overflow; destination buffer has size 8, but size argument is 20}}
 }
 
 void call_strncat() {
Index: clang/test/Sema/implicit-builtin-decl.c
===
--- clang/test/Sema/implicit-builtin-decl.c
+++ clang/test/Sema/implicit-builtin-decl.c
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-// RUN: not %clang_cc1 -fsyntax-only -ast-dump %s | FileCheck %s
 
 void f() {
   int *ptr = malloc(sizeof(int) * 10); // expected-warning{{implicitly declaring library function 'malloc' with type}} \
@@ -63,9 +62,5 @@
 struct __jmp_buf_tag {};
 void sigsetjmp(struct __jmp_buf_tag[1], int); // expected-warning{{declaration of built-in function 'sigsetjmp' requires the declaration of the 'jmp_buf' type, commonly provided in the header .}}
 
-// CHECK: FunctionDecl {{.*}}  col:6 sigsetjmp '
-// CHECK-NOT

[PATCH] D77491: [Sema] Introduce BuiltinAttr, per-declaration builtin-ness

2020-09-04 Thread Raul Tambre via Phabricator via cfe-commits
tambre added a comment.

In D77491#2254967 , @rjmccall wrote:

> I didn't see the specific example, sorry.  I agree that my description is 
> more applicable to builtins in the `__builtin` namespace, which describes 
> most of the builtins with custom typechecking.  Is the problem just 
> `__va_start`?

I grepped for all builtins with custom typechecking.
I found two occurences in MSVC's headers: `__va_start` and 
`__GetExceptionInfo`, but none on my Debian Unstable machine.

> If we have to treat all declarations as builtins for the custom-typechecking 
> builtins just to land this patch, I don't think that's the worst result in 
> the world, and we can incrementally go from there.  `__va_start` actually has 
> a signature, it just effectively has optional arguments, which is something 
> we could definitely teach the builtins database and signature-matcher about.

I'd still prefer we go incrementally.

It would be nice to receive another round of code review after having fixed the 
issues pointed out by Richard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77491

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


[clang] f0b9dbc - [analyzer][StdLibraryFunctionsChecker] Add POSIX time handling functions

2020-09-04 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-09-04T18:44:12+02:00
New Revision: f0b9dbcfc7ba2a217cab3217d6217fc270c88b58

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

LOG: [analyzer][StdLibraryFunctionsChecker] Add POSIX time handling functions

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/test/Analysis/std-c-library-functions-POSIX.c
clang/test/Analysis/std-c-library-functions-arg-constraints.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 2c20422a9cc4..ddde629f44a5 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -249,15 +249,21 @@ class StdLibraryFunctionsChecker
 }
   };
 
-  // Represents a buffer argument with an additional size argument.
-  // E.g. the first two arguments here:
+  // Represents a buffer argument with an additional size constraint. The
+  // constraint may be a concrete value, or a symbolic value in an argument.
+  // Example 1. Concrete value as the minimum buffer size.
+  //   char *asctime_r(const struct tm *restrict tm, char *restrict buf);
+  //   // `buf` size must be at least 26 bytes according the POSIX standard.
+  // Example 2. Argument as a buffer size.
   //   ctime_s(char *buffer, rsize_t bufsz, const time_t *time);
-  // Another example:
+  // Example 3. The size is computed as a multiplication of other args.
   //   size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
   //   // Here, ptr is the buffer, and its minimum size is `size * nmemb`.
   class BufferSizeConstraint : public ValueConstraint {
+// The concrete value which is the minimum size for the buffer.
+llvm::Optional ConcreteSize;
 // The argument which holds the size of the buffer.
-ArgNo SizeArgN;
+llvm::Optional SizeArgN;
 // The argument which is a multiplier to size. This is set in case of
 // `fread` like functions where the size is computed as a multiplication of
 // two arguments.
@@ -266,9 +272,10 @@ class StdLibraryFunctionsChecker
 BinaryOperator::Opcode Op = BO_LE;
 
   public:
+BufferSizeConstraint(ArgNo Buffer, llvm::APSInt BufMinSize)
+: ValueConstraint(Buffer), ConcreteSize(BufMinSize) {}
 BufferSizeConstraint(ArgNo Buffer, ArgNo BufSize)
 : ValueConstraint(Buffer), SizeArgN(BufSize) {}
-
 BufferSizeConstraint(ArgNo Buffer, ArgNo BufSize, ArgNo BufSizeMultiplier)
 : ValueConstraint(Buffer), SizeArgN(BufSize),
   SizeMultiplierArgN(BufSizeMultiplier) {}
@@ -279,14 +286,27 @@ class StdLibraryFunctionsChecker
   SValBuilder &SvalBuilder = C.getSValBuilder();
   // The buffer argument.
   SVal BufV = getArgSVal(Call, getArgNo());
-  // The size argument.
-  SVal SizeV = getArgSVal(Call, SizeArgN);
-  // Multiply with another argument if given.
-  if (SizeMultiplierArgN) {
-SVal SizeMulV = getArgSVal(Call, *SizeMultiplierArgN);
-SizeV = SvalBuilder.evalBinOp(State, BO_Mul, SizeV, SizeMulV,
-  Summary.getArgType(SizeArgN));
-  }
+
+  // Get the size constraint.
+  const SVal SizeV = [this, &State, &Call, &Summary, &SvalBuilder]() {
+if (ConcreteSize) {
+  return SVal(SvalBuilder.makeIntVal(*ConcreteSize));
+} else if (SizeArgN) {
+  // The size argument.
+  SVal SizeV = getArgSVal(Call, *SizeArgN);
+  // Multiply with another argument if given.
+  if (SizeMultiplierArgN) {
+SVal SizeMulV = getArgSVal(Call, *SizeMultiplierArgN);
+SizeV = SvalBuilder.evalBinOp(State, BO_Mul, SizeV, SizeMulV,
+  Summary.getArgType(*SizeArgN));
+  }
+  return SizeV;
+} else {
+  llvm_unreachable("The constraint must be either a concrete value or "
+   "encoded in an arguement.");
+}
+  }();
+
   // The dynamic size of the buffer argument, got from the analyzer engine.
   SVal BufDynSize = getDynamicSizeWithOffset(State, BufV);
 
@@ -2036,6 +2056,132 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 BufferSize(/*Buffer=*/ArgNo(4), /*BufSize=*/ArgNo(5)))
 .ArgConstraint(
 ArgumentCondition(5, WithinRange, Range(0, Socklen_tMax;
+
+Optional StructUtimbufTy = lookupTy("utimbuf");
+Optional StructUtimbufPtrTy = getPointerTy(StructUtimbufTy);
+
+// int utime(const char *filename, struct utimbuf *buf);
+addToFunctionSummaryMap

[PATCH] D84248: [analyzer][StdLibraryFunctionsChecker] Add POSIX time handling functions

2020-09-04 Thread Gabor Marton 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 rGf0b9dbcfc7ba: [analyzer][StdLibraryFunctionsChecker] Add 
POSIX time handling functions (authored by martong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84248

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-POSIX.c
  clang/test/Analysis/std-c-library-functions-arg-constraints.c

Index: clang/test/Analysis/std-c-library-functions-arg-constraints.c
===
--- clang/test/Analysis/std-c-library-functions-arg-constraints.c
+++ clang/test/Analysis/std-c-library-functions-arg-constraints.c
@@ -256,6 +256,7 @@
   // bugpath-note{{TRUE}} \
   // bugpath-note{{'s' is <= 2}}
 }
+
 int __buf_size_arg_constraint_mul(const void *, size_t, size_t);
 void test_buf_size_concrete_with_multiplication() {
   short buf[3]; // bugpath-note{{'buf' initialized here}}
@@ -280,3 +281,13 @@
   // bugpath-warning{{TRUE}} \
   // bugpath-note{{TRUE}}
 }
+
+// The minimum buffer size for this function is set to 10.
+int __buf_size_arg_constraint_concrete(const void *);
+void test_min_buf_size() {
+  char buf[9];// bugpath-note{{'buf' initialized here}}
+  __buf_size_arg_constraint_concrete(buf); // \
+  // report-warning{{Function argument constraint is not satisfied}} \
+  // bugpath-warning{{Function argument constraint is not satisfied}} \
+  // bugpath-note{{Function argument constraint is not satisfied}}
+}
Index: clang/test/Analysis/std-c-library-functions-POSIX.c
===
--- clang/test/Analysis/std-c-library-functions-POSIX.c
+++ clang/test/Analysis/std-c-library-functions-POSIX.c
@@ -95,6 +95,19 @@
 // CHECK: Loaded summary for: ssize_t send(int sockfd, const void *buf, size_t len, int flags)
 // CHECK: Loaded summary for: int socketpair(int domain, int type, int protocol, int sv[2])
 // CHECK: Loaded summary for: int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen, char *restrict node, socklen_t nodelen, char *restrict service, socklen_t servicelen, int flags)
+// CHECK: Loaded summary for: int utime(const char *filename, struct utimbuf *buf)
+// CHECK: Loaded summary for: int futimens(int fd, const struct timespec times[2])
+// CHECK: Loaded summary for: int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags)
+// CHECK: Loaded summary for: int utimes(const char *filename, const struct timeval times[2])
+// CHECK: Loaded summary for: int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
+// CHECK: Loaded summary for: struct tm *localtime(const time_t *tp)
+// CHECK: Loaded summary for: struct tm *localtime_r(const time_t *restrict timer, struct tm *restrict result)
+// CHECK: Loaded summary for: char *asctime_r(const struct tm *restrict tm, char *restrict buf)
+// CHECK: Loaded summary for: char *ctime_r(const time_t *timep, char *buf)
+// CHECK: Loaded summary for: struct tm *gmtime_r(const time_t *restrict timer, struct tm *restrict result)
+// CHECK: Loaded summary for: struct tm *gmtime(const time_t *tp)
+// CHECK: Loaded summary for: int clock_gettime(clockid_t clock_id, struct timespec *tp)
+// CHECK: Loaded summary for: int getitimer(int which, struct itimerval *curr_value)
 
 long a64l(const char *str64);
 char *l64a(long value);
@@ -226,6 +239,25 @@
 ssize_t send(int sockfd, const void *buf, size_t len, int flags);
 int socketpair(int domain, int type, int protocol, int sv[2]);
 int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen, char *restrict node, socklen_t nodelen, char *restrict service, socklen_t servicelen, int flags);
+struct utimbuf;
+struct timespec { int x; };
+struct timeval { int x; };
+int utime(const char *filename, struct utimbuf *buf);
+int futimens(int fd, const struct timespec times[2]);
+int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags);
+int utimes(const char *filename, const struct timeval times[2]);
+int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
+typedef unsigned long time_t;
+struct tm *localtime(const time_t *tp);
+struct tm *localtime_r(const time_t *restrict timer, struct tm *restrict result);
+char *asctime_r(const struct tm *restrict tm, char *restrict buf);
+char *ctime_r(const time_t *timep, char *buf);
+struct tm *gmtime_r(const time_t *restrict timer, struct tm *restrict result);
+struct tm *gmtime(const time_t *tp);
+typedef unsigned long clockid_t;
+int clock_gettime(clockid_t clock_id, struct timespec *tp);
+struct itimerval;
+int getitimer(int which, struct itimerval *curr_value);
 
 // Must have at least one call expression to initialize the summary map.
 int bar(void);
Index: cl

[PATCH] D87143: Check whether Gentoo-specific configuration directory exists

2020-09-04 Thread Michał Górny via Phabricator via cfe-commits
mgorny added inline comments.



Comment at: clang/lib/Driver/ToolChains/Gnu.cpp:2537-2538
 const SmallVectorImpl &CandidateBiarchTriples) {
+  if (!D.getVFS().exists(GentooConfigDir))
+return false;
+

manojgupta wrote:
> I think it should be D.SysRoot + GentooConfigDir. Otherwise, there is no way 
> to test a Gentoo configuration tests on a non-Gentoo machine.
Probably correct, given that D.SysRoot is used below. However, this code is a 
bit above my pay grade and I was never sure whether it's doing right what it's 
supposed to do. I would really prefer if someone higher up reviewed this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87143

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


[PATCH] D86950: [clang-format] Check that */& after typename macros are pointers/references

2020-09-04 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay 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/D86950/new/

https://reviews.llvm.org/D86950

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


[PATCH] D87007: [clang-format] Correctly parse function declarations with TypenameMacros

2020-09-04 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay 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/D87007/new/

https://reviews.llvm.org/D87007

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


[PATCH] D87006: [clang-format][NFC] Store FormatToken::Type as an enum instead of bitfield

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

Assuming it builds with minimum required c++ compiler


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87006

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


[PATCH] D86782: [clang-format] Allow configuring list of macros that map to attributes

2020-09-04 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.

LGTM, I think we need something like this for those keywords/macros


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86782

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


[PATCH] D86930: [clang-format] Handle typename macros inside cast expressions

2020-09-04 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay 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/D86930/new/

https://reviews.llvm.org/D86930

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


[clang] 64bb582 - Fix the type of the invoke function in the block ABI documentation

2020-09-04 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2020-09-04T10:29:09-07:00
New Revision: 64bb582f4a07d7195a6e6a44a34d166a06f0f071

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

LOG: Fix the type of the invoke function in the block ABI documentation

rdar://problem/67892794

Added: 


Modified: 
clang/docs/Block-ABI-Apple.rst

Removed: 




diff  --git a/clang/docs/Block-ABI-Apple.rst b/clang/docs/Block-ABI-Apple.rst
index d038cdfe9bd2..e21a8b68b5cd 100644
--- a/clang/docs/Block-ABI-Apple.rst
+++ b/clang/docs/Block-ABI-Apple.rst
@@ -35,7 +35,8 @@ High Level
 ==
 
 The ABI of ``Blocks`` consist of their layout and the runtime functions 
required
-by the compiler.  A ``Block`` consists of a structure of the following form:
+by the compiler.  A ``Block`` of type ``R (^)(P...)`` consists of a structure 
of
+the following form:
 
 .. code-block:: c
 
@@ -43,7 +44,7 @@ by the compiler.  A ``Block`` consists of a structure of the 
following form:
 void *isa; // initialized to &_NSConcreteStackBlock or 
&_NSConcreteGlobalBlock
 int flags;
 int reserved; 
-void (*invoke)(void *, ...);
+R (*invoke)(struct Block_literal_1 *, P...);
 struct Block_descriptor_1 {
 unsigned long int reserved; // NULL
 unsigned long int size; // sizeof(struct Block_literal_1)



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


[clang] 54205f0 - [PowerPC] Allow const pointers for load builtins in altivec.h

2020-09-04 Thread Nemanja Ivanovic via cfe-commits

Author: Nemanja Ivanovic
Date: 2020-09-04T13:56:39-04:00
New Revision: 54205f0bd2377503b818d7f62cc4ed63ef5b1e94

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

LOG: [PowerPC] Allow const pointers for load builtins in altivec.h

The load builtins in altivec.h do not have const in the signature
for the pointer parameter. This prevents using them for loading
from constant pointers. A notable case for such a use is Eigen.

This patch simply adds the missing const.

Fixes: https://bugs.llvm.org/show_bug.cgi?id=47408

Added: 


Modified: 
clang/lib/Headers/altivec.h
clang/test/CodeGen/builtins-ppc-altivec.c
clang/test/CodeGen/builtins-ppc-p10vector.c
clang/test/CodeGen/builtins-ppc-xl-xst.c

Removed: 




diff  --git a/clang/lib/Headers/altivec.h b/clang/lib/Headers/altivec.h
index 47119d702683..9fda383074f6 100644
--- a/clang/lib/Headers/altivec.h
+++ b/clang/lib/Headers/altivec.h
@@ -2702,67 +2702,67 @@ vec_insert_exp(vector unsigned int __a, vector unsigned 
int __b) {
 }
 
 #if defined(__powerpc64__)
-static __inline__ vector signed char __ATTRS_o_ai vec_xl_len(signed char *__a,
+static __inline__ vector signed char __ATTRS_o_ai vec_xl_len(const signed char 
*__a,
  size_t __b) {
   return (vector signed char)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
 static __inline__ vector unsigned char __ATTRS_o_ai
-vec_xl_len(unsigned char *__a, size_t __b) {
+vec_xl_len(const unsigned char *__a, size_t __b) {
   return (vector unsigned char)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
-static __inline__ vector signed short __ATTRS_o_ai vec_xl_len(signed short 
*__a,
+static __inline__ vector signed short __ATTRS_o_ai vec_xl_len(const signed 
short *__a,
   size_t __b) {
   return (vector signed short)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
 static __inline__ vector unsigned short __ATTRS_o_ai
-vec_xl_len(unsigned short *__a, size_t __b) {
+vec_xl_len(const unsigned short *__a, size_t __b) {
   return (vector unsigned short)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
-static __inline__ vector signed int __ATTRS_o_ai vec_xl_len(signed int *__a,
+static __inline__ vector signed int __ATTRS_o_ai vec_xl_len(const signed int 
*__a,
 size_t __b) {
   return (vector signed int)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
-static __inline__ vector unsigned int __ATTRS_o_ai vec_xl_len(unsigned int 
*__a,
+static __inline__ vector unsigned int __ATTRS_o_ai vec_xl_len(const unsigned 
int *__a,
   size_t __b) {
   return (vector unsigned int)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
-static __inline__ vector float __ATTRS_o_ai vec_xl_len(float *__a, size_t __b) 
{
+static __inline__ vector float __ATTRS_o_ai vec_xl_len(const float *__a, 
size_t __b) {
   return (vector float)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
 static __inline__ vector signed __int128 __ATTRS_o_ai
-vec_xl_len(signed __int128 *__a, size_t __b) {
+vec_xl_len(const signed __int128 *__a, size_t __b) {
   return (vector signed __int128)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
 static __inline__ vector unsigned __int128 __ATTRS_o_ai
-vec_xl_len(unsigned __int128 *__a, size_t __b) {
+vec_xl_len(const unsigned __int128 *__a, size_t __b) {
   return (vector unsigned __int128)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
 static __inline__ vector signed long long __ATTRS_o_ai
-vec_xl_len(signed long long *__a, size_t __b) {
+vec_xl_len(const signed long long *__a, size_t __b) {
   return (vector signed long long)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
 static __inline__ vector unsigned long long __ATTRS_o_ai
-vec_xl_len(unsigned long long *__a, size_t __b) {
+vec_xl_len(const unsigned long long *__a, size_t __b) {
   return (vector unsigned long long)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
-static __inline__ vector double __ATTRS_o_ai vec_xl_len(double *__a,
+static __inline__ vector double __ATTRS_o_ai vec_xl_len(const double *__a,
 size_t __b) {
   return (vector double)__builtin_vsx_lxvl(__a, (__b << 56));
 }
 
 static __inline__ vector unsigned char __ATTRS_o_ai
-vec_xl_len_r(unsigned char *__a, size_t __b) {
+vec_xl_len_r(const unsigned char *__a, size_t __b) {
   vector unsigned char __res =
   (vector unsigned char)__builtin_vsx_lxvll(__a, (__b << 56));
 #ifdef __LITTLE_ENDIAN__
@@ -16447,41 +16447,41 @@ typedef vector unsigned int unaligned_vec_uint 
__attribute__((aligned(1)));
 typedef vector float unaligned_vec_float __attribute__((aligned(1)));
 
 static inline __ATTRS_o_ai vector signed char vec_xl(signed long lon

[PATCH] D86841: [clang] Add mayprogress and llvm.loop.mustprogress attribute deduction

2020-09-04 Thread Atmn Patel via Phabricator via cfe-commits
atmnpatel updated this revision to Diff 289997.
atmnpatel added a comment.

Renamed `mayprogress` to `maynotprogress`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86841

Files:
  clang/lib/CodeGen/CGLoopInfo.cpp
  clang/lib/CodeGen/CGLoopInfo.h
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/CodeGen/attr-noprogress.c
  clang/test/CodeGen/attr-noprogress.cpp
  clang/test/CodeGenCXX/fno-unroll-loops-metadata.cpp

Index: clang/test/CodeGenCXX/fno-unroll-loops-metadata.cpp
===
--- clang/test/CodeGenCXX/fno-unroll-loops-metadata.cpp
+++ clang/test/CodeGenCXX/fno-unroll-loops-metadata.cpp
@@ -4,7 +4,7 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s -O3 -disable-llvm-optzns -fno-unroll-loops | FileCheck --check-prefix=UNROLL_DISABLED_MD %s
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s -O3 -disable-llvm-optzns | FileCheck --check-prefix=NO_UNROLL_MD %s
 
-// NO_UNROLL_MD-NOT: llvm.loop
+// NO_UNROLL_MD-NOT: llvm.loop.unroll.disable
 
 // Verify unroll.disable metadata is added to while loop with -fno-unroll-loops
 // and optlevel > 0.
Index: clang/test/CodeGen/attr-noprogress.cpp
===
--- /dev/null
+++ clang/test/CodeGen/attr-noprogress.cpp
@@ -0,0 +1,188 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --check-attributes
+// RUN: %clang_cc1 -S -emit-llvm %s -o - | FileCheck %s
+
+int a = 0;
+int b = 0;
+
+// CHECK: Function Attrs: noinline nounwind optnone maynotprogress
+// CHECK-LABEL: @_Z2f1v(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:br label [[FOR_COND:%.*]]
+// CHECK:   for.cond:
+// CHECK: br i1 true, label [[FOR_BODY:%.*]], label [[FOR_END:%.*]]
+// CHECK:   for.body:
+// CHECK: br label [[FOR_COND]]
+// CHECK:   for.end:
+// CHECK: ret void
+//
+void f1() {
+  for (; 1;) {
+  }
+}
+
+// CHECK: Function Attrs: noinline nounwind optnone
+// CHECK-LABEL: @_Z2f2v(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:br label [[FOR_COND:%.*]]
+// CHECK:   for.cond:
+// CHECK: [[TMP0:%.*]] = load i32, i32* @a, align 4
+// CHECK: [[TMP1:%.*]] = load i32, i32* @b, align 4
+// CHECK: [[CMP:%.*]] = icmp eq i32 [[TMP0]], [[TMP1]]
+// CHECK: br i1 [[CMP]], label [[FOR_BODY:%.*]], label [[FOR_END:%.*]]
+// CHECK:   for.body:
+// CHECK: br label [[FOR_COND]]
+// CHECK:   for.end:
+// CHECK: ret void
+//
+void f2() {
+  for (; a == b;) {
+  }
+}
+
+// CHECK: Function Attrs: noinline nounwind optnone maynotprogress
+// CHECK-LABEL: @_Z1Fv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:br label [[FOR_COND:%.*]]
+// CHECK:   for.cond:
+// CHECK: br i1 true, label [[FOR_BODY:%.*]], label [[FOR_END:%.*]]
+// CHECK:   for.body:
+// CHECK: br label [[FOR_COND]]
+// CHECK:   for.end:
+// CHECK: br label [[FOR_COND1:%.*]]
+// CHECK:   for.cond1:
+// CHECK: [[TMP0:%.*]] = load i32, i32* @a, align 4
+// CHECK: [[TMP1:%.*]] = load i32, i32* @b, align 4
+// CHECK: [[CMP:%.*]] = icmp eq i32 [[TMP0]], [[TMP1]]
+// CHECK: br i1 [[CMP]], label [[FOR_BODY2:%.*]], label [[FOR_END3:%.*]]
+// CHECK:   for.body2:
+// CHECK: br label [[FOR_COND1]], !llvm.loop [[LOOP2:!.*]]
+// CHECK:   for.end3:
+// CHECK: ret void
+//
+void F() {
+  for (; 1;) {
+  }
+  for (; a == b;) {
+  }
+}
+
+// CHECK: Function Attrs: noinline nounwind optnone maynotprogress
+// CHECK-LABEL: @_Z2w1v(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:br label [[WHILE_BODY:%.*]]
+// CHECK:   while.body:
+// CHECK: br label [[WHILE_BODY]]
+//
+void w1() {
+  while (1) {
+  }
+}
+
+// CHECK: Function Attrs: noinline nounwind optnone
+// CHECK-LABEL: @_Z2w2v(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:br label [[WHILE_COND:%.*]]
+// CHECK:   while.cond:
+// CHECK: [[TMP0:%.*]] = load i32, i32* @a, align 4
+// CHECK: [[TMP1:%.*]] = load i32, i32* @b, align 4
+// CHECK: [[CMP:%.*]] = icmp eq i32 [[TMP0]], [[TMP1]]
+// CHECK: br i1 [[CMP]], label [[WHILE_BODY:%.*]], label [[WHILE_END:%.*]]
+// CHECK:   while.body:
+// CHECK: br label [[WHILE_COND]]
+// CHECK:   while.end:
+// CHECK: ret void
+//
+void w2() {
+  while (a == b) {
+  }
+}
+
+// CHECK: Function Attrs: noinline nounwind optnone maynotprogress
+// CHECK-LABEL: @_Z1Wv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:br label [[WHILE_COND:%.*]]
+// CHECK:   while.cond:
+// CHECK: [[TMP0:%.*]] = load i32, i32* @a, align 4
+// CHECK: [[TMP1:%.*]] = load i32, i32* @b, align 4
+// CHECK: [[CMP:%.*]] = icmp eq i32 [[TMP0]], [[TMP1]]
+// CHECK: br i1 [[CMP]], la

[PATCH] D87143: Check whether Gentoo-specific configuration directory exists

2020-09-04 Thread Dmitry Antipov via Phabricator via cfe-commits
dmantipov updated this revision to Diff 289998.
dmantipov added a comment.

Add D.SysRoot as suggested during initial review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87143

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Gnu.h


Index: clang/lib/Driver/ToolChains/Gnu.h
===
--- clang/lib/Driver/ToolChains/Gnu.h
+++ clang/lib/Driver/ToolChains/Gnu.h
@@ -212,6 +212,9 @@
 /// The set of multilibs that the detected installation supports.
 MultilibSet Multilibs;
 
+// Gentoo-specific toolchain configurations are stored here.
+const std::string GentooConfigDir = "/etc/env.d/gcc";
+
   public:
 explicit GCCInstallationDetector(const Driver &D) : IsValid(false), D(D) {}
 void init(const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args,
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2534,6 +2534,9 @@
 const llvm::Triple &TargetTriple, const ArgList &Args,
 const SmallVectorImpl &CandidateTriples,
 const SmallVectorImpl &CandidateBiarchTriples) {
+  if (!D.getVFS().exists(D.SysRoot + GentooConfigDir))
+return false;
+
   for (StringRef CandidateTriple : CandidateTriples) {
 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
   return true;
@@ -2550,8 +2553,8 @@
 const llvm::Triple &TargetTriple, const ArgList &Args,
 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
   llvm::ErrorOr> File =
-  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
-  CandidateTriple.str());
+  D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir +
+  "/config-" + CandidateTriple.str());
   if (File) {
 SmallVector Lines;
 File.get()->getBuffer().split(Lines, "\n");
@@ -2562,8 +2565,8 @@
 continue;
   // Process the config file pointed to by CURRENT.
   llvm::ErrorOr> ConfigFile =
-  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/" +
-  Line.str());
+  D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir +
+  "/" + Line.str());
   std::pair ActiveVersion = Line.rsplit('-');
   // List of paths to scan for libraries.
   SmallVector GentooScanPaths;


Index: clang/lib/Driver/ToolChains/Gnu.h
===
--- clang/lib/Driver/ToolChains/Gnu.h
+++ clang/lib/Driver/ToolChains/Gnu.h
@@ -212,6 +212,9 @@
 /// The set of multilibs that the detected installation supports.
 MultilibSet Multilibs;
 
+// Gentoo-specific toolchain configurations are stored here.
+const std::string GentooConfigDir = "/etc/env.d/gcc";
+
   public:
 explicit GCCInstallationDetector(const Driver &D) : IsValid(false), D(D) {}
 void init(const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args,
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2534,6 +2534,9 @@
 const llvm::Triple &TargetTriple, const ArgList &Args,
 const SmallVectorImpl &CandidateTriples,
 const SmallVectorImpl &CandidateBiarchTriples) {
+  if (!D.getVFS().exists(D.SysRoot + GentooConfigDir))
+return false;
+
   for (StringRef CandidateTriple : CandidateTriples) {
 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
   return true;
@@ -2550,8 +2553,8 @@
 const llvm::Triple &TargetTriple, const ArgList &Args,
 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
   llvm::ErrorOr> File =
-  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
-  CandidateTriple.str());
+  D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir +
+  "/config-" + CandidateTriple.str());
   if (File) {
 SmallVector Lines;
 File.get()->getBuffer().split(Lines, "\n");
@@ -2562,8 +2565,8 @@
 continue;
   // Process the config file pointed to by CURRENT.
   llvm::ErrorOr> ConfigFile =
-  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/" +
-  Line.str());
+  D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir +
+  "/" + Line.str());
   std::pair ActiveVersion = Line.rsplit('-');
   // List of paths to scan for libraries.
   SmallVector GentooScanPaths;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87143: Check whether Gentoo-specific configuration directory exists

2020-09-04 Thread Manoj Gupta via Phabricator via cfe-commits
manojgupta accepted this revision.
manojgupta added a comment.
This revision is now accepted and ready to land.

Looks ok to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87143

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


Re: [clang] e6393ee - Canonicalize declaration pointers when forming APValues.

2020-09-04 Thread Richard Smith via cfe-commits
Thanks for the revert and the test. I'd imagine that we're forgetting that
we need to ask the most recent declaration whether it's weak -- isWeak()
can (presumably) change along the redecl chain. Fun :)

On Fri, 4 Sep 2020, 07:36 Nico Weber,  wrote:

> Actually in 2a03f270d69cf1079feb029f84727288e217588a
>
> On Fri, Sep 4, 2020 at 10:27 AM Nico Weber  wrote:
>
>> Test added in 85a9f6512a3cff797f1964c36c59d53e97a680c4
>>
>> On Fri, Sep 4, 2020 at 10:14 AM Nico Weber  wrote:
>>
>>> To keep the bots greener over the long weekend, I went ahead and
>>> reverted this for now in 7b0332389afd705f46b02fcf87ec3414b8dece34. I'll add
>>> a test for this.
>>>
>>> On Fri, Sep 4, 2020 at 10:11 AM Nico Weber  wrote:
>>>
 Hi Richard,

 this breaks Wunreachable-code which now ignore "weak" on redeclarations:

 thakis@thakis:~/src/llvm-project$ cat foo.cc
 extern "C" void foo(void);
 extern "C" __attribute__((weak)) decltype(foo) foo;

 void g(), h();
 void f() {
 if (foo)
   return g();
 h();
 }
 thakis@thakis:~/src/llvm-project$ out/gn/bin/clang -Wunreachable-code
 -c foo.cc
 foo.cc:8:5: warning: code will never be executed [-Wunreachable-code]
 h();
 ^

 This seems to be a somewhat common pattern for calling new functions.

 (Chromium bug: https://crbug.com/1125102)

 On Thu, Sep 3, 2020 at 6:35 PM Richard Smith via cfe-commits <
 cfe-commits@lists.llvm.org> wrote:

>
> Author: Richard Smith
> Date: 2020-09-03T15:35:12-07:00
> New Revision: e6393ee813178e9d3306b8e3c6949a4f32f8a2cb
>
> URL:
> https://github.com/llvm/llvm-project/commit/e6393ee813178e9d3306b8e3c6949a4f32f8a2cb
> DIFF:
> https://github.com/llvm/llvm-project/commit/e6393ee813178e9d3306b8e3c6949a4f32f8a2cb.diff
>
> LOG: Canonicalize declaration pointers when forming APValues.
>
> References to different declarations of the same entity aren't
> different
> values, so shouldn't have different representations.
>
> Added:
>
>
> Modified:
> clang/include/clang/AST/APValue.h
> clang/lib/AST/APValue.cpp
> clang/lib/AST/ExprConstant.cpp
> clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p9.cpp
> clang/test/OpenMP/ordered_messages.cpp
>
> Removed:
>
>
>
>
> 
> diff  --git a/clang/include/clang/AST/APValue.h
> b/clang/include/clang/AST/APValue.h
> index 87e4bd7f84c1..485e6c2602cf 100644
> --- a/clang/include/clang/AST/APValue.h
> +++ b/clang/include/clang/AST/APValue.h
> @@ -174,6 +174,7 @@ class APValue {
>return !(LHS == RHS);
>  }
>  friend llvm::hash_code hash_value(const LValueBase &Base);
> +friend struct llvm::DenseMapInfo;
>
>private:
>  PtrTy Ptr;
> @@ -201,8 +202,7 @@ class APValue {
>
>public:
>  LValuePathEntry() : Value() {}
> -LValuePathEntry(BaseOrMemberType BaseOrMember)
> -:
> Value{reinterpret_cast(BaseOrMember.getOpaqueValue())} {}
> +LValuePathEntry(BaseOrMemberType BaseOrMember);
>  static LValuePathEntry ArrayIndex(uint64_t Index) {
>LValuePathEntry Result;
>Result.Value = Index;
>
> diff  --git a/clang/lib/AST/APValue.cpp b/clang/lib/AST/APValue.cpp
> index 2a8834b4db0c..7531229654cf 100644
> --- a/clang/lib/AST/APValue.cpp
> +++ b/clang/lib/AST/APValue.cpp
> @@ -38,7 +38,7 @@ static_assert(
>  "Type is insufficiently aligned");
>
>  APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I,
> unsigned V)
> -: Ptr(P), Local{I, V} {}
> +: Ptr(P ? cast(P->getCanonicalDecl()) : nullptr),
> Local{I, V} {}
>  APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
>  : Ptr(P), Local{I, V} {}
>
> @@ -82,13 +82,19 @@ bool operator==(const APValue::LValueBase &LHS,
>  const APValue::LValueBase &RHS) {
>if (LHS.Ptr != RHS.Ptr)
>  return false;
> -  if (LHS.is())
> +  if (LHS.is() || LHS.is())
>  return true;
>return LHS.Local.CallIndex == RHS.Local.CallIndex &&
>   LHS.Local.Version == RHS.Local.Version;
>  }
>  }
>
> +APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType
> BaseOrMember) {
> +  if (const Decl *D = BaseOrMember.getPointer())
> +BaseOrMember.setPointer(D->getCanonicalDecl());
> +  Value = reinterpret_cast(BaseOrMember.getOpaqueValue());
> +}
> +
>  namespace {
>struct LVBase {
>  APValue::LValueBase Base;
> @@ -113,14 +119,16 @@ APValue::LValueBase::operator bool () const {
>
>  clang::APValue::LValueBase
>  llvm::DenseMapInfo::getEmptyKey() {
> -  return clang::APValue:

[PATCH] D86991: [libclang] Expose couple AST details

2020-09-04 Thread Jan Korous via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG052f83890349: [libclang] Expose couple more AST details via 
cursors (authored by jkorous).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86991

Files:
  clang/include/clang-c/Index.h
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/libclang.exports
  clang/unittests/libclang/LibclangTest.cpp

Index: clang/unittests/libclang/LibclangTest.cpp
===
--- clang/unittests/libclang/LibclangTest.cpp
+++ clang/unittests/libclang/LibclangTest.cpp
@@ -736,3 +736,109 @@
 
   CheckTokenKinds();
 }
+
+TEST_F(LibclangParseTest, clang_getVarDeclInitializer) {
+  std::string Main = "main.cpp";
+  WriteFile(Main, "int foo() { return 5; }; const int a = foo();");
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0, nullptr,
+   0, TUFlags);
+
+  CXCursor C = clang_getTranslationUnitCursor(ClangTU);
+  clang_visitChildren(
+  C,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+if (clang_getCursorKind(cursor) == CXCursor_VarDecl) {
+  const CXCursor Initializer = clang_Cursor_getVarDeclInitializer(cursor);
+  EXPECT_FALSE(clang_Cursor_isNull(Initializer));
+  CXString Spelling = clang_getCursorSpelling(Initializer);
+  const char* const SpellingCSstr = clang_getCString(Spelling);
+  EXPECT_TRUE(SpellingCSstr);
+  EXPECT_EQ(std::string(SpellingCSstr), std::string("foo"));
+  clang_disposeString(Spelling);
+  return CXChildVisit_Break;
+}
+return CXChildVisit_Continue;
+  },
+  nullptr);
+}
+
+TEST_F(LibclangParseTest, clang_hasVarDeclGlobalStorageFalse) {
+  std::string Main = "main.cpp";
+  WriteFile(Main, "void foo() { int a; }");
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0, nullptr,
+   0, TUFlags);
+
+  CXCursor C = clang_getTranslationUnitCursor(ClangTU);
+  clang_visitChildren(
+  C,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+if (clang_getCursorKind(cursor) == CXCursor_VarDecl) {
+  EXPECT_FALSE(clang_Cursor_hasVarDeclGlobalStorage(cursor));
+  return CXChildVisit_Break;
+}
+return CXChildVisit_Continue;
+  },
+  nullptr);
+}
+
+TEST_F(LibclangParseTest, clang_Cursor_hasVarDeclGlobalStorageTrue) {
+  std::string Main = "main.cpp";
+  WriteFile(Main, "int a;");
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0, nullptr,
+   0, TUFlags);
+
+  CXCursor C = clang_getTranslationUnitCursor(ClangTU);
+  clang_visitChildren(
+  C,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+if (clang_getCursorKind(cursor) == CXCursor_VarDecl) {
+  EXPECT_TRUE(clang_Cursor_hasVarDeclGlobalStorage(cursor));
+  return CXChildVisit_Break;
+}
+return CXChildVisit_Continue;
+  },
+  nullptr);
+}
+
+TEST_F(LibclangParseTest, clang_Cursor_hasVarDeclExternalStorageFalse) {
+  std::string Main = "main.cpp";
+  WriteFile(Main, "int a;");
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0, nullptr,
+   0, TUFlags);
+
+  CXCursor C = clang_getTranslationUnitCursor(ClangTU);
+  clang_visitChildren(
+  C,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+if (clang_getCursorKind(cursor) == CXCursor_VarDecl) {
+  EXPECT_FALSE(clang_Cursor_hasVarDeclExternalStorage(cursor));
+  return CXChildVisit_Break;
+}
+return CXChildVisit_Continue;
+  },
+  nullptr);
+}
+
+TEST_F(LibclangParseTest, clang_Cursor_hasVarDeclExternalStorageTrue) {
+  std::string Main = "main.cpp";
+  WriteFile(Main, "extern int a;");
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0, nullptr,
+   0, TUFlags);
+
+  CXCursor C = clang_getTranslationUnitCursor(ClangTU);
+  clang_visitChildren(
+  C,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+if (clang_getCursorKind(cursor) == CXCursor_VarDecl) {
+  EXPECT_TRUE(clang_Cursor_hasVarDeclExternalStorage(cursor));
+  return CXChildVisit_Break;
+}
+return CXChildVisit_Continue;
+  },
+  nullptr);
+}
Index: clang/tools/libclang/libclang.exports
===
--- clang/tools/libclang/libclang.exports
+++ clang

[clang] 052f838 - [libclang] Expose couple more AST details via cursors

2020-09-04 Thread Jan Korous via cfe-commits

Author: Jan Korous
Date: 2020-09-04T13:38:47-07:00
New Revision: 052f83890349822a606c916b2fee501bc087652b

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

LOG: [libclang] Expose couple more AST details via cursors

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

Added: 


Modified: 
clang/include/clang-c/Index.h
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/libclang.exports
clang/unittests/libclang/LibclangTest.cpp

Removed: 




diff  --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index 5fa728d6d66c..4838937c8da6 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -2940,6 +2940,26 @@ CINDEX_LINKAGE int clang_getCursorPlatformAvailability(
 CINDEX_LINKAGE void
 clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability);
 
+/**
+ * If cursor refers to a variable declaration and it has initializer returns
+ * cursor referring to the initializer otherwise return null cursor.
+ */
+CINDEX_LINKAGE CXCursor clang_Cursor_getVarDeclInitializer(CXCursor cursor);
+
+/**
+ * If cursor refers to a variable declaration that has global storage returns 
1.
+ * If cursor refers to a variable declaration that doesn't have global storage
+ * returns 0. Otherwise returns -1.
+ */
+CINDEX_LINKAGE int clang_Cursor_hasVarDeclGlobalStorage(CXCursor cursor);
+
+/**
+ * If cursor refers to a variable declaration that has external storage
+ * returns 1. If cursor refers to a variable declaration that doesn't have
+ * external storage returns 0. Otherwise returns -1.
+ */
+CINDEX_LINKAGE int clang_Cursor_hasVarDeclExternalStorage(CXCursor cursor);
+
 /**
  * Describe the "language" of the entity referred to by a cursor.
  */

diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 683b517d79fd..87138cd3b4a3 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -8851,6 +8851,42 @@ void clang::PrintLibclangResourceUsage(CXTranslationUnit 
TU) {
   clang_disposeCXTUResourceUsage(Usage);
 }
 
+CXCursor clang_Cursor_getVarDeclInitializer(CXCursor cursor) {
+  const Decl *const D = getCursorDecl(cursor);
+  if (!D)
+return clang_getNullCursor();
+  const auto *const VD = dyn_cast(D);
+  if (!VD)
+return clang_getNullCursor();
+  const Expr *const Init = VD->getInit();
+  if (!Init)
+return clang_getNullCursor();
+
+  return cxcursor::MakeCXCursor(Init, VD, cxcursor::getCursorTU(cursor));
+}
+
+int clang_Cursor_hasVarDeclGlobalStorage(CXCursor cursor) {
+  const Decl *const D = getCursorDecl(cursor);
+  if (!D)
+return -1;
+  const auto *const VD = dyn_cast(D);
+  if (!VD)
+return -1;
+
+  return VD->hasGlobalStorage();
+}
+
+int clang_Cursor_hasVarDeclExternalStorage(CXCursor cursor) {
+  const Decl *const D = getCursorDecl(cursor);
+  if (!D)
+return -1;
+  const auto *const VD = dyn_cast(D);
+  if (!VD)
+return -1;
+
+  return VD->hasExternalStorage();
+}
+
 
//===--===//
 // Misc. utility functions.
 
//===--===//

diff  --git a/clang/tools/libclang/libclang.exports 
b/clang/tools/libclang/libclang.exports
index defbaa91a488..618f99f348fb 100644
--- a/clang/tools/libclang/libclang.exports
+++ b/clang/tools/libclang/libclang.exports
@@ -382,3 +382,6 @@ clang_PrintingPolicy_setProperty
 clang_PrintingPolicy_dispose
 clang_install_aborting_llvm_fatal_error_handler
 clang_uninstall_llvm_fatal_error_handler
+clang_Cursor_getVarDeclInitializer
+clang_Cursor_hasVarDeclGlobalStorage
+clang_Cursor_hasVarDeclExternalStorage

diff  --git a/clang/unittests/libclang/LibclangTest.cpp 
b/clang/unittests/libclang/LibclangTest.cpp
index e2e3a8e887ba..27fe10dfbb0f 100644
--- a/clang/unittests/libclang/LibclangTest.cpp
+++ b/clang/unittests/libclang/LibclangTest.cpp
@@ -736,3 +736,109 @@ TEST_F(LibclangSerializationTest, 
TokenKindsAreCorrectAfterLoading) {
 
   CheckTokenKinds();
 }
+
+TEST_F(LibclangParseTest, clang_getVarDeclInitializer) {
+  std::string Main = "main.cpp";
+  WriteFile(Main, "int foo() { return 5; }; const int a = foo();");
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0, 
nullptr,
+   0, TUFlags);
+
+  CXCursor C = clang_getTranslationUnitCursor(ClangTU);
+  clang_visitChildren(
+  C,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+if (clang_getCursorKind(cursor) == CXCursor_VarDecl) {
+  const CXCursor Initializer = 
clang_Cursor_getVarDeclInitializer(cursor);
+  EXPECT_FALSE(clang_Cursor_isNull(Initializer));
+  CXString Spelling = clang

[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-09-04 Thread Barry Revzin via Phabricator via cfe-commits
BRevzin updated this revision to Diff 290023.
BRevzin added a comment.
Herald added subscribers: rupprecht, MaskRay.
Herald added a reviewer: jhenderson.
Herald added a reviewer: MaskRay.

Updating this review with some additional changes that need to be made since I 
last touched it, and some of the previous changes had inadvertently broken the 
C++14 build so fixing those as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78938

Files:
  clang/include/clang/AST/StmtIterator.h
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  llvm/include/llvm/ADT/AllocatorList.h
  llvm/include/llvm/ADT/DenseMap.h
  llvm/include/llvm/ADT/DenseSet.h
  llvm/include/llvm/ADT/DirectedGraph.h
  llvm/include/llvm/ADT/STLExtras.h
  llvm/include/llvm/ADT/StringMap.h
  llvm/include/llvm/ADT/iterator.h
  llvm/include/llvm/CodeGen/DIE.h
  llvm/include/llvm/CodeGen/LiveInterval.h
  llvm/include/llvm/DebugInfo/DWARF/DWARFDie.h
  llvm/include/llvm/DebugInfo/DWARF/DWARFExpression.h
  llvm/include/llvm/IR/Attributes.h
  llvm/include/llvm/IR/BasicBlock.h
  llvm/include/llvm/Object/StackMapParser.h
  llvm/include/llvm/ProfileData/Coverage/CoverageMappingReader.h
  llvm/include/llvm/ProfileData/InstrProfReader.h
  llvm/include/llvm/Support/BinaryStreamRef.h
  llvm/include/llvm/Support/SuffixTree.h
  llvm/lib/CodeGen/PeepholeOptimizer.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/ObjectYAML/DWARFEmitter.cpp
  llvm/lib/Transforms/Scalar/GVNHoist.cpp
  llvm/tools/llvm-objdump/llvm-objdump.cpp
  llvm/unittests/ADT/STLExtrasTest.cpp

Index: llvm/unittests/ADT/STLExtrasTest.cpp
===
--- llvm/unittests/ADT/STLExtrasTest.cpp
+++ llvm/unittests/ADT/STLExtrasTest.cpp
@@ -462,22 +462,23 @@
   EXPECT_EQ(V1, to_address(V1));
 
   // Check fancy pointer overload for unique_ptr
+  // Parenthesizing to_address to avoid ADL finding std::to_address
   std::unique_ptr V2 = std::make_unique(0);
-  EXPECT_EQ(V2.get(), to_address(V2));
+  EXPECT_EQ(V2.get(), (to_address)(V2));
 
   V2.reset(V1);
-  EXPECT_EQ(V1, to_address(V2));
+  EXPECT_EQ(V1, (to_address)(V2));
   V2.release();
 
   // Check fancy pointer overload for shared_ptr
   std::shared_ptr V3 = std::make_shared(0);
   std::shared_ptr V4 = V3;
   EXPECT_EQ(V3.get(), V4.get());
-  EXPECT_EQ(V3.get(), to_address(V3));
-  EXPECT_EQ(V4.get(), to_address(V4));
+  EXPECT_EQ(V3.get(), (to_address)(V3));
+  EXPECT_EQ(V4.get(), (to_address)(V4));
 
   V3.reset(V1);
-  EXPECT_EQ(V1, to_address(V3));
+  EXPECT_EQ(V1, (to_address)(V3));
 }
 
 TEST(STLExtrasTest, partition_point) {
Index: llvm/tools/llvm-objdump/llvm-objdump.cpp
===
--- llvm/tools/llvm-objdump/llvm-objdump.cpp
+++ llvm/tools/llvm-objdump/llvm-objdump.cpp
@@ -802,19 +802,19 @@
 bool IsASCII = DbgVariables == DVASCII;
 switch (C) {
 case LineChar::RangeStart:
-  return IsASCII ? "^" : u8"\u2548";
+  return IsASCII ? "^" : (const char *)u8"\u2548";
 case LineChar::RangeMid:
-  return IsASCII ? "|" : u8"\u2503";
+  return IsASCII ? "|" : (const char *)u8"\u2503";
 case LineChar::RangeEnd:
-  return IsASCII ? "v" : u8"\u253b";
+  return IsASCII ? "v" : (const char *)u8"\u253b";
 case LineChar::LabelVert:
-  return IsASCII ? "|" : u8"\u2502";
+  return IsASCII ? "|" : (const char *)u8"\u2502";
 case LineChar::LabelCornerNew:
-  return IsASCII ? "/" : u8"\u250c";
+  return IsASCII ? "/" : (const char *)u8"\u250c";
 case LineChar::LabelCornerActive:
-  return IsASCII ? "|" : u8"\u2520";
+  return IsASCII ? "|" : (const char *)u8"\u2520";
 case LineChar::LabelHoriz:
-  return IsASCII ? "-" : u8"\u2500";
+  return IsASCII ? "-" : (const char *)u8"\u2500";
 }
 llvm_unreachable("Unhandled LineChar enum");
   }
Index: llvm/lib/Transforms/Scalar/GVNHoist.cpp
===
--- llvm/lib/Transforms/Scalar/GVNHoist.cpp
+++ llvm/lib/Transforms/Scalar/GVNHoist.cpp
@@ -149,8 +149,8 @@
   // The instruction (VN) which uses the values flowing out of CHI.
   Instruction *I;
 
-  bool operator==(const CHIArg &A) { return VN == A.VN; }
-  bool operator!=(const CHIArg &A) { return !(*this == A); }
+  bool operator==(const CHIArg &A) const { return VN == A.VN; }
+  bool operator!=(const CHIArg &A) const { return !(*this == A); }
 };
 
 using CHIIt = SmallVectorImpl::iterator;
Index: llvm/lib/ObjectYAML/DWARFEmitter.cpp
===
--- llvm/lib/ObjectYAML/DWARFEmitter.cpp
+++ llvm/lib/ObjectYAML/DWARFEmitter.cpp
@@ -615,7 +615,7 @@
 writeInteger((uint8_t)TableEntry.SegSelectorSize, OS, DI.IsLittleEndian);
 
 for (const SegAddrPair &Pair : TableEntry.SegAddrPairs) {
-  if (TableEntry.SegSelectorSize != 

[PATCH] D87162: [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

2020-09-04 Thread Pengxuan Zheng via Phabricator via cfe-commits
pzheng created this revision.
pzheng added reviewers: MaskRay, apazos.
Herald added subscribers: cfe-commits, dang.
Herald added a project: clang.
pzheng requested review of this revision.

With 6a75496836ea14bcfd2f4b59d35a1cad4ac58cee 
, these 
two options are no longer
forwarded to GCC. This patch restores the original behavior.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D87162

Files:
  clang/include/clang/Driver/Options.td
  clang/test/Driver/gcc_forward.c


Index: clang/test/Driver/gcc_forward.c
===
--- clang/test/Driver/gcc_forward.c
+++ clang/test/Driver/gcc_forward.c
@@ -1,7 +1,7 @@
-// RUN: %clang -### %s -target aarch64-none-elf \
+// RUN: %clang -### %s -target aarch64-none-elf -specs=nosys.specs 
-nostartfiles \
 // RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostdlib -r 
-rdynamic -static -static-pie \
 // RUN:   2>&1 | FileCheck --check-prefix=FORWARD %s
-// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" 
"-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" 
"_start" "-r"
+// FORWARD: gcc{{[^"]*}}" "-specs=nosys.specs" "-nostartfiles" "--coverage" 
"-fuse-ld=lld" "--ld-path=ld" "-nostdlib" "-rdynamic" "-static" "-static-pie" 
"-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
 
 // Check that we don't try to forward -Xclang or -mlinker-version to GCC.
 // PR12920 -- Check also we may not forward W_Group options to GCC.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2760,7 +2760,7 @@
 def noprebind : Flag<["-"], "noprebind">;
 def noprofilelib : Flag<["-"], "noprofilelib">;
 def noseglinkedit : Flag<["-"], "noseglinkedit">;
-def nostartfiles : Flag<["-"], "nostartfiles">;
+def nostartfiles : Flag<["-"], "nostartfiles">, Group;
 def nostdinc : Flag<["-"], "nostdinc">, Flags<[CoreOption]>;
 def nostdlibinc : Flag<["-"], "nostdlibinc">;
 def nostdincxx : Flag<["-"], "nostdinc++">, Flags<[CC1Option]>,
@@ -2861,7 +2861,7 @@
 def shared_libgcc : Flag<["-"], "shared-libgcc">;
 def shared : Flag<["-", "--"], "shared">, Group;
 def single__module : Flag<["-"], "single_module">;
-def specs_EQ : Joined<["-", "--"], "specs=">;
+def specs_EQ : Joined<["-", "--"], "specs=">, Group;
 def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
 def static_libgcc : Flag<["-"], "static-libgcc">;
 def static_libstdcxx : Flag<["-"], "static-libstdc++">;


Index: clang/test/Driver/gcc_forward.c
===
--- clang/test/Driver/gcc_forward.c
+++ clang/test/Driver/gcc_forward.c
@@ -1,7 +1,7 @@
-// RUN: %clang -### %s -target aarch64-none-elf \
+// RUN: %clang -### %s -target aarch64-none-elf -specs=nosys.specs -nostartfiles \
 // RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostdlib -r -rdynamic -static -static-pie \
 // RUN:   2>&1 | FileCheck --check-prefix=FORWARD %s
-// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" "-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
+// FORWARD: gcc{{[^"]*}}" "-specs=nosys.specs" "-nostartfiles" "--coverage" "-fuse-ld=lld" "--ld-path=ld" "-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
 
 // Check that we don't try to forward -Xclang or -mlinker-version to GCC.
 // PR12920 -- Check also we may not forward W_Group options to GCC.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2760,7 +2760,7 @@
 def noprebind : Flag<["-"], "noprebind">;
 def noprofilelib : Flag<["-"], "noprofilelib">;
 def noseglinkedit : Flag<["-"], "noseglinkedit">;
-def nostartfiles : Flag<["-"], "nostartfiles">;
+def nostartfiles : Flag<["-"], "nostartfiles">, Group;
 def nostdinc : Flag<["-"], "nostdinc">, Flags<[CoreOption]>;
 def nostdlibinc : Flag<["-"], "nostdlibinc">;
 def nostdincxx : Flag<["-"], "nostdinc++">, Flags<[CC1Option]>,
@@ -2861,7 +2861,7 @@
 def shared_libgcc : Flag<["-"], "shared-libgcc">;
 def shared : Flag<["-", "--"], "shared">, Group;
 def single__module : Flag<["-"], "single_module">;
-def specs_EQ : Joined<["-", "--"], "specs=">;
+def specs_EQ : Joined<["-", "--"], "specs=">, Group;
 def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
 def static_libgcc : Flag<["-"], "static-libgcc">;
 def static_libstdcxx : Flag<["-"], "static-libstdc++">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87163: [DSE] Switch to MemorySSA-backed DSE by default.

2020-09-04 Thread Florian Hahn via Phabricator via cfe-commits
fhahn created this revision.
fhahn added reviewers: efriedma, dmgreen, asbirlea, reames.
Herald added subscribers: cfe-commits, lxfind, nikic, kerbowa, jfb, dexonsmith, 
steven_wu, george.burgess.iv, modocache, hiraditya, Prazek, nhaehnle, jvesely.
Herald added projects: clang, LLVM.
fhahn requested review of this revision.

The tests have been updated and I plan to move them from the MSSA
directory up.

Some end-to-end tests needed small adjustments. One difference to the
legacy DSE is that legacy DSE also deletes trivially dead instructions
that are unrelated to memory operations. Because MemorySSA-backed DSE
just walks the MemorySSA, we only visit/check memory instructions. But
removing unrelated dead instructions is not really DSE's job and other
passes will clean up.

One noteworthy change is in llvm/test/Transforms/Coroutines/ArgAddr.ll,
but I think this comes down to legacy DSE not handling instructions that
may throw correctly in that case. To cover this with MemorySSA-backed
DSE, we need an update to llvm.coro.begin to treat it's return value to
belong to the same underlying object as the passed pointer.

There are some minor cases MemorySSA-backed DSE currently misses, e.g. related
to atomic operations, but I think those can be implemented after the switch.

This has been discussed on llvm-dev:
http://lists.llvm.org/pipermail/llvm-dev/2020-August/144417.html

For the MultiSource/SPEC2000/SPEC2006 the number of eliminated stores
goes from ~17500 (legayc DSE) to ~26300 (MemorySSA-backed). More numbers
and details in the thread on llvm-dev.

Impact on CTMark:

   Legacy Pass Manager
  exec instrssize-text

O3    + 0.60%   
 - 0.27%
ReleaseThinLTO   + 1.00%- 0.42%
ReleaseLTO-g.+ 0.77%- 0.33%
RelThinLTO (link only)   + 0.87%- 0.42%
RelLO-g (link only)  + 0.78%- 0.33%

http://llvm-compile-time-tracker.com/compare.php?from=3f22e96d95c71ded906c67067d75278efb0a2525&to=ae8be4642533ff03803967ee9d7017c0d73b0ee0&stat=instructions

New Pass Manager
  exec instrs.   size-text

O3    + 0.95%   
- 0.25%
ReleaseThinLTO   + 1.34%   - 0.41%
ReleaseLTO-g.+ 1.71%   - 0.35%
RelThinLTO (link only)   + 0.96%   - 0.41%
RelLO-g (link only)  + 2.21%   - 0.35%

http://195.201.131.214:8000/compare.php?from=3f22e96d95c71ded906c67067d75278efb0a2525&to=ae8be4642533ff03803967ee9d7017c0d73b0ee0&stat=instructions


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D87163

Files:
  clang/test/CodeGen/thinlto-distributed-newpm.ll
  clang/test/CodeGenObjC/exceptions.m
  llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp
  llvm/test/Analysis/BasicAA/modref.ll
  llvm/test/CodeGen/AMDGPU/opt-pipeline.ll
  llvm/test/Other/new-pm-defaults.ll
  llvm/test/Other/new-pm-lto-defaults.ll
  llvm/test/Other/new-pm-thinlto-defaults.ll
  llvm/test/Other/opt-O2-pipeline.ll
  llvm/test/Other/opt-O3-pipeline-enable-matrix.ll
  llvm/test/Other/opt-O3-pipeline.ll
  llvm/test/Other/opt-Os-pipeline.ll
  llvm/test/Transforms/Coroutines/ArgAddr.ll
  llvm/test/Transforms/Coroutines/coro-retcon.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/2011-03-25-DSEMiscompile.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/2011-09-06-EndOfFunction.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/2011-09-06-MemCpy.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/2016-07-17-UseAfterFree.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/OverwriteStoreBegin.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/OverwriteStoreEnd.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/PartialStore.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/PartialStore2.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/X86/gather-null-pointer.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/atomic-overlapping.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/atomic-todo.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/atomic.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/calloc-store.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/combined-partial-overwrites.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/const-pointers.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/crash.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/cs-cs-aliasing.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/debug-counter.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/debuginfo.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/dominate.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/fence-todo.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/fence.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/free.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/inst-limits.ll
  llvm/test/Transforms/DeadStoreElimination/MSSA/int_sideeffect.ll
  llvm/test/Transforms/DeadStoreElimination/

[PATCH] D87164: Extending Baremetal toolchain's support for the rtlib option.

2020-09-04 Thread Manuel Carrasco via Phabricator via cfe-commits
mcarrasco created this revision.
mcarrasco added reviewers: jroelofs, clang.
mcarrasco added a project: clang-modules.
Herald added subscribers: cfe-commits, abidh, kristof.beyls.
Herald added a project: clang.
mcarrasco requested review of this revision.

The Baremetal toolchain currently has a fixed behavior regardless of the -rtlib 
option's value. It is always linking against compiler-rt unless -nodefaultlibs 
is enabled.

This proposal slightly changes the code in such a way that enabling 
-rtlib=libgcc implies linking against -libgcc.

Something that I'm unsure about this patch is that we are not enforcing the 
existence of such libgcc. By reading other toolchains, I understood that is not 
always enforced. Do you think this policy is acceptable? If it is not, how 
would you think it should be addressed?

Context:

So far I manually set an -L path to a valid libgcc on my system when clang is 
invoked. In this particular case, I use arm-none-eabi-gcc -mthumb 
-mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -print-libgcc-file-name 
which retrieves the path I want.

Assume the user forwards a gcc-toolchain installation through --gcc-toolchain. 
Would be a good idea to programmatically query arm-none-eabi-gcc for the libgcc 
as described above? If that is the case, how would be the most "llvm way" to do 
it? I'm not very related to all abstractions and concepts from the framework.

This is my very first contribution to LLVM so I'd really appreciate any 
feedback in order to improve this proposal :)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D87164

Files:
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/test/Driver/baremetal.cpp


Index: clang/test/Driver/baremetal.cpp
===
--- clang/test/Driver/baremetal.cpp
+++ clang/test/Driver/baremetal.cpp
@@ -83,3 +83,7 @@
 // RUN: %clangxx -target arm-none-eabi -mthread-model posix -v 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-THREAD-MODEL-POSIX
 // CHECK-THREAD-MODEL-POSIX: Thread model: posix
+
+// RUN: %clang -### -target arm-none-eabi -rtlib=libgcc -v %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-RTLIB-GCC
+// CHECK-RTLIB-GCC: -lgcc
Index: clang/lib/Driver/ToolChains/BareMetal.cpp
===
--- clang/lib/Driver/ToolChains/BareMetal.cpp
+++ clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -156,8 +156,16 @@
 
 void BareMetal::AddLinkRuntimeLib(const ArgList &Args,
   ArgStringList &CmdArgs) const {
-  CmdArgs.push_back(Args.MakeArgString("-lclang_rt.builtins-" +
-   getTriple().getArchName()));
+  ToolChain::RuntimeLibType RLT = GetRuntimeLibType(Args);
+  switch (RLT) {
+  case ToolChain::RLT_CompilerRT:
+CmdArgs.push_back(
+Args.MakeArgString("-lclang_rt.builtins-" + 
getTriple().getArchName()));
+break;
+  case ToolChain::RLT_Libgcc:
+CmdArgs.push_back("-lgcc");
+break;
+  }
 }
 
 void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA,


Index: clang/test/Driver/baremetal.cpp
===
--- clang/test/Driver/baremetal.cpp
+++ clang/test/Driver/baremetal.cpp
@@ -83,3 +83,7 @@
 // RUN: %clangxx -target arm-none-eabi -mthread-model posix -v 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-THREAD-MODEL-POSIX
 // CHECK-THREAD-MODEL-POSIX: Thread model: posix
+
+// RUN: %clang -### -target arm-none-eabi -rtlib=libgcc -v %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-RTLIB-GCC
+// CHECK-RTLIB-GCC: -lgcc
Index: clang/lib/Driver/ToolChains/BareMetal.cpp
===
--- clang/lib/Driver/ToolChains/BareMetal.cpp
+++ clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -156,8 +156,16 @@
 
 void BareMetal::AddLinkRuntimeLib(const ArgList &Args,
   ArgStringList &CmdArgs) const {
-  CmdArgs.push_back(Args.MakeArgString("-lclang_rt.builtins-" +
-   getTriple().getArchName()));
+  ToolChain::RuntimeLibType RLT = GetRuntimeLibType(Args);
+  switch (RLT) {
+  case ToolChain::RLT_CompilerRT:
+CmdArgs.push_back(
+Args.MakeArgString("-lclang_rt.builtins-" + getTriple().getArchName()));
+break;
+  case ToolChain::RLT_Libgcc:
+CmdArgs.push_back("-lgcc");
+break;
+  }
 }
 
 void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 69e5abb - [libclang] Add CXRewriter to libclang API

2020-09-04 Thread Jan Korous via cfe-commits

Author: Jan Korous
Date: 2020-09-04T14:17:03-07:00
New Revision: 69e5abb57b70570cf04671a93246e5e624023650

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

LOG: [libclang] Add CXRewriter to libclang API

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

Added: 
clang/include/clang-c/Rewrite.h
clang/tools/libclang/Rewrite.cpp

Modified: 
clang/tools/libclang/CMakeLists.txt
clang/tools/libclang/libclang.exports
clang/unittests/libclang/LibclangTest.cpp

Removed: 




diff  --git a/clang/include/clang-c/Rewrite.h b/clang/include/clang-c/Rewrite.h
new file mode 100644
index ..ce1b05594b38
--- /dev/null
+++ b/clang/include/clang-c/Rewrite.h
@@ -0,0 +1,63 @@
+/*===-- clang-c/Rewrite.h - C CXRewriter   --*- 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
*|
+|*
*|
+|*===--===*/
+
+#ifndef LLVM_CLANG_C_REWRITE_H
+#define LLVM_CLANG_C_REWRITE_H
+
+#include "clang-c/CXString.h"
+#include "clang-c/ExternC.h"
+#include "clang-c/Index.h"
+#include "clang-c/Platform.h"
+
+LLVM_CLANG_C_EXTERN_C_BEGIN
+
+typedef void *CXRewriter;
+
+/**
+ * Create CXRewriter.
+ */
+CINDEX_LINKAGE CXRewriter clang_CXRewriter_create(CXTranslationUnit TU);
+
+/**
+ * Insert the specified string at the specified location in the original 
buffer.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_insertTextBefore(CXRewriter Rew, 
CXSourceLocation Loc,
+   const char *Insert);
+
+/**
+ * Replace the specified range of characters in the input with the specified
+ * replacement.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_replaceText(CXRewriter Rew, CXSourceRange 
ToBeReplaced,
+  const char *Replacement);
+
+/**
+ * Remove the specified range.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_removeText(CXRewriter Rew, CXSourceRange 
ToBeRemoved);
+
+/**
+ * Save all changed files to disk.
+ * Returns 1 if any files were not saved successfully, returns 0 otherwise.
+ */
+CINDEX_LINKAGE int clang_CXRewriter_overwriteChangedFiles(CXRewriter Rew);
+
+/**
+ * Write out rewritten version of the main file to stdout.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_writeMainFileToStdOut(CXRewriter Rew);
+
+/**
+ * Free the given CXRewriter.
+ */
+CINDEX_LINKAGE void clang_CXRewriter_dispose(CXRewriter Rew);
+
+LLVM_CLANG_C_EXTERN_C_END
+
+#endif

diff  --git a/clang/tools/libclang/CMakeLists.txt 
b/clang/tools/libclang/CMakeLists.txt
index a4077140acee..4e2c19da0f7c 100644
--- a/clang/tools/libclang/CMakeLists.txt
+++ b/clang/tools/libclang/CMakeLists.txt
@@ -20,6 +20,7 @@ set(SOURCES
   CXType.cpp
   Indexing.cpp
   FatalErrorHandler.cpp
+  Rewrite.cpp
 
   ADDITIONAL_HEADERS
   CIndexDiagnostic.h

diff  --git a/clang/tools/libclang/Rewrite.cpp 
b/clang/tools/libclang/Rewrite.cpp
new file mode 100644
index ..389232d97acc
--- /dev/null
+++ b/clang/tools/libclang/Rewrite.cpp
@@ -0,0 +1,63 @@
+//===- Rewrite.cpp 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang-c/Rewrite.h"
+#include "CXSourceLocation.h"
+#include "CXTranslationUnit.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Rewrite/Core/Rewriter.h"
+
+CXRewriter clang_CXRewriter_create(CXTranslationUnit TU) {
+  if (clang::cxtu::isNotUsableTU(TU)) {
+LOG_BAD_TU(TU);
+return {};
+  }
+  clang::ASTUnit *AU = clang::cxtu::getASTUnit(TU);
+  assert(AU);
+  return reinterpret_cast(
+  new clang::Rewriter(AU->getSourceManager(), AU->getLangOpts()));
+}
+
+void clang_CXRewriter_insertTextBefore(CXRewriter Rew, CXSourceLocation Loc,
+const char *Insert) {
+  assert(Rew);
+  clang::Rewriter &R = *reinterpret_cast(Rew);
+  R.InsertTextBefore(clang::cxloc::translateSourceLocation(Loc), Insert);
+}
+
+void clang_CXRewriter_replaceText(CXRewriter Rew, CXSourceRange ToBeReplaced,
+   const char *Replacement) {
+  assert(Rew);
+ 

[PATCH] D86992: [libclang] Expose Rewriter in libclang API

2020-09-04 Thread Jan Korous via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG69e5abb57b70: [libclang] Add CXRewriter to libclang API 
(authored by jkorous).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D86992?vs=289837&id=290027#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86992

Files:
  clang/include/clang-c/Rewrite.h
  clang/tools/libclang/CMakeLists.txt
  clang/tools/libclang/Rewrite.cpp
  clang/tools/libclang/libclang.exports
  clang/unittests/libclang/LibclangTest.cpp

Index: clang/unittests/libclang/LibclangTest.cpp
===
--- clang/unittests/libclang/LibclangTest.cpp
+++ clang/unittests/libclang/LibclangTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang-c/Index.h"
+#include "clang-c/Rewrite.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/FileSystem.h"
@@ -842,3 +843,90 @@
   },
   nullptr);
 }
+class LibclangRewriteTest : public LibclangParseTest {
+public:
+  CXRewriter Rew = nullptr;
+  std::string Filename;
+  CXFile File = nullptr;
+
+  void SetUp() override {
+LibclangParseTest::SetUp();
+Filename = "file.cpp";
+WriteFile(Filename, "int main() { return 0; }");
+ClangTU = clang_parseTranslationUnit(Index, Filename.c_str(), nullptr, 0,
+ nullptr, 0, TUFlags);
+Rew = clang_CXRewriter_create(ClangTU);
+File = clang_getFile(ClangTU, Filename.c_str());
+  }
+  void TearDown() override {
+clang_CXRewriter_dispose(Rew);
+LibclangParseTest::TearDown();
+  }
+};
+
+static std::string getFileContent(const std::string& Filename) {
+  std::ifstream RewrittenFile(Filename);
+  std::string RewrittenFileContent;
+  std::string Line;
+  while (std::getline(RewrittenFile, Line)) {
+if (RewrittenFileContent.empty())
+  RewrittenFileContent = Line;
+else {
+  RewrittenFileContent += "\n" + Line;
+}
+  }
+  return RewrittenFileContent;
+}
+
+TEST_F(LibclangRewriteTest, RewriteReplace) {
+  CXSourceLocation B = clang_getLocation(ClangTU, File, 1, 5);
+  CXSourceLocation E = clang_getLocation(ClangTU, File, 1, 9);
+  CXSourceRange Rng	= clang_getRange(B, E);
+
+  clang_CXRewriter_replaceText(Rew, Rng, "MAIN");
+
+  ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(Rew), 0);
+  EXPECT_EQ(getFileContent(Filename), "int MAIN() { return 0; }");
+}
+
+TEST_F(LibclangRewriteTest, RewriteReplaceShorter) {
+  CXSourceLocation B = clang_getLocation(ClangTU, File, 1, 5);
+  CXSourceLocation E = clang_getLocation(ClangTU, File, 1, 9);
+  CXSourceRange Rng	= clang_getRange(B, E);
+
+  clang_CXRewriter_replaceText(Rew, Rng, "foo");
+
+  ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(Rew), 0);
+  EXPECT_EQ(getFileContent(Filename), "int foo() { return 0; }");
+}
+
+TEST_F(LibclangRewriteTest, RewriteReplaceLonger) {
+  CXSourceLocation B = clang_getLocation(ClangTU, File, 1, 5);
+  CXSourceLocation E = clang_getLocation(ClangTU, File, 1, 9);
+  CXSourceRange Rng	= clang_getRange(B, E);
+
+  clang_CXRewriter_replaceText(Rew, Rng, "patatino");
+
+  ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(Rew), 0);
+  EXPECT_EQ(getFileContent(Filename), "int patatino() { return 0; }");
+}
+
+TEST_F(LibclangRewriteTest, RewriteInsert) {
+  CXSourceLocation Loc = clang_getLocation(ClangTU, File, 1, 5);
+
+  clang_CXRewriter_insertTextBefore(Rew, Loc, "ro");
+
+  ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(Rew), 0);
+  EXPECT_EQ(getFileContent(Filename), "int romain() { return 0; }");
+}
+
+TEST_F(LibclangRewriteTest, RewriteRemove) {
+  CXSourceLocation B = clang_getLocation(ClangTU, File, 1, 5);
+  CXSourceLocation E = clang_getLocation(ClangTU, File, 1, 9);
+  CXSourceRange Rng	= clang_getRange(B, E);
+
+  clang_CXRewriter_removeText(Rew, Rng);
+
+  ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(Rew), 0);
+  EXPECT_EQ(getFileContent(Filename), "int () { return 0; }");
+}
Index: clang/tools/libclang/libclang.exports
===
--- clang/tools/libclang/libclang.exports
+++ clang/tools/libclang/libclang.exports
@@ -385,3 +385,10 @@
 clang_Cursor_getVarDeclInitializer
 clang_Cursor_hasVarDeclGlobalStorage
 clang_Cursor_hasVarDeclExternalStorage
+clang_CXRewriter_create
+clang_CXRewriter_insertTextBefore
+clang_CXRewriter_replaceText
+clang_CXRewriter_removeText
+clang_CXRewriter_overwriteChangedFiles
+clang_CXRewriter_writeMainFileToStdOut
+clang_CXRewriter_dispose
Index: clang/tools/libclang/Rewrite.cpp
===
--- /dev/null
+++ clang/tools/libclang/Rewrite.cpp
@@ -0,0 +1,63 @@
+//===- Rewrite.cpp ===//
+//

[PATCH] D87163: [DSE] Switch to MemorySSA-backed DSE by default.

2020-09-04 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added inline comments.



Comment at: llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp:115
cl::desc("The number of memory instructions to scan for 
"
 "dead store elimination (default = 100)"));
 static cl::opt MemorySSAUpwardsStepLimit(

Default 150?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87163

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


[PATCH] D87162: [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

2020-09-04 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.
This revision is now accepted and ready to land.

LGTM.




Comment at: clang/test/Driver/gcc_forward.c:4
 // RUN:   2>&1 | FileCheck --check-prefix=FORWARD %s
-// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" 
"-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" 
"_start" "-r"
+// FORWARD: gcc{{[^"]*}}" "-specs=nosys.specs" "-nostartfiles" "--coverage" 
"-fuse-ld=lld" "--ld-path=ld" "-nostdlib" "-rdynamic" "-static" "-static-pie" 
"-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
 

Moving nostartfiles before nostdlib to keep an alphabetical order.

Similarly, specs can precede static.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87162

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


[PATCH] D87162: [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

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

Can D83648  be closed now?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87162

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


[clang] 7cfc8f0 - [libclang] Add missing dependency on clangRewrite lib

2020-09-04 Thread Jan Korous via cfe-commits

Author: Jan Korous
Date: 2020-09-04T14:59:53-07:00
New Revision: 7cfc8f0c7c2440ea8aa722304f9e6ef32472833b

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

LOG: [libclang] Add missing dependency on clangRewrite lib

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

Added: 


Modified: 
clang/tools/libclang/CMakeLists.txt

Removed: 




diff  --git a/clang/tools/libclang/CMakeLists.txt 
b/clang/tools/libclang/CMakeLists.txt
index 4e2c19da0f7c4..c3b9ab6ffb9b0 100644
--- a/clang/tools/libclang/CMakeLists.txt
+++ b/clang/tools/libclang/CMakeLists.txt
@@ -42,6 +42,7 @@ set(LIBS
   clangFrontend
   clangIndex
   clangLex
+  clangRewrite
   clangSema
   clangSerialization
   clangTooling



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


[PATCH] D87162: [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

2020-09-04 Thread Pengxuan Zheng via Phabricator via cfe-commits
pzheng marked an inline comment as done.
pzheng added a comment.

In D87162#2257192 , @MaskRay wrote:

> Can D83648  be closed now?

Yes, I have closed it.

> BTW, can you describe a bit about your use cases? Forwarding options to gcc 
> does not seem common nowadays...

It's probably not used very common, but we do have some baremetal use cases 
still relying on these flags to be propagated to GCC.




Comment at: clang/test/Driver/gcc_forward.c:4
 // RUN:   2>&1 | FileCheck --check-prefix=FORWARD %s
-// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" 
"-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" 
"_start" "-r"
+// FORWARD: gcc{{[^"]*}}" "-specs=nosys.specs" "-nostartfiles" "--coverage" 
"-fuse-ld=lld" "--ld-path=ld" "-nostdlib" "-rdynamic" "-static" "-static-pie" 
"-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
 

MaskRay wrote:
> Moving nostartfiles before nostdlib to keep an alphabetical order.
> 
> Similarly, specs can precede static.
Thanks for pointing this out. I did not realize the flags are ordered. Will 
update the patch shortly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87162

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


[PATCH] D87162: [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

2020-09-04 Thread Pengxuan Zheng via Phabricator via cfe-commits
pzheng updated this revision to Diff 290038.
pzheng marked an inline comment as done.
pzheng added a comment.

Updated the test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87162

Files:
  clang/include/clang/Driver/Options.td
  clang/test/Driver/gcc_forward.c


Index: clang/test/Driver/gcc_forward.c
===
--- clang/test/Driver/gcc_forward.c
+++ clang/test/Driver/gcc_forward.c
@@ -1,7 +1,8 @@
 // RUN: %clang -### %s -target aarch64-none-elf \
-// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostdlib -r 
-rdynamic -static -static-pie \
+// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostartfiles \
+// RUN:   -nostdlib -r -rdynamic -specs=nosys.specs -static -static-pie \
 // RUN:   2>&1 | FileCheck --check-prefix=FORWARD %s
-// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" 
"-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" 
"_start" "-r"
+// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" 
"-nostartfiles" "-nostdlib" "-rdynamic" "-specs=nosys.specs" "-static" 
"-static-pie" "-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
 
 // Check that we don't try to forward -Xclang or -mlinker-version to GCC.
 // PR12920 -- Check also we may not forward W_Group options to GCC.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2760,7 +2760,7 @@
 def noprebind : Flag<["-"], "noprebind">;
 def noprofilelib : Flag<["-"], "noprofilelib">;
 def noseglinkedit : Flag<["-"], "noseglinkedit">;
-def nostartfiles : Flag<["-"], "nostartfiles">;
+def nostartfiles : Flag<["-"], "nostartfiles">, Group;
 def nostdinc : Flag<["-"], "nostdinc">, Flags<[CoreOption]>;
 def nostdlibinc : Flag<["-"], "nostdlibinc">;
 def nostdincxx : Flag<["-"], "nostdinc++">, Flags<[CC1Option]>,
@@ -2861,7 +2861,7 @@
 def shared_libgcc : Flag<["-"], "shared-libgcc">;
 def shared : Flag<["-", "--"], "shared">, Group;
 def single__module : Flag<["-"], "single_module">;
-def specs_EQ : Joined<["-", "--"], "specs=">;
+def specs_EQ : Joined<["-", "--"], "specs=">, Group;
 def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
 def static_libgcc : Flag<["-"], "static-libgcc">;
 def static_libstdcxx : Flag<["-"], "static-libstdc++">;


Index: clang/test/Driver/gcc_forward.c
===
--- clang/test/Driver/gcc_forward.c
+++ clang/test/Driver/gcc_forward.c
@@ -1,7 +1,8 @@
 // RUN: %clang -### %s -target aarch64-none-elf \
-// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostdlib -r -rdynamic -static -static-pie \
+// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostartfiles \
+// RUN:   -nostdlib -r -rdynamic -specs=nosys.specs -static -static-pie \
 // RUN:   2>&1 | FileCheck --check-prefix=FORWARD %s
-// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" "-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
+// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" "-nostartfiles" "-nostdlib" "-rdynamic" "-specs=nosys.specs" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
 
 // Check that we don't try to forward -Xclang or -mlinker-version to GCC.
 // PR12920 -- Check also we may not forward W_Group options to GCC.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2760,7 +2760,7 @@
 def noprebind : Flag<["-"], "noprebind">;
 def noprofilelib : Flag<["-"], "noprofilelib">;
 def noseglinkedit : Flag<["-"], "noseglinkedit">;
-def nostartfiles : Flag<["-"], "nostartfiles">;
+def nostartfiles : Flag<["-"], "nostartfiles">, Group;
 def nostdinc : Flag<["-"], "nostdinc">, Flags<[CoreOption]>;
 def nostdlibinc : Flag<["-"], "nostdlibinc">;
 def nostdincxx : Flag<["-"], "nostdinc++">, Flags<[CC1Option]>,
@@ -2861,7 +2861,7 @@
 def shared_libgcc : Flag<["-"], "shared-libgcc">;
 def shared : Flag<["-", "--"], "shared">, Group;
 def single__module : Flag<["-"], "single_module">;
-def specs_EQ : Joined<["-", "--"], "specs=">;
+def specs_EQ : Joined<["-", "--"], "specs=">, Group;
 def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
 def static_libgcc : Flag<["-"], "static-libgcc">;
 def static_libstdcxx : Flag<["-"], "static-libstdc++">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2bccd2b - [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

2020-09-04 Thread Pengxuan Zheng via cfe-commits

Author: Pengxuan Zheng
Date: 2020-09-04T15:09:33-07:00
New Revision: 2bccd2b4350f887cc7fea1cc488690f58186c440

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

LOG: [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

With 6a75496836ea14bcfd2f4b59d35a1cad4ac58cee, these two options are no longer
forwarded to GCC. This patch restores the original behavior.

Reviewed By: MaskRay

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/test/Driver/gcc_forward.c

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5f1668e701f1..4ba5d40117e7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2760,7 +2760,7 @@ def no_pie : Flag<["-"], "no-pie">, Alias;
 def noprebind : Flag<["-"], "noprebind">;
 def noprofilelib : Flag<["-"], "noprofilelib">;
 def noseglinkedit : Flag<["-"], "noseglinkedit">;
-def nostartfiles : Flag<["-"], "nostartfiles">;
+def nostartfiles : Flag<["-"], "nostartfiles">, Group;
 def nostdinc : Flag<["-"], "nostdinc">, Flags<[CoreOption]>;
 def nostdlibinc : Flag<["-"], "nostdlibinc">;
 def nostdincxx : Flag<["-"], "nostdinc++">, Flags<[CC1Option]>,
@@ -2861,7 +2861,7 @@ def segs__read__ : Joined<["-"], "segs_read_">;
 def shared_libgcc : Flag<["-"], "shared-libgcc">;
 def shared : Flag<["-", "--"], "shared">, Group;
 def single__module : Flag<["-"], "single_module">;
-def specs_EQ : Joined<["-", "--"], "specs=">;
+def specs_EQ : Joined<["-", "--"], "specs=">, Group;
 def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
 def static_libgcc : Flag<["-"], "static-libgcc">;
 def static_libstdcxx : Flag<["-"], "static-libstdc++">;

diff  --git a/clang/test/Driver/gcc_forward.c b/clang/test/Driver/gcc_forward.c
index a99944f8f533..e6b0670d1a02 100644
--- a/clang/test/Driver/gcc_forward.c
+++ b/clang/test/Driver/gcc_forward.c
@@ -1,7 +1,8 @@
 // RUN: %clang -### %s -target aarch64-none-elf \
-// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostdlib -r 
-rdynamic -static -static-pie \
+// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostartfiles \
+// RUN:   -nostdlib -r -rdynamic -specs=nosys.specs -static -static-pie \
 // RUN:   2>&1 | FileCheck --check-prefix=FORWARD %s
-// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" 
"-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" 
"_start" "-r"
+// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" 
"-nostartfiles" "-nostdlib" "-rdynamic" "-specs=nosys.specs" "-static" 
"-static-pie" "-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
 
 // Check that we don't try to forward -Xclang or -mlinker-version to GCC.
 // PR12920 -- Check also we may not forward W_Group options to GCC.



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


[PATCH] D87162: [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

2020-09-04 Thread Pengxuan Zheng 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 rG2bccd2b4350f: [Driver] Allow -specs and -nostartfiles to be 
forwarded to GCC (authored by pzheng).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87162

Files:
  clang/include/clang/Driver/Options.td
  clang/test/Driver/gcc_forward.c


Index: clang/test/Driver/gcc_forward.c
===
--- clang/test/Driver/gcc_forward.c
+++ clang/test/Driver/gcc_forward.c
@@ -1,7 +1,8 @@
 // RUN: %clang -### %s -target aarch64-none-elf \
-// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostdlib -r 
-rdynamic -static -static-pie \
+// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostartfiles \
+// RUN:   -nostdlib -r -rdynamic -specs=nosys.specs -static -static-pie \
 // RUN:   2>&1 | FileCheck --check-prefix=FORWARD %s
-// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" 
"-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" 
"_start" "-r"
+// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" 
"-nostartfiles" "-nostdlib" "-rdynamic" "-specs=nosys.specs" "-static" 
"-static-pie" "-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
 
 // Check that we don't try to forward -Xclang or -mlinker-version to GCC.
 // PR12920 -- Check also we may not forward W_Group options to GCC.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2760,7 +2760,7 @@
 def noprebind : Flag<["-"], "noprebind">;
 def noprofilelib : Flag<["-"], "noprofilelib">;
 def noseglinkedit : Flag<["-"], "noseglinkedit">;
-def nostartfiles : Flag<["-"], "nostartfiles">;
+def nostartfiles : Flag<["-"], "nostartfiles">, Group;
 def nostdinc : Flag<["-"], "nostdinc">, Flags<[CoreOption]>;
 def nostdlibinc : Flag<["-"], "nostdlibinc">;
 def nostdincxx : Flag<["-"], "nostdinc++">, Flags<[CC1Option]>,
@@ -2861,7 +2861,7 @@
 def shared_libgcc : Flag<["-"], "shared-libgcc">;
 def shared : Flag<["-", "--"], "shared">, Group;
 def single__module : Flag<["-"], "single_module">;
-def specs_EQ : Joined<["-", "--"], "specs=">;
+def specs_EQ : Joined<["-", "--"], "specs=">, Group;
 def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
 def static_libgcc : Flag<["-"], "static-libgcc">;
 def static_libstdcxx : Flag<["-"], "static-libstdc++">;


Index: clang/test/Driver/gcc_forward.c
===
--- clang/test/Driver/gcc_forward.c
+++ clang/test/Driver/gcc_forward.c
@@ -1,7 +1,8 @@
 // RUN: %clang -### %s -target aarch64-none-elf \
-// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostdlib -r -rdynamic -static -static-pie \
+// RUN:   --coverage -e _start -fuse-ld=lld --ld-path=ld -nostartfiles \
+// RUN:   -nostdlib -r -rdynamic -specs=nosys.specs -static -static-pie \
 // RUN:   2>&1 | FileCheck --check-prefix=FORWARD %s
-// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" "-nostdlib" "-rdynamic" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
+// FORWARD: gcc{{[^"]*}}" "--coverage" "-fuse-ld=lld" "--ld-path=ld" "-nostartfiles" "-nostdlib" "-rdynamic" "-specs=nosys.specs" "-static" "-static-pie" "-o" "a.out" "{{.*}}.o" "-e" "_start" "-r"
 
 // Check that we don't try to forward -Xclang or -mlinker-version to GCC.
 // PR12920 -- Check also we may not forward W_Group options to GCC.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2760,7 +2760,7 @@
 def noprebind : Flag<["-"], "noprebind">;
 def noprofilelib : Flag<["-"], "noprofilelib">;
 def noseglinkedit : Flag<["-"], "noseglinkedit">;
-def nostartfiles : Flag<["-"], "nostartfiles">;
+def nostartfiles : Flag<["-"], "nostartfiles">, Group;
 def nostdinc : Flag<["-"], "nostdinc">, Flags<[CoreOption]>;
 def nostdlibinc : Flag<["-"], "nostdlibinc">;
 def nostdincxx : Flag<["-"], "nostdinc++">, Flags<[CC1Option]>,
@@ -2861,7 +2861,7 @@
 def shared_libgcc : Flag<["-"], "shared-libgcc">;
 def shared : Flag<["-", "--"], "shared">, Group;
 def single__module : Flag<["-"], "single_module">;
-def specs_EQ : Joined<["-", "--"], "specs=">;
+def specs_EQ : Joined<["-", "--"], "specs=">, Group;
 def specs : Separate<["-", "--"], "specs">, Flags<[Unsupported]>;
 def static_libgcc : Flag<["-"], "static-libgcc">;
 def static_libstdcxx : Flag<["-"], "static-libstdc++">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87162: [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

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

LGTM.

> It's probably not used very common, but we do have some baremetal use cases 
> still relying on these flags to be propagated to GCC.

Thanks for the explanation! (Though I think in these cases calling `ld` or 
`ld.lld` directly might be better?)

And apologies about the friction but I hope the current behavior is better than 
the previous whether many unrelated options can be forwarded and many can cause 
warnings on GCC side.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87162

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


[PATCH] D87162: [Driver] Allow -specs and -nostartfiles to be forwarded to GCC

2020-09-04 Thread Pengxuan Zheng via Phabricator via cfe-commits
pzheng added a comment.

In D87162#2257233 , @MaskRay wrote:

> LGTM.
>
>> It's probably not used very common, but we do have some baremetal use cases 
>> still relying on these flags to be propagated to GCC.
>
> Thanks for the explanation! (Though I think in these cases calling `ld` or 
> `ld.lld` directly might be better?)
>
> And apologies about the friction but I hope the current behavior is better 
> than the previous whether many unrelated options can be forwarded and many 
> can cause warnings on GCC side.

No worries. Hopefully, these flags are the only outliers. Thanks for reviewing 
the patch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87162

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


[PATCH] D87064: Thread safety analysis: Test and document release_generic_capability

2020-09-04 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert updated this revision to Diff 290045.
aaronpuchert added a comment.

Add some prose, not just code. Otherwise our list of attributes would be 
incomplete.

@aaron.ballman, I think you should have another look. Sorry for missing that in 
my first patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87064

Files:
  clang/docs/ThreadSafetyAnalysis.rst
  clang/test/SemaCXX/thread-safety-annotations.h


Index: clang/test/SemaCXX/thread-safety-annotations.h
===
--- clang/test/SemaCXX/thread-safety-annotations.h
+++ clang/test/SemaCXX/thread-safety-annotations.h
@@ -6,6 +6,7 @@
 #define ASSERT_SHARED_LOCK(...) 
__attribute__((assert_shared_capability(__VA_ARGS__)))
 #define EXCLUSIVE_LOCK_FUNCTION(...)
__attribute__((acquire_capability(__VA_ARGS__)))
 #define SHARED_LOCK_FUNCTION(...)   
__attribute__((acquire_shared_capability(__VA_ARGS__)))
+#define UNLOCK_FUNCTION(...)
__attribute__((release_generic_capability(__VA_ARGS__)))
 #define EXCLUSIVE_TRYLOCK_FUNCTION(...) 
__attribute__((try_acquire_capability(__VA_ARGS__)))
 #define SHARED_TRYLOCK_FUNCTION(...)
__attribute__((try_acquire_shared_capability(__VA_ARGS__)))
 #define EXCLUSIVE_LOCKS_REQUIRED(...)   
__attribute__((requires_capability(__VA_ARGS__)))
@@ -16,6 +17,7 @@
 #define ASSERT_SHARED_LOCK(...) 
__attribute__((assert_shared_lock(__VA_ARGS__)))
 #define EXCLUSIVE_LOCK_FUNCTION(...)
__attribute__((exclusive_lock_function(__VA_ARGS__)))
 #define SHARED_LOCK_FUNCTION(...)   
__attribute__((shared_lock_function(__VA_ARGS__)))
+#define UNLOCK_FUNCTION(...)
__attribute__((unlock_function(__VA_ARGS__)))
 #define EXCLUSIVE_TRYLOCK_FUNCTION(...) 
__attribute__((exclusive_trylock_function(__VA_ARGS__)))
 #define SHARED_TRYLOCK_FUNCTION(...)
__attribute__((shared_trylock_function(__VA_ARGS__)))
 #define EXCLUSIVE_LOCKS_REQUIRED(...)   
__attribute__((exclusive_locks_required(__VA_ARGS__)))
@@ -23,7 +25,6 @@
 #endif
 
 // Lock semantics only
-#define UNLOCK_FUNCTION(...)
__attribute__((unlock_function(__VA_ARGS__)))
 #define GUARDED_VAR __attribute__((guarded_var))
 #define PT_GUARDED_VAR  __attribute__((pt_guarded_var))
 
Index: clang/docs/ThreadSafetyAnalysis.rst
===
--- clang/docs/ThreadSafetyAnalysis.rst
+++ clang/docs/ThreadSafetyAnalysis.rst
@@ -209,21 +209,21 @@
   }
 
 
-ACQUIRE(...), ACQUIRE_SHARED(...), RELEASE(...), RELEASE_SHARED(...)
-
+ACQUIRE(...), ACQUIRE_SHARED(...), RELEASE(...), RELEASE_SHARED(...), 
RELEASE_GENERIC(...)
+--
 
 *Previously*: ``EXCLUSIVE_LOCK_FUNCTION``, ``SHARED_LOCK_FUNCTION``,
 ``UNLOCK_FUNCTION``
 
-``ACQUIRE`` is an attribute on functions or methods, which
-declares that the function acquires a capability, but does not release it.  The
-caller must not hold the given capability on entry, and it will hold the
-capability on exit.  ``ACQUIRE_SHARED`` is similar.
+``ACQUIRE`` and ``ACQUIRE_SHARED`` are attributes on functions or methods
+declaring that the function acquires a capability, but does not release it.
+The given capability must not be held on entry, and will be held on exit
+(exclusively for ``ACQUIRE``, shared for ``ACQUIRE_SHARED``).
 
-``RELEASE`` and ``RELEASE_SHARED`` declare that the function releases the given
-capability.  The caller must hold the capability on entry, and will no longer
-hold it on exit. It does not matter whether the given capability is shared or
-exclusive.
+``RELEASE``, ``RELEASE_SHARED``, and ``RELEASE_GENERIC`` declare that the
+function releases the given capability.  The capability must be held on entry
+(exclusively for ``RELEASE``, shared for ``RELEASE_SHARED``, exclusively or
+shared for ``RELEASE_GENERIC``), and will no longer be held on exit.
 
 .. code-block:: c++
 
@@ -800,6 +800,9 @@
   #define RELEASE_SHARED(...) \
 THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
 
+  #define RELEASE_GENERIC(...) \
+THREAD_ANNOTATION_ATTRIBUTE__(release_generic_capability(__VA_ARGS__))
+
   #define TRY_ACQUIRE(...) \
 THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
 
@@ -844,6 +847,9 @@
 // Release/unlock a shared mutex.
 void ReaderUnlock() RELEASE_SHARED();
 
+// Generic unlock, can unlock exclusive and shared mutexes.
+void GenericUnlock() RELEASE_GENERIC();
+
 // Try to acquire the mutex.  Returns true on success, and false on 
failure.
 bool TryLock() TRY_ACQUIRE(true);
 


Index: clang/test/SemaCXX/thread-safety-annotations.h
===
--- clang/test/SemaCXX/thread-sa

[clang] 2d65294 - [PowerPC] Provide vec_cmpne on pre-Power9 architectures in altivec.h

2020-09-04 Thread Nemanja Ivanovic via cfe-commits

Author: Nemanja Ivanovic
Date: 2020-09-04T21:48:38-04:00
New Revision: 2d652949be4b772f2c11577621b0ad33052ac844

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

LOG: [PowerPC] Provide vec_cmpne on pre-Power9 architectures in altivec.h

These overloads are listed in appendix A of the ELFv2 ABI specification
without a requirement for ISA 3.0. So these need to be available on
all Altivec-capable architectures. The implementation in altivec.h
erroneously had them guarded for Power9 due to the availability of
the VCMPNE[BHW] instructions. However these need to be implemented
in terms of the VCMPEQ[BHW] instructions on older architectures.

Fixes: https://bugs.llvm.org/show_bug.cgi?id=47423

Added: 


Modified: 
clang/lib/Headers/altivec.h
clang/test/CodeGen/builtins-ppc-altivec.c

Removed: 




diff  --git a/clang/lib/Headers/altivec.h b/clang/lib/Headers/altivec.h
index 9fda383074f6..a7c4fd23ef19 100644
--- a/clang/lib/Headers/altivec.h
+++ b/clang/lib/Headers/altivec.h
@@ -1766,36 +1766,12 @@ vec_cmpne(vector unsigned int __a, vector unsigned int 
__b) {
 (vector int)__b);
 }
 
-static __inline__ vector bool long long __ATTRS_o_ai
-vec_cmpne(vector bool long long __a, vector bool long long __b) {
-  return (vector bool long long)
-~(__builtin_altivec_vcmpequd((vector long long)__a, (vector long 
long)__b));
-}
-
-static __inline__ vector bool long long __ATTRS_o_ai
-vec_cmpne(vector signed long long __a, vector signed long long __b) {
-  return (vector bool long long)
-~(__builtin_altivec_vcmpequd((vector long long)__a, (vector long 
long)__b));
-}
-
-static __inline__ vector bool long long __ATTRS_o_ai
-vec_cmpne(vector unsigned long long __a, vector unsigned long long __b) {
-  return (vector bool long long)
-~(__builtin_altivec_vcmpequd((vector long long)__a, (vector long 
long)__b));
-}
-
 static __inline__ vector bool int __ATTRS_o_ai
 vec_cmpne(vector float __a, vector float __b) {
   return (vector bool int)__builtin_altivec_vcmpnew((vector int)__a,
 (vector int)__b);
 }
 
-static __inline__ vector bool long long __ATTRS_o_ai
-vec_cmpne(vector double __a, vector double __b) {
-  return (vector bool long long)
-~(__builtin_altivec_vcmpequd((vector long long)__a, (vector long 
long)__b));
-}
-
 /* vec_cmpnez */
 
 static __inline__ vector bool char __ATTRS_o_ai
@@ -1900,6 +1876,86 @@ vec_parity_lsbb(vector signed long long __a) {
   return __builtin_altivec_vprtybd(__a);
 }
 
+#else
+/* vec_cmpne */
+
+static __inline__ vector bool char __ATTRS_o_ai
+vec_cmpne(vector bool char __a, vector bool char __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+
+static __inline__ vector bool char __ATTRS_o_ai
+vec_cmpne(vector signed char __a, vector signed char __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+
+static __inline__ vector bool char __ATTRS_o_ai
+vec_cmpne(vector unsigned char __a, vector unsigned char __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+
+static __inline__ vector bool short __ATTRS_o_ai
+vec_cmpne(vector bool short __a, vector bool short __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+
+static __inline__ vector bool short __ATTRS_o_ai
+vec_cmpne(vector signed short __a, vector signed short __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+
+static __inline__ vector bool short __ATTRS_o_ai
+vec_cmpne(vector unsigned short __a, vector unsigned short __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+
+static __inline__ vector bool int __ATTRS_o_ai
+vec_cmpne(vector bool int __a, vector bool int __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+
+static __inline__ vector bool int __ATTRS_o_ai
+vec_cmpne(vector signed int __a, vector signed int __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+
+static __inline__ vector bool int __ATTRS_o_ai
+vec_cmpne(vector unsigned int __a, vector unsigned int __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+
+static __inline__ vector bool int __ATTRS_o_ai
+vec_cmpne(vector float __a, vector float __b) {
+  return ~(vec_cmpeq(__a, __b));
+}
+#endif
+
+#ifdef __POWER8_VECTOR__
+static __inline__ vector bool long long __ATTRS_o_ai
+vec_cmpne(vector bool long long __a, vector bool long long __b) {
+  return (vector bool long long)
+~(__builtin_altivec_vcmpequd((vector long long)__a, (vector long 
long)__b));
+}
+
+static __inline__ vector bool long long __ATTRS_o_ai
+vec_cmpne(vector signed long long __a, vector signed long long __b) {
+  return (vector bool long long)
+~(__builtin_altivec_vcmpequd((vector long long)__a, (vector long 
long)__b));
+}
+
+static __inline__ vector bool long long __ATTRS_o_ai
+vec_cmpne(vector unsigned long long __a, vector unsigned long long __b) {
+  return (vector bool long long)
+~(__builtin_altivec_vcmpe