[PATCH] D114312: libfuzzer: Disable broken tests for arm

2021-11-19 Thread Manoj Gupta via Phabricator via cfe-commits
manojgupta created this revision.
manojgupta added reviewers: morehouse, metzman.
Herald added a subscriber: kristof.beyls.
manojgupta requested review of this revision.
Herald added a project: Sanitizers.
Herald added a subscriber: Sanitizers.

libfuzzer was recently enabled for Arm32 in D112091 
.
A few tests apparently do not work with arm32 so disable them.
The list of tests was obtained from
https://lab.llvm.org/buildbot/#/builders/190/builds/513


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114312

Files:
  compiler-rt/test/fuzzer/acquire-crash-state.test
  compiler-rt/test/fuzzer/compressed.test
  compiler-rt/test/fuzzer/msan-custom-mutator.test
  compiler-rt/test/fuzzer/msan-param-unpoison.test
  compiler-rt/test/fuzzer/msan.test
  compiler-rt/test/fuzzer/sigint.test
  compiler-rt/test/fuzzer/value-profile-div.test


Index: compiler-rt/test/fuzzer/value-profile-div.test
===
--- compiler-rt/test/fuzzer/value-profile-div.test
+++ compiler-rt/test/fuzzer/value-profile-div.test
@@ -1,5 +1,5 @@
 UNSUPPORTED: ios
-UNSUPPORTED: aarch64
+UNSUPPORTED: arm, aarch64
 CHECK: AddressSanitizer: {{FPE|int-divide-by-zero}}
 RUN: %cpp_compiler %S/DivTest.cpp -fsanitize-coverage=trace-div -o %t-DivTest
 RUN: not %run %t-DivTest -seed=1 -use_value_profile=1 -runs=1000 2>&1 | 
FileCheck %s
Index: compiler-rt/test/fuzzer/sigint.test
===
--- compiler-rt/test/fuzzer/sigint.test
+++ compiler-rt/test/fuzzer/sigint.test
@@ -1,4 +1,5 @@
 REQUIRES: msan
+UNSUPPORTED: arm
 
 # Check that libFuzzer exits gracefully under SIGINT with MSan.
 RUN: rm -rf %t
Index: compiler-rt/test/fuzzer/msan.test
===
--- compiler-rt/test/fuzzer/msan.test
+++ compiler-rt/test/fuzzer/msan.test
@@ -1,4 +1,5 @@
 REQUIRES: msan
+UNSUPPORTED: arm
 RUN: %msan_compiler %S/SimpleTestStdio.cpp -o %t
 RUN: not %run %t -seed=1 -runs=1000 2>&1 | FileCheck %s 
--check-prefix=NO-REPORT
 
Index: compiler-rt/test/fuzzer/msan-param-unpoison.test
===
--- compiler-rt/test/fuzzer/msan-param-unpoison.test
+++ compiler-rt/test/fuzzer/msan-param-unpoison.test
@@ -1,4 +1,5 @@
 REQUIRES: msan
+UNSUPPORTED: arm
 RUN: %msan_compiler %S/MsanParamUnpoison.cpp -o %t
 RUN: %run %t -seed=1 -runs=1000 2>&1 | FileCheck %s
 
Index: compiler-rt/test/fuzzer/msan-custom-mutator.test
===
--- compiler-rt/test/fuzzer/msan-custom-mutator.test
+++ compiler-rt/test/fuzzer/msan-custom-mutator.test
@@ -1,4 +1,5 @@
 REQUIRES: msan
+UNSUPPORTED: arm
 RUN: %msan_compiler %S/MsanCustomMutator.cpp -o %t
 RUN: %run %t -seed=1 -runs=1000 2>&1 | FileCheck %s
 
Index: compiler-rt/test/fuzzer/compressed.test
===
--- compiler-rt/test/fuzzer/compressed.test
+++ compiler-rt/test/fuzzer/compressed.test
@@ -2,7 +2,7 @@
 REQUIRES: zlib
 # zlib is "supported" on i386 even when only for x86_64, explicitly make i386
 # unsupported by this test.
-UNSUPPORTED: i386
+UNSUPPORTED: i386, arm
 # Custom mutator should find this bug, w/o custom -- no chance.
 RUN: %cpp_compiler %S/CompressedTest.cpp -o %t-CompressedTestCustom 
-DCUSTOM_MUTATOR -lz
 RUN: %cpp_compiler %S/CompressedTest.cpp -o %t-CompressedTestPlain -lz
Index: compiler-rt/test/fuzzer/acquire-crash-state.test
===
--- compiler-rt/test/fuzzer/acquire-crash-state.test
+++ compiler-rt/test/fuzzer/acquire-crash-state.test
@@ -1,3 +1,4 @@
+UNSUPPORTED: arm
 RUN: %cpp_compiler %S/AcquireCrashStateTest.cpp -o %t
 RUN: %run %t 2>&1 | FileCheck %s
 CHECK-NOT: fuzz target exited


Index: compiler-rt/test/fuzzer/value-profile-div.test
===
--- compiler-rt/test/fuzzer/value-profile-div.test
+++ compiler-rt/test/fuzzer/value-profile-div.test
@@ -1,5 +1,5 @@
 UNSUPPORTED: ios
-UNSUPPORTED: aarch64
+UNSUPPORTED: arm, aarch64
 CHECK: AddressSanitizer: {{FPE|int-divide-by-zero}}
 RUN: %cpp_compiler %S/DivTest.cpp -fsanitize-coverage=trace-div -o %t-DivTest
 RUN: not %run %t-DivTest -seed=1 -use_value_profile=1 -runs=1000 2>&1 | FileCheck %s
Index: compiler-rt/test/fuzzer/sigint.test
===
--- compiler-rt/test/fuzzer/sigint.test
+++ compiler-rt/test/fuzzer/sigint.test
@@ -1,4 +1,5 @@
 REQUIRES: msan
+UNSUPPORTED: arm
 
 # Check that libFuzzer exits gracefully under SIGINT with MSan.
 RUN: rm -rf %t
Index: compiler-rt/test/fuzzer/msan.test
===
--- compiler-rt/test/fuzzer/msan.test
+++ compiler-rt/test/fuzzer/msan.test
@@ -1,4 +1,5 @@
 REQUIRES: msan
+UNSUPPORTED: arm
 RUN: 

[PATCH] D114251: [AST] Add a sugar type for types found via UsingDecl

2021-11-19 Thread David Rector via Phabricator via cfe-commits
davrec added a comment.

Looks good, a few notes.




Comment at: clang/include/clang/AST/ASTContext.h:1559
 
+  QualType getUsingType(const NamedDecl *Found, QualType Underlying) const;
+

I believe you mentioned ObjC considerations might require expanding beyond 
UsingShadowDecl as the type of `Found` -- is that why this is a generic 
NamedDecl?  I.e. can `Found` indeed be other things than a UsingShadowDecl?



Comment at: clang/include/clang/AST/RecursiveASTVisitor.h:984
 
+DEF_TRAVERSE_TYPE(UsingType, { TRY_TO(TraverseType(T->getUnderlyingType())); })
 DEF_TRAVERSE_TYPE(UnresolvedUsingType, {})

This should just be DEF_TRAVERSE_TYPE(UsingType, {}), i.e. same as for 
TypedefType -- RecursiveASTVisitor only visits the child nodes, to avoid 
retraversal of any nodes; by traversing the desugared node this would jump back 
to a node it probably already traversed.



Comment at: clang/include/clang/AST/RecursiveASTVisitor.h:1256
 
+DEF_TRAVERSE_TYPELOC(UsingType,
+ { TRY_TO(TraverseTypeLoc(TL.getUnderlyingLoc())); })

DEF_TRAVERSE_TYPELOC(UsingType, {})



Comment at: clang/include/clang/AST/Type.h:4381
+public:
+  NamedDecl *getFoundDecl() const { return Found; }
+  QualType getUnderlyingType() const { return UnderlyingTy; }

 I would rename this to `getDecl()`, to match the interface for other types 
that just wrap a decl.  E.g. if something is a RecordType I know I can call 
getDecl() to get the RecordDecl; likewise a TypedefType::getDecl() returns a 
TypedefNameDecl; I think it would follow this pattern for UsingType to have a 
getDecl() method that returns a UsingShadowDecl (or whatever else it can be, 
per other question).




Comment at: clang/include/clang/AST/TypeLoc.h:671
+/// Wrapper for source info for types used via transparent aliases.
+class UsingTypeLoc : public ConcreteTypeLoc {

Should this be analogous to TypedefTypeLoc, with base as
```
 InheritingConcreteTypeLoc
```
?



Comment at: clang/include/clang/AST/TypeProperties.td:366
+let Class = UsingType in {
+  def : Property<"foundDeclaration", NamedDeclRef> {
+let Read = [{ node->getFoundDecl() }];

Rename to "declaration" iff renaming UsingType::getFoundDecl to 
UsingType::getDecl



Comment at: clang/lib/AST/ASTContext.cpp:4612
+Canon = getCanonicalType(Underlying);
+  UsingType *NewType = new UsingType(Found, Underlying, Canon);
+  Types.push_back(NewType);

UsingType *NewType = new (*this, TypeAlignment) UsingType(Found, Underlying, 
Canon)



Comment at: clang/lib/AST/ASTStructuralEquivalence.cpp:952
+  return false;
+if (!IsStructurallyEquivalent(Context,
+  cast(T1)->getUnderlyingType(),

Is there a good reason this checks the underlying type in addition to 
getFoundDecl()? I'm looking at the Typedef case below and it only checks the 
decl, does this need to be different from that?



Comment at: clang/lib/AST/Type.cpp:1819
 
+Type *VisitUsingType(const UsingType *T) {
+  return Visit(T->getUnderlyingType());

Do we need this here?  I ask because I mainly because don't see a 
VisitTypedefType, not 100% sure what this class does though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114251

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


[PATCH] D114249: [clang-tidy] performance-unnecessary-copy-initialization: Fix false negative.

2021-11-19 Thread Felix Berger via Phabricator via cfe-commits
flx added a comment.

Thank you for catching and fixing this!




Comment at: 
clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp:97
+  cxxOperatorCallExpr(callee(MethodDecl), hasArgument(0, ReceiverExpr),
+  hasArgument(0, hasType(recordType(hasDeclaration(
+ ReceiverTypeDecl)));

Does this work if if the object argument is a pointer or a type alias? Could 
you add a test to confirm?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114249

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


[PATCH] D107944: [hmaptool] Port to python3

2021-11-19 Thread Nathan Lanza via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1bd4dc4f2854: [hmaptool] Port to python3 (authored by lanza).

Changed prior to commit:
  https://reviews.llvm.org/D107944?vs=388568=388668#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107944

Files:
  clang/utils/hmaptool/hmaptool


Index: clang/utils/hmaptool/hmaptool
===
--- clang/utils/hmaptool/hmaptool
+++ clang/utils/hmaptool/hmaptool
@@ -1,6 +1,7 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 from __future__ import absolute_import, division, print_function
 
+from ctypes import ArgumentError
 import json
 import optparse
 import os
@@ -9,8 +10,8 @@
 
 ###
 
-k_header_magic_LE = 'pamh'
-k_header_magic_BE = 'hmap'
+k_header_magic_LE = b'pamh'
+k_header_magic_BE = b'hmap'
 
 def hmap_hash(str):
 """hash(str) -> int
@@ -43,7 +44,7 @@
 path,))
 
 (version, reserved, strtable_offset, num_entries,
- num_buckets, max_value_len) = struct.unpack(header_fmt, data)
+ num_buckets) = struct.unpack(header_fmt, data)
 
 if version != 1:
 raise SystemExit("error: %s: unknown headermap version: %r" % (
@@ -83,7 +84,7 @@
 if len(strtable) != strtable_size:
 raise SystemExit("error: %s: unable to read complete string 
table"%(
 path,))
-if strtable[-1] != '\0':
+if strtable[-1] != 0:
 raise SystemExit("error: %s: invalid string table in 
headermap" % (
 path,))
 
@@ -97,8 +98,8 @@
 def get_string(self, idx):
 if idx >= len(self.strtable):
 raise SystemExit("error: %s: invalid string index" % (
-path,))
-end_idx = self.strtable.index('\0', idx)
+idx,))
+end_idx = self.strtable.index(0, idx)
 return self.strtable[idx:end_idx]
 
 @property
@@ -220,7 +221,7 @@
 
 # Write out the headermap.
 with open(output_path, 'wb') as f:
-f.write(magic.encode())
+f.write(magic)
 f.write(struct.pack(header_fmt, *header))
 for bucket in table:
 f.write(struct.pack(bucket_fmt, *bucket))


Index: clang/utils/hmaptool/hmaptool
===
--- clang/utils/hmaptool/hmaptool
+++ clang/utils/hmaptool/hmaptool
@@ -1,6 +1,7 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 from __future__ import absolute_import, division, print_function
 
+from ctypes import ArgumentError
 import json
 import optparse
 import os
@@ -9,8 +10,8 @@
 
 ###
 
-k_header_magic_LE = 'pamh'
-k_header_magic_BE = 'hmap'
+k_header_magic_LE = b'pamh'
+k_header_magic_BE = b'hmap'
 
 def hmap_hash(str):
 """hash(str) -> int
@@ -43,7 +44,7 @@
 path,))
 
 (version, reserved, strtable_offset, num_entries,
- num_buckets, max_value_len) = struct.unpack(header_fmt, data)
+ num_buckets) = struct.unpack(header_fmt, data)
 
 if version != 1:
 raise SystemExit("error: %s: unknown headermap version: %r" % (
@@ -83,7 +84,7 @@
 if len(strtable) != strtable_size:
 raise SystemExit("error: %s: unable to read complete string table"%(
 path,))
-if strtable[-1] != '\0':
+if strtable[-1] != 0:
 raise SystemExit("error: %s: invalid string table in headermap" % (
 path,))
 
@@ -97,8 +98,8 @@
 def get_string(self, idx):
 if idx >= len(self.strtable):
 raise SystemExit("error: %s: invalid string index" % (
-path,))
-end_idx = self.strtable.index('\0', idx)
+idx,))
+end_idx = self.strtable.index(0, idx)
 return self.strtable[idx:end_idx]
 
 @property
@@ -220,7 +221,7 @@
 
 # Write out the headermap.
 with open(output_path, 'wb') as f:
-f.write(magic.encode())
+f.write(magic)
 f.write(struct.pack(header_fmt, *header))
 for bucket in table:
 f.write(struct.pack(bucket_fmt, *bucket))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1bd4dc4 - [hmaptool] Port to python3

2021-11-19 Thread Nathan Lanza via cfe-commits

Author: Nathan Lanza
Date: 2021-11-19T19:25:31-05:00
New Revision: 1bd4dc4f2854edf3035732416ec7e4adbddaf982

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

LOG: [hmaptool] Port to python3

This is just a few trivial changes -- change the interpreter and fix a
few byte-vs-string issues.

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

Added: 


Modified: 
clang/utils/hmaptool/hmaptool

Removed: 




diff  --git a/clang/utils/hmaptool/hmaptool b/clang/utils/hmaptool/hmaptool
index e647cde6bc46a..7949002020489 100755
--- a/clang/utils/hmaptool/hmaptool
+++ b/clang/utils/hmaptool/hmaptool
@@ -1,6 +1,7 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 from __future__ import absolute_import, division, print_function
 
+from ctypes import ArgumentError
 import json
 import optparse
 import os
@@ -9,8 +10,8 @@ import sys
 
 ###
 
-k_header_magic_LE = 'pamh'
-k_header_magic_BE = 'hmap'
+k_header_magic_LE = b'pamh'
+k_header_magic_BE = b'hmap'
 
 def hmap_hash(str):
 """hash(str) -> int
@@ -43,7 +44,7 @@ class HeaderMap(object):
 path,))
 
 (version, reserved, strtable_offset, num_entries,
- num_buckets, max_value_len) = struct.unpack(header_fmt, data)
+ num_buckets) = struct.unpack(header_fmt, data)
 
 if version != 1:
 raise SystemExit("error: %s: unknown headermap version: %r" % (
@@ -83,7 +84,7 @@ class HeaderMap(object):
 if len(strtable) != strtable_size:
 raise SystemExit("error: %s: unable to read complete string 
table"%(
 path,))
-if strtable[-1] != '\0':
+if strtable[-1] != 0:
 raise SystemExit("error: %s: invalid string table in 
headermap" % (
 path,))
 
@@ -97,8 +98,8 @@ class HeaderMap(object):
 def get_string(self, idx):
 if idx >= len(self.strtable):
 raise SystemExit("error: %s: invalid string index" % (
-path,))
-end_idx = self.strtable.index('\0', idx)
+idx,))
+end_idx = self.strtable.index(0, idx)
 return self.strtable[idx:end_idx]
 
 @property
@@ -220,7 +221,7 @@ def action_write(name, args):
 
 # Write out the headermap.
 with open(output_path, 'wb') as f:
-f.write(magic.encode())
+f.write(magic)
 f.write(struct.pack(header_fmt, *header))
 for bucket in table:
 f.write(struct.pack(bucket_fmt, *bucket))



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


[PATCH] D114299: [clang-tidy] Fix `readability-redundant-declaration` false positive for template friend declaration

2021-11-19 Thread Fabian Wolff via Phabricator via cfe-commits
fwolff created this revision.
fwolff added reviewers: Eugene.Zelenko, alexfh, Szelethus.
fwolff added a project: clang-tools-extra.
Herald added subscribers: carlosgalvezp, xazax.hun.
fwolff requested review of this revision.
Herald added a subscriber: cfe-commits.

Fixes PR#48086 . The problem is 
that the current matcher uses `hasParent()` to detect friend declarations, but 
for a template friend declaration, the immediate parent of the `FunctionDecl` 
is a `FunctionTemplateDecl`, not the `FriendDecl`. Therefore, I have replaced 
the matcher with `hasAncestor()`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114299

Files:
  clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
@@ -66,8 +66,14 @@
 struct Friendly {
   friend void best_friend();
   friend void enemy();
+
+  template 
+  friend void generic_friend();
 };
 
+template 
+void generic_friend() {}
+
 void enemy();
 
 namespace macros {
Index: clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp
@@ -37,7 +37,7 @@
   functionDecl(unless(anyOf(
   isDefinition(), isDefaulted(),
   doesDeclarationForceExternallyVisibleDefinition(),
-  hasParent(friendDecl()))
+  hasAncestor(friendDecl()))
   .bind("Decl"),
   this);
 }


Index: clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
@@ -66,8 +66,14 @@
 struct Friendly {
   friend void best_friend();
   friend void enemy();
+
+  template 
+  friend void generic_friend();
 };
 
+template 
+void generic_friend() {}
+
 void enemy();
 
 namespace macros {
Index: clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp
@@ -37,7 +37,7 @@
   functionDecl(unless(anyOf(
   isDefinition(), isDefaulted(),
   doesDeclarationForceExternallyVisibleDefinition(),
-  hasParent(friendDecl()))
+  hasAncestor(friendDecl()))
   .bind("Decl"),
   this);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] f764a1a - [clangd] Avoid possible crash: apply configuration after binding methods

2021-11-19 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-11-20T01:13:38+01:00
New Revision: f764a1a5bd7c281d3d7cc3c6d7f1430711176762

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

LOG: [clangd] Avoid possible crash: apply configuration after binding methods

The configuration may kick off indexing, which may involve sending LSP
messages.
The crash is fiddly to reproduce in a hermetic test (we need background
indexing on without disk storage, and to handle server->client messages
in LSPClient...)

Fixes https://github.com/clangd/clangd/issues/926

Added: 


Modified: 
clang-tools-extra/clangd/ClangdLSPServer.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 6c000d3290fda..762ca1aa213a4 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -493,7 +493,6 @@ void ClangdLSPServer::onInitialize(const InitializeParams 
,
 Server.emplace(*CDB, TFS, Opts,
static_cast(this));
   }
-  applyConfiguration(Params.initializationOptions.ConfigSettings);
 
   Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets;
   Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes;
@@ -627,6 +626,10 @@ void ClangdLSPServer::onInitialize(const InitializeParams 
,
   if (Opts.Encoding)
 Result["offsetEncoding"] = *Opts.Encoding;
   Reply(std::move(Result));
+
+  // Apply settings after we're fully initialized.
+  // This can start background indexing and in turn trigger LSP notifications.
+  applyConfiguration(Params.initializationOptions.ConfigSettings);
 }
 
 void ClangdLSPServer::onInitialized(const InitializedParams ) {}



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


[PATCH] D114268: [InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment

2021-11-19 Thread Kyungwoo Lee 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 rGde11de308b64: [InstrProf] Use i32 for GEP index from 
lowering llvm.instrprof.increment (authored by ellis, committed by kyulee).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114268

Files:
  clang/test/CodeGen/profile-filter.c
  clang/test/Profile/branch-logical-mixed.cpp
  clang/test/Profile/c-captured.c
  clang/test/Profile/c-general.c
  clang/test/Profile/c-ternary.c
  clang/test/Profile/cxx-class.cpp
  clang/test/Profile/cxx-lambda.cpp
  clang/test/Profile/cxx-rangefor.cpp
  clang/test/Profile/cxx-stmt-initializers.cpp
  clang/test/Profile/cxx-templates.cpp
  clang/test/Profile/cxx-throws.cpp
  clang/test/Profile/objc-general.m
  llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
  llvm/test/Instrumentation/InstrProfiling/atomic-updates.ll
  llvm/test/Instrumentation/InstrProfiling/runtime-counter-relocation.ll
  llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
  llvm/test/Transforms/PGOProfile/instr_entry_bb.ll

Index: llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
===
--- llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
+++ llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
@@ -18,7 +18,7 @@
 ; GEN: entry:
 ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__profn_test_br_2, i32 0, i32 0), i64 {{[0-9]+}}, i32 2, i32 0)
 ; GENA: entry:
-; GENA: %{{[0-9+]}} = atomicrmw add i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 0), i64 1 monotonic
+; GENA: %{{[0-9+]}} = atomicrmw add i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 0), i64 1 monotonic
 ; USE: br i1 %cmp, label %if.then, label %if.else
 ; USE-SAME: !prof ![[BW_ENTRY:[0-9]+]]
 ; USE: ![[BW_ENTRY]] = !{!"branch_weights", i32 0, i32 1}
@@ -35,9 +35,9 @@
 ; GEN: if.else:
 ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__profn_test_br_2, i32 0, i32 0), i64 {{[0-9]+}}, i32 2, i32 1)
 ; GENA: if.else:
-; GENA:  %pgocount = load i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 1), align 8
+; GENA:  %pgocount = load i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 1), align 8
 ; GENA:  [[V:%[0-9]*]] = add i64 %pgocount, 1
-; GENA:  store i64 [[V]], i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 1), align 8
+; GENA:  store i64 [[V]], i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 1), align 8
   %sub = sub nsw i32 %i, 2
   br label %if.end
 
Index: llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
===
--- llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
+++ llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
@@ -38,11 +38,11 @@
 
 for.body: ; preds = %for.cond
 ; CHECK: for.body:
-; NOTENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 0)
-; TENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
+; NOTENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 0)
+; TENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
 ; CHECK: %1 = add i64 %pgocount1, 1
-; NOTENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 0)
-; ENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
+; NOTENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 0)
+; ENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
   %idxprom = zext i32 %i.0 to i64
   %arrayidx = getelementptr inbounds [200 x i8], [200 x i8]* @"?buffer@@3PADA", i64 0, i64 %idxprom
   %0 = load i8, i8* %arrayidx, align 1
@@ -55,11 +55,11 @@
 
 for.inc:  ; preds = %if.end
 ; CHECK: for.inc:
-; NOTENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
-; ENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 2)
+; NOTENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
+; ENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* 

[clang] de11de3 - [InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment

2021-11-19 Thread Kyungwoo Lee via cfe-commits

Author: Ellis Hoag
Date: 2021-11-19T15:45:14-08:00
New Revision: de11de308b6480fc35d901c7104f46918674418c

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

LOG: [InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment

The `llvm.instrprof.increment` intrinsic uses `i32` for the index. We should 
use this same type for the index into the GEP instructions.

Reviewed By: MaskRay

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

Added: 


Modified: 
clang/test/CodeGen/profile-filter.c
clang/test/Profile/branch-logical-mixed.cpp
clang/test/Profile/c-captured.c
clang/test/Profile/c-general.c
clang/test/Profile/c-ternary.c
clang/test/Profile/cxx-class.cpp
clang/test/Profile/cxx-lambda.cpp
clang/test/Profile/cxx-rangefor.cpp
clang/test/Profile/cxx-stmt-initializers.cpp
clang/test/Profile/cxx-templates.cpp
clang/test/Profile/cxx-throws.cpp
clang/test/Profile/objc-general.m
llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
llvm/test/Instrumentation/InstrProfiling/atomic-updates.ll
llvm/test/Instrumentation/InstrProfiling/runtime-counter-relocation.ll
llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
llvm/test/Transforms/PGOProfile/instr_entry_bb.ll

Removed: 




diff  --git a/clang/test/CodeGen/profile-filter.c 
b/clang/test/CodeGen/profile-filter.c
index d39097076fc9c..5d71657f8f2d7 100644
--- a/clang/test/CodeGen/profile-filter.c
+++ b/clang/test/CodeGen/profile-filter.c
@@ -37,11 +37,11 @@ unsigned i;
 // EXCLUDE: noprofile
 // EXCLUDE: @test1
 unsigned test1() {
-  // CHECK: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test1, i64 0, i64 0)
-  // FUNC: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test1, i64 0, i64 0)
-  // FILE: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test1, i64 0, i64 0)
-  // SECTION-NOT: %pgocount = load i64, i64* getelementptr inbounds ([1 x 
i64], [1 x i64]* @__profc_test1, i64 0, i64 0)
-  // EXCLUDE-NOT: %pgocount = load i64, i64* getelementptr inbounds ([1 x 
i64], [1 x i64]* @__profc_test1, i64 0, i64 0)
+  // CHECK: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test1, i32 0, i32 0)
+  // FUNC: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test1, i32 0, i32 0)
+  // FILE: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test1, i32 0, i32 0)
+  // SECTION-NOT: %pgocount = load i64, i64* getelementptr inbounds ([1 x 
i64], [1 x i64]* @__profc_test1, i32 0, i32 0)
+  // EXCLUDE-NOT: %pgocount = load i64, i64* getelementptr inbounds ([1 x 
i64], [1 x i64]* @__profc_test1, i32 0, i32 0)
   return i + 1;
 }
 
@@ -56,10 +56,10 @@ unsigned test1() {
 // EXCLUDE-NOT: noprofile
 // EXCLUDE: @test2
 unsigned test2() {
-  // CHECK: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test2, i64 0, i64 0)
-  // FUNC-NOT: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], 
[1 x i64]* @__profc_test2, i64 0, i64 0)
-  // FILE: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test2, i64 0, i64 0)
-  // SECTION: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 
x i64]* @__profc_test2, i64 0, i64 0)
-  // EXCLUDE: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 
x i64]* @__profc_test2, i64 0, i64 0)
+  // CHECK: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test2, i32 0, i32 0)
+  // FUNC-NOT: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], 
[1 x i64]* @__profc_test2, i32 0, i32 0)
+  // FILE: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 x 
i64]* @__profc_test2, i32 0, i32 0)
+  // SECTION: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 
x i64]* @__profc_test2, i32 0, i32 0)
+  // EXCLUDE: %pgocount = load i64, i64* getelementptr inbounds ([1 x i64], [1 
x i64]* @__profc_test2, i32 0, i32 0)
   return i - 1;
 }

diff  --git a/clang/test/Profile/branch-logical-mixed.cpp 
b/clang/test/Profile/branch-logical-mixed.cpp
index 04b51d81d13bd..cdcee76c3d0cf 100644
--- a/clang/test/Profile/branch-logical-mixed.cpp
+++ b/clang/test/Profile/branch-logical-mixed.cpp
@@ -23,44 +23,44 @@ bool func() {
   bool bf5 = false;
 
   bool a = bt0 &&
-   bf0 &&   // CHECK: store {{.*}} @[[FUNC]], i64 0, 
i64 10
-   bt1 &&   // CHECK: store {{.*}} @[[FUNC]], i64 0, 
i64 8
-   bf1 &&   // CHECK: store {{.*}} @[[FUNC]], i64 0, 
i64 6
-   bt2 &&   // CHECK: store {{.*}} @[[FUNC]], i64 

[PATCH] D114268: [InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment

2021-11-19 Thread Ellis Hoag via Phabricator via cfe-commits
ellis updated this revision to Diff 388652.
ellis added a comment.

Remove register names


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114268

Files:
  clang/test/CodeGen/profile-filter.c
  clang/test/Profile/branch-logical-mixed.cpp
  clang/test/Profile/c-captured.c
  clang/test/Profile/c-general.c
  clang/test/Profile/c-ternary.c
  clang/test/Profile/cxx-class.cpp
  clang/test/Profile/cxx-lambda.cpp
  clang/test/Profile/cxx-rangefor.cpp
  clang/test/Profile/cxx-stmt-initializers.cpp
  clang/test/Profile/cxx-templates.cpp
  clang/test/Profile/cxx-throws.cpp
  clang/test/Profile/objc-general.m
  llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
  llvm/test/Instrumentation/InstrProfiling/atomic-updates.ll
  llvm/test/Instrumentation/InstrProfiling/runtime-counter-relocation.ll
  llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
  llvm/test/Transforms/PGOProfile/instr_entry_bb.ll

Index: llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
===
--- llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
+++ llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
@@ -18,7 +18,7 @@
 ; GEN: entry:
 ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__profn_test_br_2, i32 0, i32 0), i64 {{[0-9]+}}, i32 2, i32 0)
 ; GENA: entry:
-; GENA: %{{[0-9+]}} = atomicrmw add i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 0), i64 1 monotonic
+; GENA: %{{[0-9+]}} = atomicrmw add i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 0), i64 1 monotonic
 ; USE: br i1 %cmp, label %if.then, label %if.else
 ; USE-SAME: !prof ![[BW_ENTRY:[0-9]+]]
 ; USE: ![[BW_ENTRY]] = !{!"branch_weights", i32 0, i32 1}
@@ -35,9 +35,9 @@
 ; GEN: if.else:
 ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__profn_test_br_2, i32 0, i32 0), i64 {{[0-9]+}}, i32 2, i32 1)
 ; GENA: if.else:
-; GENA:  %pgocount = load i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 1), align 8
+; GENA:  %pgocount = load i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 1), align 8
 ; GENA:  [[V:%[0-9]*]] = add i64 %pgocount, 1
-; GENA:  store i64 [[V]], i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 1), align 8
+; GENA:  store i64 [[V]], i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 1), align 8
   %sub = sub nsw i32 %i, 2
   br label %if.end
 
Index: llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
===
--- llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
+++ llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
@@ -38,11 +38,11 @@
 
 for.body: ; preds = %for.cond
 ; CHECK: for.body:
-; NOTENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 0)
-; TENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
+; NOTENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 0)
+; TENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
 ; CHECK: %1 = add i64 %pgocount1, 1
-; NOTENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 0)
-; ENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
+; NOTENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 0)
+; ENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
   %idxprom = zext i32 %i.0 to i64
   %arrayidx = getelementptr inbounds [200 x i8], [200 x i8]* @"?buffer@@3PADA", i64 0, i64 %idxprom
   %0 = load i8, i8* %arrayidx, align 1
@@ -55,11 +55,11 @@
 
 for.inc:  ; preds = %if.end
 ; CHECK: for.inc:
-; NOTENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
-; ENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 2)
+; NOTENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
+; ENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 2)
 ; CHECK: %3 = add i64 %pgocount2, 1
-; NOTENTRY: store i64 %3, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 

[PATCH] D107944: [hmaptool] Port to python3

2021-11-19 Thread Bruno Cardoso Lopes via Phabricator via cfe-commits
bruno accepted this revision.
bruno added a comment.
This revision is now accepted and ready to land.

LGTM!


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

https://reviews.llvm.org/D107944

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


[PATCH] D114292: [clang-tidy] Fix `altera-struct-pack-align` check for empty structs

2021-11-19 Thread Fabian Wolff via Phabricator via cfe-commits
fwolff created this revision.
fwolff added reviewers: alexfh, whisperity, hokein.
fwolff added a project: clang-tools-extra.
Herald added subscribers: carlosgalvezp, rnkovacs, xazax.hun.
fwolff requested review of this revision.
Herald added a subscriber: cfe-commits.

Fixes PR#51620 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114292

Files:
  clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align.cpp
@@ -99,3 +99,22 @@
   struct bad_align3 instantiated { 'a', 0.001, 'b' };
 }
 
+// Make sure that we don't recommend aligning an empty struct to zero bytes 
(PR#51620)
+struct StructWithNoFields {};
+
+struct ContainsStructWithNoFields {
+  StructWithNoFields s;
+};
+
+// Make sure that an empty struct is treated like "char" for padding and 
alignment purposes
+struct ContainsStructWithNoFields2 {
+  StructWithNoFields s;
+  double d;
+  StructWithNoFields t;
+};
+// CHECK-MESSAGES: :[[@LINE-5]]:8: warning: accessing fields in struct 
'ContainsStructWithNoFields2' is inefficient due to padding; only needs 10 
bytes but is using 24 bytes [altera-struct-pack-align]
+// CHECK-MESSAGES: :[[@LINE-6]]:8: note: use "__attribute__((packed))" to 
reduce the amount of padding applied to struct 'ContainsStructWithNoFields2'
+// CHECK-MESSAGES: :[[@LINE-7]]:8: warning: accessing fields in struct 
'ContainsStructWithNoFields2' is inefficient due to poor alignment; currently 
aligned to 8 bytes, but recommended alignment is 16 bytes 
[altera-struct-pack-align]
+// CHECK-MESSAGES: :[[@LINE-8]]:8: note: use "__attribute__((aligned(16)))" to 
align struct 'ContainsStructWithNoFields2' to 16 bytes
+// CHECK-FIXES: __attribute__((packed))
+// CHECK-FIXES: __attribute__((aligned(16)));
Index: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
===
--- clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
+++ clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
@@ -73,7 +73,8 @@
   uint64_t CharSize = Result.Context->getCharWidth();
   CharUnits CurrSize = Result.Context->getASTRecordLayout(Struct).getSize();
   CharUnits MinByteSize =
-  CharUnits::fromQuantity(ceil((float)TotalBitSize / CharSize));
+  CharUnits::fromQuantity(std::max(
+  ceil((float)TotalBitSize / CharSize), 1));
   CharUnits MaxAlign = CharUnits::fromQuantity(
   ceil((float)Struct->getMaxAlignment() / CharSize));
   CharUnits CurrAlign =


Index: clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align.cpp
@@ -99,3 +99,22 @@
   struct bad_align3 instantiated { 'a', 0.001, 'b' };
 }
 
+// Make sure that we don't recommend aligning an empty struct to zero bytes (PR#51620)
+struct StructWithNoFields {};
+
+struct ContainsStructWithNoFields {
+  StructWithNoFields s;
+};
+
+// Make sure that an empty struct is treated like "char" for padding and alignment purposes
+struct ContainsStructWithNoFields2 {
+  StructWithNoFields s;
+  double d;
+  StructWithNoFields t;
+};
+// CHECK-MESSAGES: :[[@LINE-5]]:8: warning: accessing fields in struct 'ContainsStructWithNoFields2' is inefficient due to padding; only needs 10 bytes but is using 24 bytes [altera-struct-pack-align]
+// CHECK-MESSAGES: :[[@LINE-6]]:8: note: use "__attribute__((packed))" to reduce the amount of padding applied to struct 'ContainsStructWithNoFields2'
+// CHECK-MESSAGES: :[[@LINE-7]]:8: warning: accessing fields in struct 'ContainsStructWithNoFields2' is inefficient due to poor alignment; currently aligned to 8 bytes, but recommended alignment is 16 bytes [altera-struct-pack-align]
+// CHECK-MESSAGES: :[[@LINE-8]]:8: note: use "__attribute__((aligned(16)))" to align struct 'ContainsStructWithNoFields2' to 16 bytes
+// CHECK-FIXES: __attribute__((packed))
+// CHECK-FIXES: __attribute__((aligned(16)));
Index: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
===
--- clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
+++ clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
@@ -73,7 +73,8 @@
   uint64_t CharSize = Result.Context->getCharWidth();
   CharUnits CurrSize = Result.Context->getASTRecordLayout(Struct).getSize();
   CharUnits MinByteSize =
-  CharUnits::fromQuantity(ceil((float)TotalBitSize / CharSize));
+  

[PATCH] D114268: [InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment

2021-11-19 Thread Ellis Hoag via Phabricator via cfe-commits
ellis added a comment.

In D114268#3143976 , @MaskRay wrote:

>> Add names to pgo registers for clarity.
>
> This may increase memory usage, especially for large LTO applications. Unless 
> this is very helpful I might omit it.

I'll omit it. Thanks for the quick review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114268

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


[PATCH] D114268: [InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment

2021-11-19 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.

> Add names to pgo registers for clarity.

This may increase memory usage. Unless this is very helpful I might omit it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114268

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


[PATCH] D114287: [clangd] IncludeCleaner: Traverse unresolved expressions

2021-11-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Thanks for the fix!




Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:108
 
+  // Some expressions might be not resolved yet due to ADL: conservatively mark
+  // all resolution candidates as used.

The impl is correct but the comment is not.
The primary reason we haven't resolved the overload is simply that we have 
dependent arguments, and you need to know the types to resolve overloads. This 
is true even if ADL doesn't apply (usually because the name is qualified).

If ADL applies, this heuristic isn't conservative: a function in *any* 
namespace with the right name is a candidate, and we can't identify them all 
here.
However if the template expects to find the callee via ADL, then the callee is 
quite likely not even visible here and the instantiation site rather than the 
template is the real user of it, so there's nothing for us to do here.

(We're going to have a hard time identifying such cases at the instantiation 
site, but that's the way it goes)



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:101
+  {
+  "template  void ^foo(T &) {}",
+  "template  void bar() { foo([](){}); }",

Neither the lambda or the foo template are essential here.
Maybe clearer:
```
int ^foo(char);
int ^foo(float);
template int x = foo(T{});
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114287

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


[PATCH] D114287: [clangd] IncludeCleaner: Traverse unresolved expressions

2021-11-19 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
kbobyrev requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114287

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -97,6 +97,10 @@
   "inline void ^foo() {}",
   "void bar() { foo(); }",
   },
+  {
+  "template  void ^foo(T &) {}",
+  "template  void bar() { foo([](){}); }",
+  },
   // Static function
   {
   "struct ^X { static bool ^foo(); }; bool X::^foo() {}",
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -13,6 +13,7 @@
 #include "SourceCode.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/HeaderSearch.h"
@@ -104,6 +105,14 @@
 return true;
   }
 
+  // Some expressions might be not resolved yet due to ADL: conservatively mark
+  // all resolution candidates as used.
+  bool VisitOverloadExpr(OverloadExpr *E) {
+for (const auto *ResolutionDecl : E->decls())
+  add(ResolutionDecl);
+return true;
+  }
+
 private:
   using Base = RecursiveASTVisitor;
 


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -97,6 +97,10 @@
   "inline void ^foo() {}",
   "void bar() { foo(); }",
   },
+  {
+  "template  void ^foo(T &) {}",
+  "template  void bar() { foo([](){}); }",
+  },
   // Static function
   {
   "struct ^X { static bool ^foo(); }; bool X::^foo() {}",
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -13,6 +13,7 @@
 #include "SourceCode.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/HeaderSearch.h"
@@ -104,6 +105,14 @@
 return true;
   }
 
+  // Some expressions might be not resolved yet due to ADL: conservatively mark
+  // all resolution candidates as used.
+  bool VisitOverloadExpr(OverloadExpr *E) {
+for (const auto *ResolutionDecl : E->decls())
+  add(ResolutionDecl);
+return true;
+  }
+
 private:
   using Base = RecursiveASTVisitor;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a075d67 - [Sema] fix nondeterminism in ASTContext::getDeducedTemplateSpecializationType

2021-11-19 Thread Wei Wang via cfe-commits

Author: Wei Wang
Date: 2021-11-19T13:22:07-08:00
New Revision: a075d67222832c234296ffd605f19e33023e6060

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

LOG: [Sema] fix nondeterminism in 
ASTContext::getDeducedTemplateSpecializationType

`DeducedTemplateSpecializationTypes` is a 
`llvm::FoldingSet` [1],
where `FoldingSetNodeID` is based on the values: {`TemplateName`, `QualType`, 
`IsDeducedAsDependent`},
those values are also used as `DeducedTemplateSpecializationType` constructor 
arguments.

A `FoldingSetNodeID` created by the static 
`DeducedTemplateSpecializationType::Profile` may not be equal
to`FoldingSetNodeID` created by a member 
`DeducedTemplateSpecializationType::Profile` of an instance
created with the same {`TemplateName`, `QualType`, `IsDeducedAsDependent`}, 
which makes
`DeducedTemplateSpecializationTypes` lookups nondeterministic.

Specifically, while `IsDeducedAsDependent` value is passes to the constructor, 
`IsDependent()` method on
the created instance may return a different value, because `IsDependent` is not 
saved as is:
```name=clang/include/clang/AST/Type.h
  DeducedTemplateSpecializationType(TemplateName Template,  QualType 
DeducedAsType, bool IsDeducedAsDependent)
  : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
toTypeDependence(Template.getDependence()) | // <~  also 
considers `TemplateName` parameter
(IsDeducedAsDependent ? 
TypeDependence::DependentInstantiation : TypeDependence::None)),
```
For example, if an instance A with key `FoldingSetNodeID {A, B, false}` is 
inserted. Then a key
`FoldingSetNodeID {A, B, true}` is probed:
If it happens to correspond to the same bucket in `FoldingSet` as the first 
key, and `A.Profile()` returns
`FoldingSetNodeID {A, B, true}`, then it's a hit.
If the bucket for the second key is different from the first key, instance A is 
not considered at all, and it's
a no hit, even if `A.Profile()` returns  `FoldingSetNodeID {A, B, true}`.

Since `TemplateName`, `QualType` parameter values involve memory pointers, the 
lookup result depend on allocator,
and may differ from run to run. When this is used as part of modules 
compilation, it may result in "module out of date"
errors, if imported modules are built on different machines.

This makes `ASTContext::getDeducedTemplateSpecializationType` consider 
`Template.isDependent()` similar
`DeducedTemplateSpecializationType` constructor.

Tested on a very big codebase, by running modules compilations from directories 
with varied path length
(seem to affect allocator seed).

1. https://llvm.org/docs/ProgrammersManual.html#llvm-adt-foldingset-h

Patch by Wei Wang and Igor Sugak!

Reviewed By: bruno

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

Added: 


Modified: 
clang/include/clang/AST/Type.h
clang/lib/AST/ASTContext.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index fd25ec25d4f2..4c89c297bf34 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -5073,8 +5073,10 @@ class DeducedTemplateSpecializationType : public 
DeducedType,
   static void Profile(llvm::FoldingSetNodeID , TemplateName Template,
   QualType Deduced, bool IsDependent) {
 Template.Profile(ID);
-ID.AddPointer(Deduced.getAsOpaquePtr());
-ID.AddBoolean(IsDependent);
+QualType CanonicalType =
+Deduced.isNull() ? Deduced : Deduced.getCanonicalType();
+ID.AddPointer(CanonicalType.getAsOpaquePtr());
+ID.AddBoolean(IsDependent || Template.isDependent());
   }
 
   static bool classof(const Type *T) {

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index f0b931bdc905..294cc20f76c5 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -5676,6 +5676,9 @@ QualType ASTContext::getDeducedTemplateSpecializationType(
 
   auto *DTST = new (*this, TypeAlignment)
   DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
+  llvm::FoldingSetNodeID TempID;
+  DTST->Profile(TempID);
+  assert(ID == TempID && "ID does not match");
   Types.push_back(DTST);
   DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
   return QualType(DTST, 0);



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


[PATCH] D112481: [Sema] fix nondeterminism in ASTContext::getDeducedTemplateSpecializationType

2021-11-19 Thread Wei Wang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa075d6722283: [Sema] fix nondeterminism in 
ASTContext::getDeducedTemplateSpecializationType (authored by weiwang).

Changed prior to commit:
  https://reviews.llvm.org/D112481?vs=382375=388616#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112481

Files:
  clang/include/clang/AST/Type.h
  clang/lib/AST/ASTContext.cpp


Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -5676,6 +5676,9 @@
 
   auto *DTST = new (*this, TypeAlignment)
   DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
+  llvm::FoldingSetNodeID TempID;
+  DTST->Profile(TempID);
+  assert(ID == TempID && "ID does not match");
   Types.push_back(DTST);
   DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
   return QualType(DTST, 0);
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -5073,8 +5073,10 @@
   static void Profile(llvm::FoldingSetNodeID , TemplateName Template,
   QualType Deduced, bool IsDependent) {
 Template.Profile(ID);
-ID.AddPointer(Deduced.getAsOpaquePtr());
-ID.AddBoolean(IsDependent);
+QualType CanonicalType =
+Deduced.isNull() ? Deduced : Deduced.getCanonicalType();
+ID.AddPointer(CanonicalType.getAsOpaquePtr());
+ID.AddBoolean(IsDependent || Template.isDependent());
   }
 
   static bool classof(const Type *T) {


Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -5676,6 +5676,9 @@
 
   auto *DTST = new (*this, TypeAlignment)
   DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
+  llvm::FoldingSetNodeID TempID;
+  DTST->Profile(TempID);
+  assert(ID == TempID && "ID does not match");
   Types.push_back(DTST);
   DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
   return QualType(DTST, 0);
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -5073,8 +5073,10 @@
   static void Profile(llvm::FoldingSetNodeID , TemplateName Template,
   QualType Deduced, bool IsDependent) {
 Template.Profile(ID);
-ID.AddPointer(Deduced.getAsOpaquePtr());
-ID.AddBoolean(IsDependent);
+QualType CanonicalType =
+Deduced.isNull() ? Deduced : Deduced.getCanonicalType();
+ID.AddPointer(CanonicalType.getAsOpaquePtr());
+ID.AddBoolean(IsDependent || Template.isDependent());
   }
 
   static bool classof(const Type *T) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114163: Use VersionTuple for parsing versions in Triple. This makes it possible to distinguish between "16" and "16.0" after parsing, which previously was not possible.

2021-11-19 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a reviewer: arphaman.
dexonsmith added a subscriber: arphaman.
dexonsmith added a comment.
This revision now requires review to proceed.

@arphaman , can you take a look?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114163

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


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

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

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

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

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

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

Patch by: Becca Royal-Gordon

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

Added: 


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

Removed: 




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

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

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



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


[PATCH] D112773: Allow __attribute__((swift_attr)) in attribute push pragmas

2021-11-19 Thread Alex Lorenz via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG290cddcd139d: Allow __attribute__((swift_attr)) in attribute 
push pragmas (authored by beccadax, committed by arphaman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112773

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


Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -163,6 +163,7 @@
 // CHECK-NEXT: SwiftAsyncContext (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: SwiftAsyncError (SubjectMatchRule_function, 
SubjectMatchRule_objc_method)
 // CHECK-NEXT: SwiftAsyncName (SubjectMatchRule_objc_method, 
SubjectMatchRule_function)
+// CHECK-NEXT: SwiftAttr ()
 // CHECK-NEXT: SwiftBridgedTypedef (SubjectMatchRule_type_alias)
 // CHECK-NEXT: SwiftContext (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: SwiftError (SubjectMatchRule_function, 
SubjectMatchRule_objc_method)
Index: clang/test/AST/attr-swift_attr.m
===
--- clang/test/AST/attr-swift_attr.m
+++ clang/test/AST/attr-swift_attr.m
@@ -4,5 +4,13 @@
 @interface View
 @end
 
-// CHECK: InterfaceDecl {{.*}} View
+// CHECK-LABEL: InterfaceDecl {{.*}} View
 // CHECK-NEXT: SwiftAttrAttr {{.*}} "@actor"
+
+#pragma clang attribute push(__attribute__((swift_attr("@sendable"))), 
apply_to=objc_interface)
+@interface Contact
+@end
+#pragma clang attribute pop
+
+// CHECK-LABEL: InterfaceDecl {{.*}} Contact
+// CHECK-NEXT: SwiftAttrAttr {{.*}} "@sendable"
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -2310,6 +2310,7 @@
   let Spellings = [GNU<"swift_attr">];
   let Args = [StringArgument<"Attribute">];
   let Documentation = [SwiftAttrDocs];
+  let PragmaAttributeSupport = 1;
 }
 
 def SwiftBridge : InheritableAttr {


Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -163,6 +163,7 @@
 // CHECK-NEXT: SwiftAsyncContext (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: SwiftAsyncError (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEXT: SwiftAsyncName (SubjectMatchRule_objc_method, SubjectMatchRule_function)
+// CHECK-NEXT: SwiftAttr ()
 // CHECK-NEXT: SwiftBridgedTypedef (SubjectMatchRule_type_alias)
 // CHECK-NEXT: SwiftContext (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: SwiftError (SubjectMatchRule_function, SubjectMatchRule_objc_method)
Index: clang/test/AST/attr-swift_attr.m
===
--- clang/test/AST/attr-swift_attr.m
+++ clang/test/AST/attr-swift_attr.m
@@ -4,5 +4,13 @@
 @interface View
 @end
 
-// CHECK: InterfaceDecl {{.*}} View
+// CHECK-LABEL: InterfaceDecl {{.*}} View
 // CHECK-NEXT: SwiftAttrAttr {{.*}} "@actor"
+
+#pragma clang attribute push(__attribute__((swift_attr("@sendable"))), apply_to=objc_interface)
+@interface Contact
+@end
+#pragma clang attribute pop
+
+// CHECK-LABEL: InterfaceDecl {{.*}} Contact
+// CHECK-NEXT: SwiftAttrAttr {{.*}} "@sendable"
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -2310,6 +2310,7 @@
   let Spellings = [GNU<"swift_attr">];
   let Args = [StringArgument<"Attribute">];
   let Documentation = [SwiftAttrDocs];
+  let PragmaAttributeSupport = 1;
 }
 
 def SwiftBridge : InheritableAttr {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112773: Allow __attribute__((swift_attr)) in attribute push pragmas

2021-11-19 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

I will commit this on behalf of @beccadax as she doesn't have commit access yet.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112773

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


[PATCH] D113946: [libc][clang-tidy] fix namespace check for externals

2021-11-19 Thread Michael Jones via Phabricator via cfe-commits
michaelrj updated this revision to Diff 388588.
michaelrj marked 3 inline comments as done.
michaelrj added a comment.

address comments and rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113946

Files:
  clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/llvmlibc-callee-namespace.cpp
  libc/docs/clang_tidy_checks.rst
  libc/src/__support/FPUtil/NearestIntegerOperations.h
  libc/src/__support/str_to_float.h
  libc/src/__support/str_to_integer.h
  libc/src/math/generic/math_utils.h
  libc/src/string/strdup.cpp
  libc/src/string/strndup.cpp

Index: libc/src/string/strndup.cpp
===
--- libc/src/string/strndup.cpp
+++ libc/src/string/strndup.cpp
@@ -23,7 +23,7 @@
   size_t len = internal::string_length(src);
   if (len > size)
 len = size;
-  char *dest = reinterpret_cast(::malloc(len + 1)); // NOLINT
+  char *dest = reinterpret_cast(::malloc(len + 1));
   if (dest == nullptr)
 return nullptr;
   char *result =
Index: libc/src/string/strdup.cpp
===
--- libc/src/string/strdup.cpp
+++ libc/src/string/strdup.cpp
@@ -21,7 +21,7 @@
 return nullptr;
   }
   size_t len = internal::string_length(src) + 1;
-  char *dest = reinterpret_cast(::malloc(len)); // NOLINT
+  char *dest = reinterpret_cast(::malloc(len));
   if (dest == nullptr) {
 return nullptr;
   }
Index: libc/src/math/generic/math_utils.h
===
--- libc/src/math/generic/math_utils.h
+++ libc/src/math/generic/math_utils.h
@@ -55,7 +55,7 @@
 
 template  static inline T with_errno(T x, int err) {
   if (math_errhandling & MATH_ERRNO)
-errno = err; // NOLINT
+errno = err;
   return x;
 }
 
Index: libc/src/__support/str_to_integer.h
===
--- libc/src/__support/str_to_integer.h
+++ libc/src/__support/str_to_integer.h
@@ -74,7 +74,7 @@
   const char *original_src = src;
 
   if (base < 0 || base == 1 || base > 36) {
-errno = EINVAL; // NOLINT
+errno = EINVAL;
 return 0;
   }
 
@@ -114,19 +114,19 @@
 // the result cannot change, but we still need to advance src to the end of
 // the number.
 if (result == ABS_MAX) {
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
   continue;
 }
 
 if (result > ABS_MAX_DIV_BY_BASE) {
   result = ABS_MAX;
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
 } else {
   result = result * base;
 }
 if (result > ABS_MAX - cur_digit) {
   result = ABS_MAX;
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
 } else {
   result = result + cur_digit;
 }
Index: libc/src/__support/str_to_float.h
===
--- libc/src/__support/str_to_float.h
+++ libc/src/__support/str_to_float.h
@@ -200,7 +200,7 @@
   static_cast(fputil::FloatProperties::exponentBias)) {
 *outputMantissa = 0;
 *outputExp2 = fputil::FPBits::maxExponent;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
   // If the exponent is too small even for a subnormal, return 0.
@@ -210,7 +210,7 @@
fputil::FloatProperties::mantissaWidth)) {
 *outputMantissa = 0;
 *outputExp2 = 0;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
 
@@ -253,7 +253,7 @@
   if (exp2 >= fputil::FPBits::maxExponent) {
 *outputMantissa = 0;
 *outputExp2 = fputil::FPBits::maxExponent;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
 
@@ -289,7 +289,7 @@
   }
 
   if (exp2 == 0) {
-errno = ERANGE; // NOLINT
+errno = ERANGE;
   }
 
   *outputMantissa = finalMantissa;
@@ -391,7 +391,7 @@
   static_cast(fputil::FloatProperties::exponentBias) / 3) {
 *outputMantissa = 0;
 *outputExp2 = fputil::FPBits::maxExponent;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
   // If the exponent is too small even for a subnormal, return 0.
@@ -402,7 +402,7 @@
   2) {
 *outputMantissa = 0;
 *outputExp2 = 0;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
 
@@ -467,7 +467,7 @@
 // This indicates an overflow, so we make the result INF and set errno.
 *outputExp2 = (1 << fputil::FloatProperties::exponentWidth) - 1;
 *outputMantissa = 0;
-errno = ERANGE; // NOLINT
+errno = ERANGE;
 return;
   }
 
@@ -483,7 +483,7 @@
   // Return 0 if the exponent is too small.
   *outputMantissa = 0;
   *outputExp2 = 0;
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
   return;
 }
   }
@@ -511,12 +511,12 @@
 ++biasedExponent;
 
 if (biasedExponent == INF_EXP) {
-  errno = ERANGE; // NOLINT
+  errno = ERANGE;
 

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd8e5a0c42bd8: [clang][NFC] Inclusive terms: replace some 
uses of sanity in clang (authored by ZarkoCA).

Changed prior to commit:
  https://reviews.llvm.org/D114025?vs=388550=388587#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

Files:
  clang/include/clang/AST/Redeclarable.h
  clang/include/clang/Analysis/CFG.h
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/include/clang/Sema/Lookup.h
  clang/lib/Analysis/BodyFarm.cpp
  clang/lib/Analysis/RetainSummaryManager.cpp
  clang/lib/Basic/DiagnosticIDs.cpp
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -126,7 +126,7 @@
   for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
-// FIXME: sanity-check the role.
+// FIXME: validate the role.
   }
 
   auto Reachable = [](Node *From, Node *N) {
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -249,7 +249,7 @@
 }
 
 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
-  // Sanity check to avoid doing the wrong thing in the face of
+  // Early return to avoid doing the wrong thing in the face of
   // reinterpret_cast.
   if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
 return UnknownVal();
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -326,8 +326,8 @@
 }
 Result = InitWithAdjustments;
   } else {
-// We need to create a region no matter what. For sanity, make sure we don't
-// try to stuff a Loc into a non-pointer temporary region.
+// We need to create a region no matter what. Make sure we don't try to
+// stuff a Loc into a non-pointer temporary region.
 assert(!InitValWithAdjustments.getAs() ||
Loc::isLocType(Result->getType()) ||
Result->getType()->isMemberPointerType());
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1670,9 +1670,10 @@
   if (isUnderconstrained(PrevN)) {
 IsSatisfied = true;
 
-// As a sanity check, make sure that the negation of the constraint
-// was infeasible in the current state.  If it is feasible, we somehow
-// missed the transition point.
+// At this point, the negation of the constraint should be infeasible. If it
+// is feasible, make sure that the negation of the constrainti was
+// infeasible in the current state.  If it is feasible, we somehow missed
+// the transition point.
 assert(!isUnderconstrained(N));
 
 // We found the transition point for the constraint.  We now need to
Index: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -182,8 +182,7 @@
   ProgramStateRef state = C.getState();
 
   if (CE->getNumArgs() < MinArgCount) {
-// The frontend should issue a warning for this case, so this is a sanity
-// check.
+// The frontend should issue a warning for this case. Just return.
 return;
   } else if (CE->getNumArgs() == MaxArgCount) {
 const Expr *Arg = CE->getArg(CreateModeArgIndex);
@@ -366,7 +365,7 @@
  const unsigned numArgs,
  const unsigned sizeArg,
  const char *fn) const {

[clang] d8e5a0c - [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via cfe-commits

Author: Zarko Todorovski
Date: 2021-11-19T14:58:35-05:00
New Revision: d8e5a0c42bd8796cce9caa53aacab88c7cb2a3eb

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

LOG: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

Rewording of comments to avoid using `sanity test, sanity check`.

Reviewed By: aaron.ballman, Quuxplusone

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

Added: 


Modified: 
clang/include/clang/AST/Redeclarable.h
clang/include/clang/Analysis/CFG.h
clang/include/clang/CodeGen/CGFunctionInfo.h
clang/include/clang/Sema/Lookup.h
clang/lib/Analysis/BodyFarm.cpp
clang/lib/Analysis/RetainSummaryManager.cpp
clang/lib/Basic/DiagnosticIDs.cpp
clang/lib/Basic/SourceManager.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Format/Format.cpp
clang/lib/Frontend/FrontendActions.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaLookup.cpp
clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/Store.cpp
clang/lib/Tooling/Syntax/Tree.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Redeclarable.h 
b/clang/include/clang/AST/Redeclarable.h
index 77b827c52bfb3..58ec07973920c 100644
--- a/clang/include/clang/AST/Redeclarable.h
+++ b/clang/include/clang/AST/Redeclarable.h
@@ -258,7 +258,8 @@ class Redeclarable {
 
 redecl_iterator& operator++() {
   assert(Current && "Advancing while iterator has reached end");
-  // Sanity check to avoid infinite loop on invalid redecl chain.
+  // Make sure we don't infinitely loop on an invalid redecl chain. This
+  // should never happen.
   if (Current->isFirstDecl()) {
 if (PassedFirst) {
   assert(0 && "Passed first decl twice, invalid redecl chain!");

diff  --git a/clang/include/clang/Analysis/CFG.h 
b/clang/include/clang/Analysis/CFG.h
index f9223fe58a27a..3b9b22e87f35c 100644
--- a/clang/include/clang/Analysis/CFG.h
+++ b/clang/include/clang/Analysis/CFG.h
@@ -515,7 +515,7 @@ class CFGTerminator {
 /// of the most derived class while we're in the base class.
 VirtualBaseBranch,
 
-/// Number of 
diff erent kinds, for sanity checks. We subtract 1 so that
+/// Number of 
diff erent kinds, for validity checks. We subtract 1 so that
 /// to keep receiving compiler warnings when we don't cover all enum values
 /// in a switch.
 NumKindsMinusOne = VirtualBaseBranch

diff  --git a/clang/include/clang/CodeGen/CGFunctionInfo.h 
b/clang/include/clang/CodeGen/CGFunctionInfo.h
index 4899c9deda6a3..cd6c7e2e31287 100644
--- a/clang/include/clang/CodeGen/CGFunctionInfo.h
+++ b/clang/include/clang/CodeGen/CGFunctionInfo.h
@@ -250,7 +250,7 @@ class ABIArgInfo {
   static ABIArgInfo getCoerceAndExpand(llvm::StructType *coerceToType,
llvm::Type *unpaddedCoerceToType) {
 #ifndef NDEBUG
-// Sanity checks on unpaddedCoerceToType.
+// Check that unpaddedCoerceToType has roughly the right shape.
 
 // Assert that we only have a struct type if there are multiple elements.
 auto unpaddedStruct = dyn_cast(unpaddedCoerceToType);

diff  --git a/clang/include/clang/Sema/Lookup.h 
b/clang/include/clang/Sema/Lookup.h
index c6edc2df5b9f6..54fe7081b7105 100644
--- a/clang/include/clang/Sema/Lookup.h
+++ b/clang/include/clang/Sema/Lookup.h
@@ -319,7 +319,7 @@ class LookupResult {
   }
 
   LookupResultKind getResultKind() const {
-assert(sanity());
+assert(checkDebugAssumptions());
 return ResultKind;
   }
 
@@ -706,10 +706,9 @@ class LookupResult {
   void addDeclsFromBasePaths(const CXXBasePaths );
   void configure();
 
-  // Sanity checks.
-  bool sanity() const;
+  bool checkDebugAssumptions() const;
 
-  bool sanityCheckUnresolved() const {
+  bool checkUnresolved() const {
 for (iterator I = begin(), E = end(); I != E; ++I)
   if (isa((*I)->getUnderlyingDecl()))
 return true;

diff  --git a/clang/lib/Analysis/BodyFarm.cpp b/clang/lib/Analysis/BodyFarm.cpp
index 49ac74c233bd6..92c236ed9080c 100644
--- a/clang/lib/Analysis/BodyFarm.cpp
+++ b/clang/lib/Analysis/BodyFarm.cpp
@@ -790,9 +790,8 @@ static Stmt *createObjCPropertyGetter(ASTContext ,
 }
   }
 
-  // Sanity check that the property is the same type as the ivar, or a
-  // reference to it, and that it is either an object 

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA marked an inline comment as done.
ZarkoCA added a comment.

Thanks @aaron.ballman and @Quuxplusone for the constructive reviews.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D114142: [clang-format] [PR52527] can join * with /* to form an outside of comment error C4138

2021-11-19 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

In D114142#3142122 , @MyDeveloperDay 
wrote:

>> I only now this from the tests with `-debug`. Is there a way to get "normal" 
>> clang-format to print these? Or did you write a test for that to print the 
>> information?
>
> I just use the --debug option to clang-format.exe?
>
> I develop on windows, using Visual Studio 2019 (Command Shell)  - (with 
> cygwin bash) and build with ninja (so much faster than anything else)
>
> I build Debug  (its possible --debug is only available on Debug builds)
>
>   export CC=cl.exe
>   export CXX=cl.exe
>   c:/Program\ Files/CMake/bin/cmake.exe ../llvm-project/llvm -G "Ninja" \
>   -DLLVM_BUILD_TESTS=ON \
>   -DCMAKE_BUILD_TYPE=Debug \
>   -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
>   -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra"
>
> Then just run with --debug
>
>   $ clang-format --debug test1.cpp
>   Args: C:\llvm\build_ninja\bin\clang-format.exe --debug test
>   1.cpp
>   Trying C:\clang-format-examples\comment\.clang-format...
>   Using configuration file C:\clang-format-examples\comment\.c
>   lang-format
>   File encoding: UTF8
>   Language: C++
>   
>   Line(0, FSC=0): comment[T=93, OC=0]
>   Line(0, FSC=0): eof[T=93, OC=119]

Okay, my debug build does not produce a working clang-format, only the tests. 
And my normal clang-format is release, maybe it's that.

On the matter of this change, I would second the test with `//`, and if the 
`tok::comment`` does the trick, that should be better, than using the type.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114142

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


[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:48
+/// Type-erased base class for dataflow analyses built on a single lattice 
type.
+class DataflowAnalysisDynamic {
+public:

Does the `Dynamic` in the suffix refer to the fact this is using type erasure 
as opposed to templates? 

I have multiple questions at this point:
* Why do we prefer type erasure over generic programming?
* Do you plan to have non-dynamic counterparts?

Nit: having Dynamic both in the class name and in the method names sounds 
overly verbose to me.
Nit: please add a comment what dynamic refers to in the name,



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:140
+struct DataflowAnalysisState {
+  DataflowAnalysisState(AnyLatticeElement Lattice, Environment Env)
+  : Lattice(std::move(Lattice)), Env(std::move(Env)) {}

Do we need a ctor? Or is this a workaround for aggregate initialization not 
working well with certain library facilities?



Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp:26
+runDataflowAnalysis(const CFG , DataflowAnalysisDynamic ,
+const Environment ) {
+  // FIXME: Implement work list-based algorithm to compute the fixed

Is there a way to query how the CFG was built? Adding an assert to see if 
`setAlwaysAdd` was set might be useful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

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


[PATCH] D114163: Use VersionTuple for parsing versions in Triple. This makes it possible to distinguish between "16" and "16.0" after parsing, which previously was not possible.

2021-11-19 Thread Dan Albert via Phabricator via cfe-commits
danalbert accepted this revision.
danalbert added a comment.
This revision is now accepted and ready to land.

Nice, that's a lot of code cleaned up! LGTM, but probably should wait for 
someone from Apple to weigh in. I think the new formatting for those error 
messages is better for them too but that's not my call :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114163

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


[PATCH] D114251: [AST] Add a sugar type for types found via UsingDecl

2021-11-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/include/clang/AST/Type.h:4372
+class UsingType : public Type, public llvm::FoldingSetNode {
+  QualType UnderlyingTy;
+  NamedDecl *Found;

Hmm, maybe I should be getting this from Found, rather than storing it.
We'd have to do more work than e.g. TypedefType though, as we have to check the 
possible types of Found.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114251

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


[PATCH] D114231: [clang][docs][dataflow] Added an introduction to dataflow analysis

2021-11-19 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Thanks for working on this! Publishing documentation alongside the feature is a 
great practice. I liked this documentation a lot. I have strong opinion about 
the ambiguous use of `path condition` in this document, otherwise I was only 
nitpicking.




Comment at: clang/docs/DataFlowAnalysisIntro.md:24
+*   [Introduction to Dataflow 
Analysis](https://www.youtube.com/watch?v=OROXJ9-wUQE)
+*   [Introduction to abstract 
interpretation](http://www.cs.tau.ac.il/~msagiv/courses/asv/absint-1.pdf).
+*   [Introduction to symbolic 
execution](https://www.cs.umd.edu/~mwh/se-tutorial/symbolic-exec.pdf).

I know, everyone has their favorite set of resources. Let me share mine: 
`https://cs.au.dk/~amoeller/spa/`
I think this one might have a bit more content with more examples. Feel free to 
leave it as is. 



Comment at: clang/docs/DataFlowAnalysisIntro.md:49
+  int x;
+  // x is {}
+  if (n > 0) {

Nit: I wonder if representing the value of `x` with an empty set is a good 
choice. One could argue that `x` has an indeterminate value that could be 
represented with the set of all integers using top. Others could argue for a 
bottom value. Those concepts are not yet introduced. Maybe initializing `x` in 
the source code would side step this problem.



Comment at: clang/docs/DataFlowAnalysisIntro.md:71-72
+Abstract algebra provides a nice formalism that models this type of structure,
+namely, a lattice. A lattice is a partially ordered set, in which every two
+elements have a least upper bound (called a *join*).
+

Technically, I think this would be a `join-semilattice`. To have a `lattice`, 
we would need both `join` and `meet`.



Comment at: clang/docs/DataFlowAnalysisIntro.md:86-87
+
+Computing the join in the lattice corresponds to finding the lowest common
+ancestor between two nodes in its Hasse diagram.
+

If we want to be practical, I wonder if we want to give some guidance how to 
implement that efficiently. E.g. we could cite a paper like this: 
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.106.4911=rep1=pdf



Comment at: clang/docs/DataFlowAnalysisIntro.md:111-112
+information that we track. In this case, we can, for example, arbitrarily limit
+the size of sets to 3 elements. If at a certain program point `x` has more than
+3 possible values, we stop tracking specific values at that program point.
+Instead, we denote possible values of `x` with the symbol `⊤` (pronounced "top"

I wonder if we want to cite widening and narrowing in this context to give 
people some pointers where to look for more info.



Comment at: clang/docs/DataFlowAnalysisIntro.md:182
+void Example(int n) {
+  int x;  // x is ⊥
+  if (n > 0) {

I think it would make sense to include the whole program state in the comments. 
E.g. `// x is ⊥, n is ⊤`.
This could showcase how we constrain the value of `n` to `42` in one of the 
branches.



Comment at: clang/docs/DataFlowAnalysisIntro.md:279
+```
+out = transfer(basic_block, join(in_1, in_2, ..., in_n))
+```

While I agree that this is the general formula, people sometimes do small 
variations, e.g.:
```
out =  join(transfer(basic_block,in_1), transfer(basic_block,in_2), ..., 
transfer(basic_block,in_n))
```

This is less efficient as we end up invoking the transfer function more often, 
but it can be more precise. E.g. with some ad-hoc notation:

```
Given the branches: x: {1}, x: {2}, x: {3}, x: {4}
join(in...) : x : {⊤}
transfer("x/2", ...) == x : {⊤}

vs.
Given the branches: x: {1}, x: {2}, x: {3}, x: {4}
transfer("x/2", ...) ==x : {0}, x : {1}, x : {1}, x: {2} == outs
join(outs) == x: {0, 1, 2}
```



Comment at: clang/docs/DataFlowAnalysisIntro.md:288
+Since the lattice has a finite height, the algorithm is guaranteed to 
terminate.
+Each iteration of the algorithm can change computed values only to larger 
values
+from the lattice. In the worst case, all computed values become `⊤`, which is

Only if our transfer functions are monotonic :)



Comment at: clang/docs/DataFlowAnalysisIntro.md:299
+
+## Symbolic execution: a very short informal introduction
+

I think many people find it confusing, what is the relationship between 
symbolic execution and abstract interpretation? I found this answer helpful: 
https://cstheory.stackexchange.com/questions/19708/symbolic-execution-is-a-case-of-abstract-interpretation
I wonder if it might be worth citing.



Comment at: clang/docs/DataFlowAnalysisIntro.md:365
+void ExampleOfSymbolicPointers(bool b) {
+  int x = 0; // x is {0}
+  int* ptr =  // x is {0}

Here, I think we want to include `ptr` in the comments describing the program 
state. 



Comment at: 

[PATCH] D71016: [SYCL] Implement OpenCL kernel function generation

2021-11-19 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

Added in the sycl_special_class attribute. This is still work in progress as I 
still have a few LIT tests failing and didn't address the issue of the 
separating sema from codegen work.


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

https://reviews.llvm.org/D71016

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


[PATCH] D114095: [clang][lex] Include tracking: simplify and move to preprocessor

2021-11-19 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added inline comments.



Comment at: clang/lib/Serialization/ASTWriter.cpp:873
   RECORD(PP_TOKEN);
+  RECORD(PP_INCLUDED_FILES);
 

I believe `PP_INCLUDED_FILES` is located in `AST_BLOCK`. Yes, you write it in 
`ASTWriter::WritePreprocessor` but after `Stream.ExitBlock()` together with 
`MACRO_OFFSET`. And then you read it in `ASTReader::ReadASTBlock` at the top 
level and not inside `case PREPROCESSOR_BLOCK_ID` or from 
`ModuleFile::MacroCursor`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114095

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


[PATCH] D114268: [InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment

2021-11-19 Thread Ellis Hoag via Phabricator via cfe-commits
ellis created this revision.
Herald added subscribers: wenlei, arphaman, hiraditya.
ellis updated this revision to Diff 388564.
ellis added a comment.
ellis edited the summary of this revision.
ellis added a reviewer: MaskRay.
ellis retitled this revision from "[InstrProf] Use i32 for GEP index" to 
"[InstrProf] Use i32 for GEP index from lowering llvm.instrprof.increment".
ellis published this revision for review.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Run `clang-format`.


The `llvm.instrprof.increment` intrinsic uses `i32` for the index. We should 
use this same type for the index into the GEP instructions.

Add names to pgo registers for clarity.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114268

Files:
  clang/test/CodeGen/profile-filter.c
  clang/test/Profile/branch-logical-mixed.cpp
  clang/test/Profile/c-captured.c
  clang/test/Profile/c-general.c
  clang/test/Profile/c-ternary.c
  clang/test/Profile/cxx-class.cpp
  clang/test/Profile/cxx-lambda.cpp
  clang/test/Profile/cxx-rangefor.cpp
  clang/test/Profile/cxx-stmt-initializers.cpp
  clang/test/Profile/cxx-templates.cpp
  clang/test/Profile/cxx-throws.cpp
  clang/test/Profile/objc-general.m
  llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
  llvm/test/Instrumentation/InstrProfiling/atomic-updates.ll
  llvm/test/Instrumentation/InstrProfiling/runtime-counter-relocation.ll
  llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
  llvm/test/Transforms/PGOProfile/instr_entry_bb.ll

Index: llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
===
--- llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
+++ llvm/test/Transforms/PGOProfile/instr_entry_bb.ll
@@ -18,7 +18,7 @@
 ; GEN: entry:
 ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__profn_test_br_2, i32 0, i32 0), i64 {{[0-9]+}}, i32 2, i32 0)
 ; GENA: entry:
-; GENA: %{{[0-9+]}} = atomicrmw add i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 0), i64 1 monotonic
+; GENA: %{{[0-9+]}} = atomicrmw add i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 0), i64 1 monotonic
 ; USE: br i1 %cmp, label %if.then, label %if.else
 ; USE-SAME: !prof ![[BW_ENTRY:[0-9]+]]
 ; USE: ![[BW_ENTRY]] = !{!"branch_weights", i32 0, i32 1}
@@ -35,9 +35,9 @@
 ; GEN: if.else:
 ; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__profn_test_br_2, i32 0, i32 0), i64 {{[0-9]+}}, i32 2, i32 1)
 ; GENA: if.else:
-; GENA:  %pgocount = load i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 1), align 8
+; GENA:  %pgocount = load i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 1), align 8
 ; GENA:  [[V:%[0-9]*]] = add i64 %pgocount, 1
-; GENA:  store i64 [[V]], i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i64 0, i64 1), align 8
+; GENA:  store i64 [[V]], i64* getelementptr inbounds ([2 x i64], [2 x i64]* @__profc_test_br_2, i32 0, i32 1), align 8
   %sub = sub nsw i32 %i, 2
   br label %if.end
 
Index: llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
===
--- llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
+++ llvm/test/Transforms/PGOProfile/counter_promo_exit_catchswitch.ll
@@ -38,11 +38,11 @@
 
 for.body: ; preds = %for.cond
 ; CHECK: for.body:
-; NOTENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 0)
-; TENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
+; NOTENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 0)
+; TENTRY: %pgocount1 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
 ; CHECK: %1 = add i64 %pgocount1, 1
-; NOTENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 0)
-; ENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i64 0, i64 1)
+; NOTENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 0)
+; ENTRY: store i64 %1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @"__profc_?run@@YAXH@Z", i32 0, i32 1)
   %idxprom = zext i32 %i.0 to i64
   %arrayidx = getelementptr inbounds [200 x i8], [200 x i8]* @"?buffer@@3PADA", i64 0, i64 %idxprom
   %0 = load i8, i8* %arrayidx, align 1
@@ -55,11 +55,11 @@
 
 for.inc:  ; preds = %if.end
 ; CHECK: for.inc:
-; NOTENTRY: %pgocount2 = load i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* 

[PATCH] D107944: [hmaptool] Port to python3

2021-11-19 Thread Nathan Lanza via Phabricator via cfe-commits
lanza updated this revision to Diff 388568.

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

https://reviews.llvm.org/D107944

Files:
  clang/utils/hmaptool/hmaptool


Index: clang/utils/hmaptool/hmaptool
===
--- clang/utils/hmaptool/hmaptool
+++ clang/utils/hmaptool/hmaptool
@@ -1,6 +1,7 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 from __future__ import absolute_import, division, print_function

+from ctypes import ArgumentError
 import json
 import optparse
 import os
@@ -9,8 +10,8 @@

 ###

-k_header_magic_LE = 'pamh'
-k_header_magic_BE = 'hmap'
+k_header_magic_LE = b'pamh'
+k_header_magic_BE = b'hmap'

 def hmap_hash(str):
 """hash(str) -> int
@@ -43,7 +44,7 @@
 path,))

 (version, reserved, strtable_offset, num_entries,
- num_buckets, max_value_len) = struct.unpack(header_fmt, data)
+ num_buckets) = struct.unpack(header_fmt, data)

 if version != 1:
 raise SystemExit("error: %s: unknown headermap version: %r" % (
@@ -83,7 +84,7 @@
 if len(strtable) != strtable_size:
 raise SystemExit("error: %s: unable to read complete string 
table"%(
 path,))
-if strtable[-1] != '\0':
+if strtable[-1] != 0:
 raise SystemExit("error: %s: invalid string table in 
headermap" % (
 path,))

@@ -97,8 +98,8 @@
 def get_string(self, idx):
 if idx >= len(self.strtable):
 raise SystemExit("error: %s: invalid string index" % (
-path,))
-end_idx = self.strtable.index('\0', idx)
+idx,))
+end_idx = self.strtable.index(0, idx)
 return self.strtable[idx:end_idx]

 @property
@@ -220,7 +221,7 @@

 # Write out the headermap.
 with open(output_path, 'wb') as f:
-f.write(magic.encode())
+f.write(magic)
 f.write(struct.pack(header_fmt, *header))
 for bucket in table:
 f.write(struct.pack(bucket_fmt, *bucket))


Index: clang/utils/hmaptool/hmaptool
===
--- clang/utils/hmaptool/hmaptool
+++ clang/utils/hmaptool/hmaptool
@@ -1,6 +1,7 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 from __future__ import absolute_import, division, print_function

+from ctypes import ArgumentError
 import json
 import optparse
 import os
@@ -9,8 +10,8 @@

 ###

-k_header_magic_LE = 'pamh'
-k_header_magic_BE = 'hmap'
+k_header_magic_LE = b'pamh'
+k_header_magic_BE = b'hmap'

 def hmap_hash(str):
 """hash(str) -> int
@@ -43,7 +44,7 @@
 path,))

 (version, reserved, strtable_offset, num_entries,
- num_buckets, max_value_len) = struct.unpack(header_fmt, data)
+ num_buckets) = struct.unpack(header_fmt, data)

 if version != 1:
 raise SystemExit("error: %s: unknown headermap version: %r" % (
@@ -83,7 +84,7 @@
 if len(strtable) != strtable_size:
 raise SystemExit("error: %s: unable to read complete string table"%(
 path,))
-if strtable[-1] != '\0':
+if strtable[-1] != 0:
 raise SystemExit("error: %s: invalid string table in headermap" % (
 path,))

@@ -97,8 +98,8 @@
 def get_string(self, idx):
 if idx >= len(self.strtable):
 raise SystemExit("error: %s: invalid string index" % (
-path,))
-end_idx = self.strtable.index('\0', idx)
+idx,))
+end_idx = self.strtable.index(0, idx)
 return self.strtable[idx:end_idx]

 @property
@@ -220,7 +221,7 @@

 # Write out the headermap.
 with open(output_path, 'wb') as f:
-f.write(magic.encode())
+f.write(magic)
 f.write(struct.pack(header_fmt, *header))
 for bucket in table:
 f.write(struct.pack(bucket_fmt, *bucket))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:9176
   // Don't check the implicit member of the anonymous union type.
-  // This is technically non-conformant, but sanity demands it.
+  // This is technically non-conformant, but validation tests demand it.
   return false;

ZarkoCA wrote:
> Quuxplusone wrote:
> > Quuxplusone wrote:
> > > Quuxplusone wrote:
> > > > This comment seems incorrectly translated.
> > > This comment //still// seems incorrectly translated.
> > > Things we do "for sanity's sake" aren't necessarily //required//, 
> > > technically; but we're doing them anyway, for sanity.
> > "Don't check ... but check it anyway"?
> Right, that didn't make sense :). I noticed that there were warnings for this 
> case in SemaDecl.cpp AFAIU so edited the comment to state that. Should be 
> better now? 
Well, this version of the comment now gives the //impression// that it must be 
clear to //someone//. ;) I don't understand its implications, but I also don't 
know the code.

Specifically, I don't know what "This" refers to (grammatically) — "Anonymous 
union types aren't conforming, but we support them anyway, and this is the 
right thing to do with them"? "Our behavior in this case isn't conforming, but 
it wouldn't make sense to do the conforming thing [wat]"? or something else?

More fundamentally to //my// confusion (but not to that hypothetical other 
someone), I don't know what "the implicit member of the anonymous union type" 
actually means (in terms of the arcane details of C++), i.e., I personally 
don't know when this codepath is hit or what its effect is when it does get hit.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:12260
   // even if hidden by ordinary names, *except* in a dependent context
-  // where it's important for the sanity of two-phase lookup.
+  // where it's important for the validation of two-phase lookup.
   if (!IsInstantiation)

Quuxplusone wrote:
> This comment seems incorrectly translated.
Perhaps just `// where they may be used by two-phase lookup.` (But this is now 
just a nit.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D114006: [analyzer][NFC] Enable access to CodeGenOptions from analyzer's instances

2021-11-19 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D114006#3142313 , @martong wrote:

> LGTM!

Thanks, guys!
I'll load it as soon as D110927  also be 
ready for load(I'm working on it), as this patch is just a preparatory one.


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

https://reviews.llvm.org/D114006

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


[PATCH] D103096: [analyzer] Implement cast for ranges of symbolic integers

2021-11-19 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 388552.
ASDenysPetrov added a comment.

Rebased.


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

https://reviews.llvm.org/D103096

Files:
  clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SymbolManager.cpp
  clang/test/Analysis/symbol-integral-cast.cpp

Index: clang/test/Analysis/symbol-integral-cast.cpp
===
--- /dev/null
+++ clang/test/Analysis/symbol-integral-cast.cpp
@@ -0,0 +1,374 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -analyzer-config eagerly-assume=false -analyzer-config support-symbolic-integer-casts=true -verify %s
+
+template 
+void clang_analyzer_eval(T);
+void clang_analyzer_warnIfReached();
+
+typedef short int16_t;
+typedef int int32_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+
+void test1(int x) {
+  // Even if two lower bytes of `x` equal to zero, it doesn't mean that
+  // the entire `x` is zero. We are not able to know the exact value of x.
+  // It can be one of  65536 possible values like [0, 65536, 131072, ...]
+  // and so on. To avoid huge range sets we still assume `x` in the range
+  // [INT_MIN, INT_MAX].
+  if (!(short)x) {
+if (!x)
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  }
+}
+
+void test2(int x) {
+  // If two lower bytes of `x` equal to zero, and we know x to be 65537,
+  // which is not truncated to short as zero. Thus the branch is infisible.
+  short s = x;
+  if (!s) {
+if (x == 65537)
+  clang_analyzer_warnIfReached(); // no-warning
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  }
+}
+
+void test3(int x, short s) {
+  s = x;
+  if ((short)x > -10 && s < 10) {
+if (x > 0 && x < 10) {
+  // If the range of the whole variable was constrained then reason again
+  // about truncated bytes to make the ranges more precise.
+  clang_analyzer_eval((short)x <= 0); // expected-warning {{FALSE}}
+}
+  }
+}
+
+void test4(unsigned x) {
+  if ((char)x > 8) {
+// Constraint the range of the lowest byte of `x` to [9, CHAR_MAX].
+// The original range of `x` still remains [0, UINT_MAX].
+clang_analyzer_eval((char)x < 42); // expected-warning {{UNKNOWN}}
+if (x < 42) {
+  // Constraint the original range to [0, 42] and update (re-constraint)
+  // the range of the lowest byte of 'x' to [9, 42].
+  clang_analyzer_eval((char)x < 42); // expected-warning {{TRUE}}
+}
+  }
+}
+
+void test5(unsigned x) {
+  if ((char)x > -10 && (char)x < 10) {
+if ((short)x == 8) {
+  // If the range of higher bytes(short) was constrained then reason again
+  // about smaller truncated ranges(char) to make it more precise.
+  clang_analyzer_eval((char)x == 8);  // expected-warning {{TRUE}}
+  clang_analyzer_eval((short)x == 8); // expected-warning {{TRUE}}
+  // We still assume full version of `x` in the range [INT_MIN, INT_MAX].
+  clang_analyzer_eval(x == 8); // expected-warning {{UNKNOWN}}
+}
+  }
+}
+
+void test6(int x) {
+  // Even if two lower bytes of `x` less than zero, it doesn't mean that `x`
+  // can't be greater than zero. Thence we don't change the native range of
+  // `x` and this branch is feasible.
+  if (x > 0)
+if ((short)x < 0)
+  clang_analyzer_eval(x > 0); // expected-warning {{TRUE}}
+}
+
+void test7(int x) {
+  // The range of two lower bytes of `x` [1, SHORT_MAX] is enough to cover
+  // all possible values of char [CHAR_MIN, CHAR_MAX]. So the lowest byte
+  // can be lower than zero.
+  if ((short)x > 0) {
+if ((char)x < 0)
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  }
+}
+
+void test8(int x) {
+  // Promotion from `signed int` to `signed long long` also reasoning about the
+  // original range, because we know the fact that even after promotion it
+  // remains in the range [INT_MIN, INT_MAX].
+  if ((long long)x < 0)
+clang_analyzer_eval(x < 0); // expected-warning {{TRUE}}
+}
+
+void test9(signed int x) {
+  // Any cast `signed` to `unsigned` produces an unsigned range, which is
+  // [0, UNSIGNED_MAX] and can not be lower than zero.
+  if ((unsigned long long)x < 0)
+clang_analyzer_warnIfReached(); // no-warning
+  else
+clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+
+  if ((unsigned int)x < 0)
+clang_analyzer_warnIfReached(); // no-warning
+  else
+clang_analyzer_warnIfReached(); // expected-warning 

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:9176
   // Don't check the implicit member of the anonymous union type.
-  // This is technically non-conformant, but sanity demands it.
+  // This is technically non-conformant, but validation tests demand it.
   return false;

Quuxplusone wrote:
> Quuxplusone wrote:
> > Quuxplusone wrote:
> > > This comment seems incorrectly translated.
> > This comment //still// seems incorrectly translated.
> > Things we do "for sanity's sake" aren't necessarily //required//, 
> > technically; but we're doing them anyway, for sanity.
> "Don't check ... but check it anyway"?
Right, that didn't make sense :). I noticed that there were warnings for this 
case in SemaDecl.cpp AFAIU so edited the comment to state that. Should be 
better now? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA updated this revision to Diff 388550.
ZarkoCA marked 3 inline comments as done.
ZarkoCA added a comment.

- Address latest round of comments
- Fix unrelated formatting to stop distracting clang-format linter complaints


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

Files:
  clang/include/clang/AST/Redeclarable.h
  clang/include/clang/Analysis/CFG.h
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/include/clang/Sema/Lookup.h
  clang/lib/Analysis/BodyFarm.cpp
  clang/lib/Analysis/RetainSummaryManager.cpp
  clang/lib/Basic/DiagnosticIDs.cpp
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -126,7 +126,7 @@
   for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
-// FIXME: sanity-check the role.
+// FIXME: validate the role.
   }
 
   auto Reachable = [](Node *From, Node *N) {
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -249,7 +249,7 @@
 }
 
 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
-  // Sanity check to avoid doing the wrong thing in the face of
+  // Early return to avoid doing the wrong thing in the face of
   // reinterpret_cast.
   if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
 return UnknownVal();
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -326,8 +326,8 @@
 }
 Result = InitWithAdjustments;
   } else {
-// We need to create a region no matter what. For sanity, make sure we don't
-// try to stuff a Loc into a non-pointer temporary region.
+// We need to create a region no matter what. Make sure we don't try to
+// stuff a Loc into a non-pointer temporary region.
 assert(!InitValWithAdjustments.getAs() ||
Loc::isLocType(Result->getType()) ||
Result->getType()->isMemberPointerType());
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1670,9 +1670,10 @@
   if (isUnderconstrained(PrevN)) {
 IsSatisfied = true;
 
-// As a sanity check, make sure that the negation of the constraint
-// was infeasible in the current state.  If it is feasible, we somehow
-// missed the transition point.
+// At this point, the negation of the constraint should be infeasible. If it
+// is feasible, make sure that the negation of the constrainti was
+// infeasible in the current state.  If it is feasible, we somehow missed
+// the transition point.
 assert(!isUnderconstrained(N));
 
 // We found the transition point for the constraint.  We now need to
Index: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -182,8 +182,7 @@
   ProgramStateRef state = C.getState();
 
   if (CE->getNumArgs() < MinArgCount) {
-// The frontend should issue a warning for this case, so this is a sanity
-// check.
+// The frontend should issue a warning for this case. Just return.
 return;
   } else if (CE->getNumArgs() == MaxArgCount) {
 const Expr *Arg = CE->getArg(CreateModeArgIndex);
@@ -366,7 +365,7 @@
  const unsigned numArgs,
  const unsigned sizeArg,
  const char *fn) const {
-  // Sanity check for the correct number of 

[PATCH] D113250: [clang][driver] Add -fplugin-arg- to pass arguments to plugins

2021-11-19 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/docs/ClangPlugins.rst:131
+
+The clang compiler driver accepts the `fplugin` option to load a plugin.
+Clang plugins can receive arguments from the compiler driver command





Comment at: clang/docs/ClangPlugins.rst:141
+  $ export BD=/path/to/build/directory
+  $ (cd $BD && make CallSuperAttr )
+  $ clang++ -fplugin=$BD/lib/CallSuperAttr.so \





Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6676
+if (FirstDashIndex == StringRef::npos)
+  continue;
+

This probably should be an error. See elsewhere in the file for error reporting.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6679
+auto Arg = ArgValue.substr(FirstDashIndex + 1);
+auto PluginName = ArgValue.substr(0, FirstDashIndex);
+





Comment at: clang/test/Driver/plugin-driver-args.cpp:5
+// CHECK: "-load"
+// CHECK: CallSuperAttr
+// CHECK: "-plugin-arg-call_super_plugin"

CHECK-SAME


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

https://reviews.llvm.org/D113250

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


[clang] d5de568 - [analyzer][NFC] MaybeUInt -> MaybeCount

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:36:55+01:00
New Revision: d5de568cc7375281b14bd2632576bff7f4afabc3

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

LOG: [analyzer][NFC] MaybeUInt -> MaybeCount

I forgot to include this in D113594

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index 67db652a1e52..396c9a4de440 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -42,14 +42,14 @@ enum CallDescriptionFlags : unsigned {
 /// arguments and the name of the function.
 class CallDescription {
   friend class CallEvent;
-  using MaybeUInt = Optional;
+  using MaybeCount = Optional;
 
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
   std::vector QualifiedName;
-  MaybeUInt RequiredArgs;
-  MaybeUInt RequiredParams;
+  MaybeCount RequiredArgs;
+  MaybeCount RequiredParams;
   int Flags;
 
 public:
@@ -65,13 +65,13 @@ class CallDescription {
   /// name regardless the number of arguments.
   CallDescription(CallDescriptionFlags Flags,
   ArrayRef QualifiedName,
-  MaybeUInt RequiredArgs = None,
-  MaybeUInt RequiredParams = None);
+  MaybeCount RequiredArgs = None,
+  MaybeCount RequiredParams = None);
 
   /// Construct a CallDescription with default flags.
   CallDescription(ArrayRef QualifiedName,
-  MaybeUInt RequiredArgs = None,
-  MaybeUInt RequiredParams = None);
+  MaybeCount RequiredArgs = None,
+  MaybeCount RequiredParams = None);
 
   CallDescription(std::nullptr_t) = delete;
 

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index 36c50e96311f..810fe365d021 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -22,11 +22,11 @@
 using namespace llvm;
 using namespace clang;
 
-using MaybeUInt = Optional;
+using MaybeCount = Optional;
 
 // A constructor helper.
-static MaybeUInt readRequiredParams(MaybeUInt RequiredArgs,
-MaybeUInt RequiredParams) {
+static MaybeCount readRequiredParams(MaybeCount RequiredArgs,
+ MaybeCount RequiredParams) {
   if (RequiredParams)
 return RequiredParams;
   if (RequiredArgs)
@@ -36,8 +36,8 @@ static MaybeUInt readRequiredParams(MaybeUInt RequiredArgs,
 
 ento::CallDescription::CallDescription(CallDescriptionFlags Flags,
ArrayRef QualifiedName,
-   MaybeUInt RequiredArgs /*= None*/,
-   MaybeUInt RequiredParams /*= None*/)
+   MaybeCount RequiredArgs /*= None*/,
+   MaybeCount RequiredParams /*= None*/)
 : RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
@@ -48,8 +48,8 @@ ento::CallDescription::CallDescription(CallDescriptionFlags 
Flags,
 
 /// Construct a CallDescription with default flags.
 ento::CallDescription::CallDescription(ArrayRef QualifiedName,
-   MaybeUInt RequiredArgs /*= None*/,
-   MaybeUInt RequiredParams /*= None*/)
+   MaybeCount RequiredArgs /*= None*/,
+   MaybeCount RequiredParams /*= None*/)
 : CallDescription(CDF_None, QualifiedName, RequiredArgs, RequiredParams) {}
 
 bool ento::CallDescription::matches(const CallEvent ) const {



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


[Diffusion] rGc93f93b2e3f2: Revert "Revert "Recommit "Revert "[CVP] processSwitch: Remove default case when…

2021-11-19 Thread Bogdan Graur via Phabricator via cfe-commits
bgraur added a comment.

Early heads up that this revision causes a large regression in compilation time 
for some of our internal source files: we are seeing seeing an almost 20x 
increase in compilation times for some files (from 42s to 728s).

I'm working on a reproducer which I'm going to upload when ready.


BRANCHES
  main

Users:
  junparser (Author)

https://reviews.llvm.org/rGc93f93b2e3f2

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


[PATCH] D113595: [analyzer][NFC] Use enum for CallDescription flags

2021-11-19 Thread Balázs Benics 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 rGe6ef134f3c77: [analyzer][NFC] Use enum for CallDescription 
flags (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113595

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -34,7 +34,7 @@
   return None;
 }
 
-ento::CallDescription::CallDescription(int Flags,
+ento::CallDescription::CallDescription(CallDescriptionFlags Flags,
ArrayRef QualifiedName,
MaybeUInt RequiredArgs /*= None*/,
MaybeUInt RequiredParams /*= None*/)
@@ -50,7 +50,7 @@
 ento::CallDescription::CallDescription(ArrayRef QualifiedName,
MaybeUInt RequiredArgs /*= None*/,
MaybeUInt RequiredParams /*= None*/)
-: CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
+: CallDescription(CDF_None, QualifiedName, RequiredArgs, RequiredParams) {}
 
 bool ento::CallDescription::matches(const CallEvent ) const {
   // FIXME: Add ObjC Message support.
Index: clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
@@ -42,12 +42,12 @@
  CheckerContext &) const;
 
   CallDescriptionMap Callbacks = {
-{{0, "clang_analyzer_iterator_position", 1},
- ::analyzerIteratorPosition},
-{{0, "clang_analyzer_iterator_container", 1},
- ::analyzerIteratorContainer},
-{{0, "clang_analyzer_iterator_validity", 1},
- ::analyzerIteratorValidity},
+  {{"clang_analyzer_iterator_position", 1},
+   ::analyzerIteratorPosition},
+  {{"clang_analyzer_iterator_container", 1},
+   ::analyzerIteratorContainer},
+  {{"clang_analyzer_iterator_validity", 1},
+   ::analyzerIteratorValidity},
   };
 
 public:
Index: clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
@@ -41,10 +41,10 @@
  CheckerContext &) const;
 
   CallDescriptionMap Callbacks = {
-{{0, "clang_analyzer_container_begin", 1},
- ::analyzerContainerBegin},
-{{0, "clang_analyzer_container_end", 1},
- ::analyzerContainerEnd},
+  {{"clang_analyzer_container_begin", 1},
+   ::analyzerContainerBegin},
+  {{"clang_analyzer_container_end", 1},
+   ::analyzerContainerEnd},
   };
 
 public:
Index: clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
@@ -72,42 +72,27 @@
SVal) const;
 
   CallDescriptionMap NoIterParamFunctions = {
-{{0, "clear", 0},
- ::handleClear},
-{{0, "assign", 2},
- ::handleAssign},
-{{0, "push_back", 1},
- ::handlePushBack},
-{{0, "emplace_back", 1},
- ::handlePushBack},
-{{0, "pop_back", 0},
- ::handlePopBack},
-{{0, "push_front", 1},
- ::handlePushFront},
-{{0, "emplace_front", 1},
- ::handlePushFront},
-{{0, "pop_front", 0},
- ::handlePopFront},
+  {{"clear", 0}, ::handleClear},
+  {{"assign", 2}, ::handleAssign},
+  {{"push_back", 1}, ::handlePushBack},
+  {{"emplace_back", 1}, ::handlePushBack},
+  {{"pop_back", 0}, ::handlePopBack},
+  {{"push_front", 1}, ::handlePushFront},
+  {{"emplace_front", 1}, ::handlePushFront},
+  {{"pop_front", 0}, ::handlePopFront},
   };
-  
+
   CallDescriptionMap OneIterParamFunctions = {
-{{0, "insert", 2},
- ::handleInsert},
-{{0, "emplace", 2},
- ::handleInsert},
-{{0, "erase", 1},
- ::handleErase},
-{{0, "erase_after", 1},
- ::handleEraseAfter},
+ 

[PATCH] D113594: [analyzer][NFC] Consolidate the inner representation of CallDescriptions

2021-11-19 Thread Balázs Benics 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 rG97f1bf15b154: [analyzer][NFC] Consolidate the inner 
representation of CallDescriptions (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113594

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -22,20 +22,22 @@
 using namespace llvm;
 using namespace clang;
 
+using MaybeUInt = Optional;
+
 // A constructor helper.
-static Optional readRequiredParams(Optional RequiredArgs,
-   Optional RequiredParams) {
+static MaybeUInt readRequiredParams(MaybeUInt RequiredArgs,
+MaybeUInt RequiredParams) {
   if (RequiredParams)
 return RequiredParams;
   if (RequiredArgs)
-return static_cast(*RequiredArgs);
+return RequiredArgs;
   return None;
 }
 
-ento::CallDescription::CallDescription(
-int Flags, ArrayRef QualifiedName,
-Optional RequiredArgs /*= None*/,
-Optional RequiredParams /*= None*/)
+ento::CallDescription::CallDescription(int Flags,
+   ArrayRef QualifiedName,
+   MaybeUInt RequiredArgs /*= None*/,
+   MaybeUInt RequiredParams /*= None*/)
 : RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
@@ -45,10 +47,9 @@
 }
 
 /// Construct a CallDescription with default flags.
-ento::CallDescription::CallDescription(
-ArrayRef QualifiedName,
-Optional RequiredArgs /*= None*/,
-Optional RequiredParams /*= None*/)
+ento::CallDescription::CallDescription(ArrayRef QualifiedName,
+   MaybeUInt RequiredArgs /*= None*/,
+   MaybeUInt RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
 bool ento::CallDescription::matches(const CallEvent ) const {
@@ -62,8 +63,8 @@
 
   if (Flags & CDF_MaybeBuiltin) {
 return CheckerContext::isCLibraryFunction(FD, getFunctionName()) &&
-   (!RequiredArgs || RequiredArgs <= Call.getNumArgs()) &&
-   (!RequiredParams || RequiredParams <= Call.parameters().size());
+   (!RequiredArgs || *RequiredArgs <= Call.getNumArgs()) &&
+   (!RequiredParams || *RequiredParams <= Call.parameters().size());
   }
 
   if (!II.hasValue()) {
@@ -87,9 +88,9 @@
   const auto ExactMatchArgAndParamCounts =
   [](const CallEvent , const CallDescription ) -> bool {
 const bool ArgsMatch =
-!CD.RequiredArgs || CD.RequiredArgs == Call.getNumArgs();
+!CD.RequiredArgs || *CD.RequiredArgs == Call.getNumArgs();
 const bool ParamsMatch =
-!CD.RequiredParams || CD.RequiredParams == Call.parameters().size();
+!CD.RequiredParams || *CD.RequiredParams == Call.parameters().size();
 return ArgsMatch && ParamsMatch;
   };
 
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -40,12 +40,14 @@
 /// arguments and the name of the function.
 class CallDescription {
   friend class CallEvent;
+  using MaybeUInt = Optional;
+
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
   std::vector QualifiedName;
-  Optional RequiredArgs;
-  Optional RequiredParams;
+  MaybeUInt RequiredArgs;
+  MaybeUInt RequiredParams;
   int Flags;
 
 public:
@@ -60,13 +62,13 @@
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
   CallDescription(int Flags, ArrayRef QualifiedName,
-  Optional RequiredArgs = None,
-  Optional RequiredParams = None);
+  MaybeUInt RequiredArgs = None,
+  MaybeUInt RequiredParams = None);
 
   /// Construct a CallDescription with default flags.
   CallDescription(ArrayRef QualifiedName,
-  Optional RequiredArgs = None,
-  Optional RequiredParams = None);
+  MaybeUInt RequiredArgs = None,
+  MaybeUInt RequiredParams = None);
 
   

[PATCH] D113593: [analyzer][NFC] CallDescription should own the qualified name parts

2021-11-19 Thread Balázs Benics 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 rGde9d7e42aca2: [analyzer][NFC] CallDescription should own the 
qualified name parts (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113593

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp


Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
+#include 
 
 using namespace llvm;
 using namespace clang;
@@ -35,10 +36,12 @@
 int Flags, ArrayRef QualifiedName,
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
-: QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
+: RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
   assert(!QualifiedName.empty());
+  this->QualifiedName.reserve(QualifiedName.size());
+  llvm::copy(QualifiedName, std::back_inserter(this->QualifiedName));
 }
 
 /// Construct a CallDescription with default flags.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -43,7 +43,7 @@
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
-  std::vector QualifiedName;
+  std::vector QualifiedName;
   Optional RequiredArgs;
   Optional RequiredParams;
   int Flags;


Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
+#include 
 
 using namespace llvm;
 using namespace clang;
@@ -35,10 +36,12 @@
 int Flags, ArrayRef QualifiedName,
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
-: QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
+: RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
   assert(!QualifiedName.empty());
+  this->QualifiedName.reserve(QualifiedName.size());
+  llvm::copy(QualifiedName, std::back_inserter(this->QualifiedName));
 }
 
 /// Construct a CallDescription with default flags.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -43,7 +43,7 @@
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
-  std::vector QualifiedName;
+  std::vector QualifiedName;
   Optional RequiredArgs;
   Optional RequiredParams;
   int Flags;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D113592: [analyzer][NFC] Demonstrate the use of CallDescriptionSet

2021-11-19 Thread Balázs Benics 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 rG9ad0a90baa8c: [analyzer][NFC] Demonstrate the use of 
CallDescriptionSet (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113592

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


Index: clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -534,10 +534,12 @@
 namespace {
 class CFRetainReleaseChecker : public Checker {
   mutable APIMisuse BT{this, "null passed to CF memory management function"};
-  CallDescription CFRetain{"CFRetain", 1},
-  CFRelease{"CFRelease", 1},
-  CFMakeCollectable{"CFMakeCollectable", 1},
-  CFAutorelease{"CFAutorelease", 1};
+  const CallDescriptionSet ModelledCalls = {
+  {"CFRetain", 1},
+  {"CFRelease", 1},
+  {"CFMakeCollectable", 1},
+  {"CFAutorelease", 1},
+  };
 
 public:
   void checkPreCall(const CallEvent , CheckerContext ) const;
@@ -551,8 +553,7 @@
 return;
 
   // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
-
-  if (!matchesAny(Call, CFRetain, CFRelease, CFMakeCollectable, CFAutorelease))
+  if (!ModelledCalls.contains(Call))
 return;
 
   // Get the argument's value.


Index: clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -534,10 +534,12 @@
 namespace {
 class CFRetainReleaseChecker : public Checker {
   mutable APIMisuse BT{this, "null passed to CF memory management function"};
-  CallDescription CFRetain{"CFRetain", 1},
-  CFRelease{"CFRelease", 1},
-  CFMakeCollectable{"CFMakeCollectable", 1},
-  CFAutorelease{"CFAutorelease", 1};
+  const CallDescriptionSet ModelledCalls = {
+  {"CFRetain", 1},
+  {"CFRelease", 1},
+  {"CFMakeCollectable", 1},
+  {"CFAutorelease", 1},
+  };
 
 public:
   void checkPreCall(const CallEvent , CheckerContext ) const;
@@ -551,8 +553,7 @@
 return;
 
   // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
-
-  if (!matchesAny(Call, CFRetain, CFRelease, CFMakeCollectable, CFAutorelease))
+  if (!ModelledCalls.contains(Call))
 return;
 
   // Get the argument's value.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D113591: [analyzer][NFC] Switch to using CallDescription::matches() instead of isCalled()

2021-11-19 Thread Balázs Benics 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 rGf18da190b0db: [analyzer][NFC] Switch to using 
CallDescription::matches() instead of isCalled() (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113591

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
  clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
  clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp

Index: clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp
===
--- clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp
+++ clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp
@@ -86,17 +86,17 @@
 
 public:
   void checkPreCall(const CallEvent , CheckerContext ) const {
-if (Call.isCalled(CallDescription{"preventError", 0})) {
+if (CallDescription{"preventError", 0}.matches(Call)) {
   C.addTransition(C.getState()->set(true));
   return;
 }
 
-if (Call.isCalled(CallDescription{"allowError", 0})) {
+if (CallDescription{"allowError", 0}.matches(Call)) {
   C.addTransition(C.getState()->set(false));
   return;
 }
 
-if (Call.isCalled(CallDescription{"error", 0})) {
+if (CallDescription{"error", 0}.matches(Call)) {
   if (C.getState()->get())
 return;
   const ExplodedNode *N = C.generateErrorNode();
Index: clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
===
--- clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
+++ clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
@@ -22,7 +22,7 @@
 
 public:
   bool evalCall(const CallEvent , CheckerContext ) const {
-return Call.isCalled(Foo);
+return Foo.matches(Call);
   }
 };
 
Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -303,10 +303,6 @@
   return PostImplicitCall(D, Loc, getLocationContext(), Tag);
 }
 
-bool CallEvent::isCalled(const CallDescription ) const {
-  return CD.matches(*this);
-}
-
 SVal CallEvent::getArgSVal(unsigned Index) const {
   const Expr *ArgE = getArgExpr(Index);
   if (!ArgE)
Index: clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
@@ -39,7 +39,7 @@
 
 void PutenvWithAutoChecker::checkPostCall(const CallEvent ,
   CheckerContext ) const {
-  if (!Call.isCalled(Putenv))
+  if (!Putenv.matches(Call))
 return;
 
   SVal ArgV = Call.getArgSVal(0);
Index: clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
@@ -127,15 +127,15 @@
  CheckerContext ) const {
   if (!Call.isGlobalCFunction())
 return;
-  if (Call.isCalled(VaStart))
+  if (VaStart.matches(Call))
 checkVAListStartCall(Call, C, false);
-  else if (Call.isCalled(VaCopy))
+  else if (VaCopy.matches(Call))
 checkVAListStartCall(Call, C, true);
-  else if (Call.isCalled(VaEnd))
+  else if (VaEnd.matches(Call))
 checkVAListEndCall(Call, C);
   else {
 for (auto FuncInfo : VAListAccepters) {
-  if (!Call.isCalled(FuncInfo.Func))
+  if (!FuncInfo.Func.matches(Call))
 continue;
   bool Symbolic;
   const MemRegion *VAList =
Index: clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
+++ 

[PATCH] D113590: [analyzer][NFC] Introduce CallDescription::matches() in addition to isCalled()

2021-11-19 Thread Balázs Benics 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 rG6c512703a9e6: [analyzer][NFC] Introduce 
CallDescription::matches() in addition to isCalled() (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113590

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp

Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -304,85 +304,7 @@
 }
 
 bool CallEvent::isCalled(const CallDescription ) const {
-  // FIXME: Add ObjC Message support.
-  if (getKind() == CE_ObjCMessage)
-return false;
-
-  const auto *FD = dyn_cast_or_null(getDecl());
-  if (!FD)
-return false;
-
-  if (CD.Flags & CDF_MaybeBuiltin) {
-return CheckerContext::isCLibraryFunction(FD, CD.getFunctionName()) &&
-   (!CD.RequiredArgs || CD.RequiredArgs <= getNumArgs()) &&
-   (!CD.RequiredParams || CD.RequiredParams <= parameters().size());
-  }
-
-  if (!CD.II.hasValue()) {
-CD.II = ()->getStateManager().getContext().Idents.get(
-CD.getFunctionName());
-  }
-
-  const auto MatchNameOnly = [](const CallDescription ,
-const NamedDecl *ND) -> bool {
-DeclarationName Name = ND->getDeclName();
-if (const auto *II = Name.getAsIdentifierInfo())
-  return II == CD.II.getValue(); // Fast case.
-
-// Fallback to the slow stringification and comparison for:
-// C++ overloaded operators, constructors, destructors, etc.
-// FIXME This comparison is way SLOWER than comparing pointers.
-// At some point in the future, we should compare FunctionDecl pointers.
-return Name.getAsString() == CD.getFunctionName();
-  };
-
-  const auto ExactMatchArgAndParamCounts =
-  [](const CallEvent , const CallDescription ) -> bool {
-const bool ArgsMatch =
-!CD.RequiredArgs || CD.RequiredArgs == Call.getNumArgs();
-const bool ParamsMatch =
-!CD.RequiredParams || CD.RequiredParams == Call.parameters().size();
-return ArgsMatch && ParamsMatch;
-  };
-
-  const auto MatchQualifiedNameParts = [](const CallDescription ,
-  const Decl *D) -> bool {
-const auto FindNextNamespaceOrRecord =
-[](const DeclContext *Ctx) -> const DeclContext * {
-  while (Ctx && !isa(Ctx))
-Ctx = Ctx->getParent();
-  return Ctx;
-};
-
-auto QualifierPartsIt = CD.begin_qualified_name_parts();
-const auto QualifierPartsEndIt = CD.end_qualified_name_parts();
-
-// Match namespace and record names. Skip unrelated names if they don't
-// match.
-const DeclContext *Ctx = FindNextNamespaceOrRecord(D->getDeclContext());
-for (; Ctx && QualifierPartsIt != QualifierPartsEndIt;
- Ctx = FindNextNamespaceOrRecord(Ctx->getParent())) {
-  // If not matched just continue and try matching for the next one.
-  if (cast(Ctx)->getName() != *QualifierPartsIt)
-continue;
-  ++QualifierPartsIt;
-}
-
-// We matched if we consumed all expected qualifier segments.
-return QualifierPartsIt == QualifierPartsEndIt;
-  };
-
-  // Let's start matching...
-  if (!ExactMatchArgAndParamCounts(*this, CD))
-return false;
-
-  if (!MatchNameOnly(CD, FD))
-return false;
-
-  if (!CD.hasQualifiedNameParts())
-return true;
-
-  return MatchQualifiedNameParts(CD, FD);
+  return CD.matches(*this);
 }
 
 SVal CallEvent::getArgSVal(unsigned Index) const {
Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -14,6 +14,7 @@
 
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
 
@@ -47,6 +48,88 @@
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
+bool ento::CallDescription::matches(const CallEvent ) const {
+  // FIXME: Add ObjC Message support.
+  if (Call.getKind() == CE_ObjCMessage)
+return false;
+
+  const auto *FD = dyn_cast_or_null(Call.getDecl());
+  if (!FD)
+return false;
+
+  if (Flags & CDF_MaybeBuiltin) {
+return CheckerContext::isCLibraryFunction(FD, getFunctionName()) &&
+   (!RequiredArgs || RequiredArgs <= Call.getNumArgs()) &&
+  

[PATCH] D113589: [analyzer][NFC] Introduce CallDescriptionSets

2021-11-19 Thread Balázs Benics 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 rGd448fcd9b223: [analyzer][NFC] Introduce CallDescriptionSets 
(authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113589

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/lib/StaticAnalyzer/Core/CallDescription.cpp


Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -46,3 +46,14 @@
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
+
+ento::CallDescriptionSet::CallDescriptionSet(
+std::initializer_list &) {
+  Impl.LinearMap.reserve(List.size());
+  for (const CallDescription  : List)
+Impl.LinearMap.push_back({CD, /*unused*/ true});
+}
+
+bool ento::CallDescriptionSet::contains(const CallEvent ) const {
+  return static_cast(Impl.lookup(Call));
+}
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -88,6 +88,8 @@
 /// An immutable map from CallDescriptions to arbitrary data. Provides a 
unified
 /// way for checkers to react on function calls.
 template  class CallDescriptionMap {
+  friend class CallDescriptionSet;
+
   // Some call descriptions aren't easily hashable (eg., the ones with 
qualified
   // names in which some sections are omitted), so let's put them
   // in a simple vector and use linear lookup.
@@ -118,6 +120,21 @@
   }
 };
 
+/// An immutable set of CallDescriptions.
+/// Checkers can efficiently decide if a given CallEvent matches any
+/// CallDescription in the set.
+class CallDescriptionSet {
+  CallDescriptionMap Impl = {};
+
+public:
+  CallDescriptionSet(std::initializer_list &);
+
+  CallDescriptionSet(const CallDescriptionSet &) = delete;
+  CallDescriptionSet =(const CallDescription &) = delete;
+
+  LLVM_NODISCARD bool contains(const CallEvent ) const;
+};
+
 } // namespace ento
 } // namespace clang
 


Index: clang/lib/StaticAnalyzer/Core/CallDescription.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -46,3 +46,14 @@
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
+
+ento::CallDescriptionSet::CallDescriptionSet(
+std::initializer_list &) {
+  Impl.LinearMap.reserve(List.size());
+  for (const CallDescription  : List)
+Impl.LinearMap.push_back({CD, /*unused*/ true});
+}
+
+bool ento::CallDescriptionSet::contains(const CallEvent ) const {
+  return static_cast(Impl.lookup(Call));
+}
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -88,6 +88,8 @@
 /// An immutable map from CallDescriptions to arbitrary data. Provides a unified
 /// way for checkers to react on function calls.
 template  class CallDescriptionMap {
+  friend class CallDescriptionSet;
+
   // Some call descriptions aren't easily hashable (eg., the ones with qualified
   // names in which some sections are omitted), so let's put them
   // in a simple vector and use linear lookup.
@@ -118,6 +120,21 @@
   }
 };
 
+/// An immutable set of CallDescriptions.
+/// Checkers can efficiently decide if a given CallEvent matches any
+/// CallDescription in the set.
+class CallDescriptionSet {
+  CallDescriptionMap Impl = {};
+
+public:
+  CallDescriptionSet(std::initializer_list &);
+
+  CallDescriptionSet(const CallDescriptionSet &) = delete;
+  CallDescriptionSet =(const CallDescription &) = delete;
+
+  LLVM_NODISCARD bool contains(const CallEvent ) const;
+};
+
 } // namespace ento
 } // namespace clang
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e6ef134 - [analyzer][NFC] Use enum for CallDescription flags

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: e6ef134f3c77005438f9fb7c1d17d3c30747844e

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

LOG: [analyzer][NFC] Use enum for CallDescription flags

Yeah, let's prefer a slightly stronger type representing this.

Reviewed By: martong, xazax.hun

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
clang/lib/StaticAnalyzer/Checkers/DebugIteratorModeling.cpp
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index 88f67a03acfe..67db652a1e52 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -28,7 +28,9 @@ class IdentifierInfo;
 namespace clang {
 namespace ento {
 
-enum CallDescriptionFlags : int {
+enum CallDescriptionFlags : unsigned {
+  CDF_None = 0,
+
   /// Describes a C standard function that is sometimes implemented as a macro
   /// that expands to a compiler builtin with some __builtin prefix.
   /// The builtin may as well have a few extra arguments on top of the 
requested
@@ -61,7 +63,8 @@ class CallDescription {
   /// @param RequiredArgs The number of arguments that is expected to match a
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
-  CallDescription(int Flags, ArrayRef QualifiedName,
+  CallDescription(CallDescriptionFlags Flags,
+  ArrayRef QualifiedName,
   MaybeUInt RequiredArgs = None,
   MaybeUInt RequiredParams = None);
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
index c46a564f50b4..77a3218f55fb 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
@@ -72,42 +72,27 @@ class ContainerModeling
SVal) const;
 
   CallDescriptionMap NoIterParamFunctions = {
-{{0, "clear", 0},
- ::handleClear},
-{{0, "assign", 2},
- ::handleAssign},
-{{0, "push_back", 1},
- ::handlePushBack},
-{{0, "emplace_back", 1},
- ::handlePushBack},
-{{0, "pop_back", 0},
- ::handlePopBack},
-{{0, "push_front", 1},
- ::handlePushFront},
-{{0, "emplace_front", 1},
- ::handlePushFront},
-{{0, "pop_front", 0},
- ::handlePopFront},
+  {{"clear", 0}, ::handleClear},
+  {{"assign", 2}, ::handleAssign},
+  {{"push_back", 1}, ::handlePushBack},
+  {{"emplace_back", 1}, ::handlePushBack},
+  {{"pop_back", 0}, ::handlePopBack},
+  {{"push_front", 1}, ::handlePushFront},
+  {{"emplace_front", 1}, ::handlePushFront},
+  {{"pop_front", 0}, ::handlePopFront},
   };
-  
+
   CallDescriptionMap OneIterParamFunctions = {
-{{0, "insert", 2},
- ::handleInsert},
-{{0, "emplace", 2},
- ::handleInsert},
-{{0, "erase", 1},
- ::handleErase},
-{{0, "erase_after", 1},
- ::handleEraseAfter},
+  {{"insert", 2}, ::handleInsert},
+  {{"emplace", 2}, ::handleInsert},
+  {{"erase", 1}, ::handleErase},
+  {{"erase_after", 1}, ::handleEraseAfter},
   };
-  
+
   CallDescriptionMap TwoIterParamFunctions = {
-{{0, "erase", 2},
- ::handleErase},
-{{0, "erase_after", 2},
- ::handleEraseAfter},
+  {{"erase", 2}, ::handleErase},
+  {{"erase_after", 2}, ::handleEraseAfter},
   };
-  
 };
 
 bool isBeginCall(const FunctionDecl *Func);

diff  --git a/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp 
b/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
index b49027783a90..47fd57c7db9b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/DebugContainerModeling.cpp
@@ -41,10 +41,10 @@ class DebugContainerModeling
  CheckerContext &) const;
 
   CallDescriptionMap Callbacks = {
-{{0, "clang_analyzer_container_begin", 1},
- ::analyzerContainerBegin},
-{{0, "clang_analyzer_container_end", 1},
- ::analyzerContainerEnd},
+  

[clang] 97f1bf1 - [analyzer][NFC] Consolidate the inner representation of CallDescriptions

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: 97f1bf15b154ef32608fe17b82f2f312401d150c

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

LOG: [analyzer][NFC] Consolidate the inner representation of CallDescriptions

`CallDescriptions` have a `RequiredArgs` and `RequiredParams` members,
but they are of different types, `unsigned` and `size_t` respectively.
In the patch I use only `unsigned` for both, that should be large enough
anyway.
I also introduce the `MaybeUInt` type alias for `Optional`.

Additionally, I also avoid the use of the //smart// less-than operator.

  template 
  constexpr bool operator<=(const Optional , const T );

Which would check if the optional **has** a value and compare the data
only after. I found it surprising, thus I think we are better off
without it.

Reviewed By: martong, xazax.hun

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index abc2b93e32fe..88f67a03acfe 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -40,12 +40,14 @@ enum CallDescriptionFlags : int {
 /// arguments and the name of the function.
 class CallDescription {
   friend class CallEvent;
+  using MaybeUInt = Optional;
+
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
   std::vector QualifiedName;
-  Optional RequiredArgs;
-  Optional RequiredParams;
+  MaybeUInt RequiredArgs;
+  MaybeUInt RequiredParams;
   int Flags;
 
 public:
@@ -60,13 +62,13 @@ class CallDescription {
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
   CallDescription(int Flags, ArrayRef QualifiedName,
-  Optional RequiredArgs = None,
-  Optional RequiredParams = None);
+  MaybeUInt RequiredArgs = None,
+  MaybeUInt RequiredParams = None);
 
   /// Construct a CallDescription with default flags.
   CallDescription(ArrayRef QualifiedName,
-  Optional RequiredArgs = None,
-  Optional RequiredParams = None);
+  MaybeUInt RequiredArgs = None,
+  MaybeUInt RequiredParams = None);
 
   CallDescription(std::nullptr_t) = delete;
 

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index af541bdcfd59..9274f8a41165 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -22,20 +22,22 @@
 using namespace llvm;
 using namespace clang;
 
+using MaybeUInt = Optional;
+
 // A constructor helper.
-static Optional readRequiredParams(Optional RequiredArgs,
-   Optional RequiredParams) {
+static MaybeUInt readRequiredParams(MaybeUInt RequiredArgs,
+MaybeUInt RequiredParams) {
   if (RequiredParams)
 return RequiredParams;
   if (RequiredArgs)
-return static_cast(*RequiredArgs);
+return RequiredArgs;
   return None;
 }
 
-ento::CallDescription::CallDescription(
-int Flags, ArrayRef QualifiedName,
-Optional RequiredArgs /*= None*/,
-Optional RequiredParams /*= None*/)
+ento::CallDescription::CallDescription(int Flags,
+   ArrayRef QualifiedName,
+   MaybeUInt RequiredArgs /*= None*/,
+   MaybeUInt RequiredParams /*= None*/)
 : RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
@@ -45,10 +47,9 @@ ento::CallDescription::CallDescription(
 }
 
 /// Construct a CallDescription with default flags.
-ento::CallDescription::CallDescription(
-ArrayRef QualifiedName,
-Optional RequiredArgs /*= None*/,
-Optional RequiredParams /*= None*/)
+ento::CallDescription::CallDescription(ArrayRef QualifiedName,
+   MaybeUInt RequiredArgs /*= None*/,
+   MaybeUInt RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
 bool ento::CallDescription::matches(const CallEvent ) const {
@@ -62,8 +63,8 @@ bool 

[clang] de9d7e4 - [analyzer][NFC] CallDescription should own the qualified name parts

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: de9d7e42aca29920e9918ecaed4ad9c45fa673f1

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

LOG: [analyzer][NFC] CallDescription should own the qualified name parts

Previously, CallDescription simply referred to the qualified name parts
by `const char*` pointers.
In the future we might want to dynamically load and populate
`CallDescriptionMaps`, hence we will need the `CallDescriptions` to
actually **own** their qualified name parts.

Reviewed By: martong, xazax.hun

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index a35a5fb912eb..abc2b93e32fe 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -43,7 +43,7 @@ class CallDescription {
   mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
-  std::vector QualifiedName;
+  std::vector QualifiedName;
   Optional RequiredArgs;
   Optional RequiredParams;
   int Flags;

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index 3ab54de96f3f..af541bdcfd59 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
+#include 
 
 using namespace llvm;
 using namespace clang;
@@ -35,10 +36,12 @@ ento::CallDescription::CallDescription(
 int Flags, ArrayRef QualifiedName,
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
-: QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
+: RequiredArgs(RequiredArgs),
   RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
   Flags(Flags) {
   assert(!QualifiedName.empty());
+  this->QualifiedName.reserve(QualifiedName.size());
+  llvm::copy(QualifiedName, std::back_inserter(this->QualifiedName));
 }
 
 /// Construct a CallDescription with default flags.



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


[clang] 9ad0a90 - [analyzer][NFC] Demonstrate the use of CallDescriptionSet

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: 9ad0a90baa8ca8067fe65086056fffd083c86796

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

LOG: [analyzer][NFC] Demonstrate the use of CallDescriptionSet

Reviewed By: martong, xazax.hun

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

Added: 


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

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
index ebd384a5a5b4..2c210fb6cdb9 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -534,10 +534,12 @@ void CFNumberChecker::checkPreStmt(const CallExpr *CE,
 namespace {
 class CFRetainReleaseChecker : public Checker {
   mutable APIMisuse BT{this, "null passed to CF memory management function"};
-  CallDescription CFRetain{"CFRetain", 1},
-  CFRelease{"CFRelease", 1},
-  CFMakeCollectable{"CFMakeCollectable", 1},
-  CFAutorelease{"CFAutorelease", 1};
+  const CallDescriptionSet ModelledCalls = {
+  {"CFRetain", 1},
+  {"CFRelease", 1},
+  {"CFMakeCollectable", 1},
+  {"CFAutorelease", 1},
+  };
 
 public:
   void checkPreCall(const CallEvent , CheckerContext ) const;
@@ -551,8 +553,7 @@ void CFRetainReleaseChecker::checkPreCall(const CallEvent 
,
 return;
 
   // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
-
-  if (!matchesAny(Call, CFRetain, CFRelease, CFMakeCollectable, CFAutorelease))
+  if (!ModelledCalls.contains(Call))
 return;
 
   // Get the argument's value.



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


[clang] f18da19 - [analyzer][NFC] Switch to using CallDescription::matches() instead of isCalled()

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: f18da190b0dba817d33ccd7727537f12304d8125

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

LOG: [analyzer][NFC] Switch to using CallDescription::matches() instead of 
isCalled()

This patch replaces each use of the previous API with the new one.
In variadic cases, it will use the ADL `matchesAny(Call, CDs...)`
variadic function.
Also simplifies some code involving such operations.

Reviewed By: martong, xazax.hun

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
clang/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
clang/lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
clang/lib/StaticAnalyzer/Checkers/cert/PutenvWithAutoChecker.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp
clang/unittests/StaticAnalyzer/ConflictingEvalCallsTest.cpp
clang/unittests/StaticAnalyzer/NoStateChangeFuncVisitorTest.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
index 1e6b2457c706d..d135e70dd75dc 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -257,20 +257,6 @@ class CallEvent {
 return false;
   }
 
-  /// Returns true if the CallEvent is a call to a function that matches
-  /// the CallDescription.
-  ///
-  /// Note that this function is not intended to be used to match Obj-C method
-  /// calls.
-  bool isCalled(const CallDescription ) const;
-
-  /// Returns true whether the CallEvent is any of the CallDescriptions 
supplied
-  /// as a parameter.
-  template 
-  bool isCalled(const FirstCallDesc , const CallDescs &... Rest) const {
-return isCalled(First) || isCalled(Rest...);
-  }
-
   /// Returns a source range for the entire call, suitable for
   /// outputting in diagnostics.
   virtual SourceRange getSourceRange() const {

diff  --git a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
index 655facfed7d2e..ebd384a5a5b4c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
@@ -551,8 +551,8 @@ void CFRetainReleaseChecker::checkPreCall(const CallEvent 
,
 return;
 
   // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
-  if (!(Call.isCalled(CFRetain) || Call.isCalled(CFRelease) ||
-Call.isCalled(CFMakeCollectable) || Call.isCalled(CFAutorelease)))
+
+  if (!matchesAny(Call, CFRetain, CFRelease, CFMakeCollectable, CFAutorelease))
 return;
 
   // Get the argument's value.

diff  --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 86f3d0ff0fea1..8416ab39e1943 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -97,14 +97,7 @@ void 
BlockInCriticalSectionChecker::initIdentifierInfo(ASTContext ) const {
 }
 
 bool BlockInCriticalSectionChecker::isBlockingFunction(const CallEvent ) 
const {
-  if (Call.isCalled(SleepFn)
-  || Call.isCalled(GetcFn)
-  || Call.isCalled(FgetsFn)
-  || Call.isCalled(ReadFn)
-  || Call.isCalled(RecvFn)) {
-return true;
-  }
-  return false;
+  return matchesAny(Call, SleepFn, GetcFn, FgetsFn, ReadFn, RecvFn);
 }
 
 bool BlockInCriticalSectionChecker::isLockFunction(const CallEvent ) 
const {
@@ -114,15 +107,8 @@ bool BlockInCriticalSectionChecker::isLockFunction(const 
CallEvent ) const
   return true;
   }
 
-  if (Call.isCalled(LockFn)
-  || Call.isCalled(PthreadLockFn)
-  || Call.isCalled(PthreadTryLockFn)
-  || Call.isCalled(MtxLock)
-  || Call.isCalled(MtxTimedLock)
-  || Call.isCalled(MtxTryLock)) {
-return true;
-  }
-  return false;
+  return matchesAny(Call, LockFn, PthreadLockFn, PthreadTryLockFn, MtxLock,
+MtxTimedLock, 

[clang] 6c51270 - [analyzer][NFC] Introduce CallDescription::matches() in addition to isCalled()

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: 6c512703a9e6e495afa0f44528821c27f28db795

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

LOG: [analyzer][NFC] Introduce CallDescription::matches() in addition to 
isCalled()

This patch introduces `CallDescription::matches()` member function,
accepting a `CallEvent`.
Semantically, `Call.isCalled(CD)` is the same as `CD.matches(Call)`.

The patch also introduces the `matchesAny()` variadic free function template.
It accepts a `CallEvent` and at least one `CallDescription` to match
against.

Reviewed By: martong

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index b34e1c82eb7d..a35a5fb912eb 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -83,6 +83,33 @@ class CallDescription {
   /// It's false, if and only if we expect a single identifier, such as
   /// `getenv`. It's true for `std::swap`, or `my::detail::container::data`.
   bool hasQualifiedNameParts() const { return QualifiedName.size() > 1; }
+
+  /// @name Matching CallDescriptions against a CallEvent
+  /// @{
+
+  /// Returns true if the CallEvent is a call to a function that matches
+  /// the CallDescription.
+  ///
+  /// \note This function is not intended to be used to match Obj-C method
+  /// calls.
+  bool matches(const CallEvent ) const;
+
+  /// Returns true whether the CallEvent matches on any of the CallDescriptions
+  /// supplied.
+  ///
+  /// \note This function is not intended to be used to match Obj-C method
+  /// calls.
+  friend bool matchesAny(const CallEvent , const CallDescription ) {
+return CD1.matches(Call);
+  }
+
+  /// \copydoc clang::ento::matchesAny(const CallEvent &, const 
CallDescription &)
+  template 
+  friend bool matchesAny(const CallEvent , const CallDescription ,
+ const Ts &...CDs) {
+return CD1.matches(Call) || matchesAny(Call, CDs...);
+  }
+  /// @}
 };
 
 /// An immutable map from CallDescriptions to arbitrary data. Provides a 
unified
@@ -113,7 +140,7 @@ template  class CallDescriptionMap {
 // Slow path: linear lookup.
 // TODO: Implement some sort of fast path.
 for (const std::pair  : LinearMap)
-  if (Call.isCalled(I.first))
+  if (I.first.matches(Call))
 return 
 
 return nullptr;

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index 097cbf68f066..3ab54de96f3f 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -14,6 +14,7 @@
 
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
 
@@ -47,6 +48,88 @@ ento::CallDescription::CallDescription(
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
 
+bool ento::CallDescription::matches(const CallEvent ) const {
+  // FIXME: Add ObjC Message support.
+  if (Call.getKind() == CE_ObjCMessage)
+return false;
+
+  const auto *FD = dyn_cast_or_null(Call.getDecl());
+  if (!FD)
+return false;
+
+  if (Flags & CDF_MaybeBuiltin) {
+return CheckerContext::isCLibraryFunction(FD, getFunctionName()) &&
+   (!RequiredArgs || RequiredArgs <= Call.getNumArgs()) &&
+   (!RequiredParams || RequiredParams <= Call.parameters().size());
+  }
+
+  if (!II.hasValue()) {
+II = ()->getStateManager().getContext().Idents.get(
+getFunctionName());
+  }
+
+  const auto MatchNameOnly = [](const CallDescription ,
+const NamedDecl *ND) -> bool {
+DeclarationName Name = ND->getDeclName();
+if (const auto *II = Name.getAsIdentifierInfo())
+  return II == CD.II.getValue(); // Fast case.
+
+// Fallback to the slow stringification and comparison for:
+// C++ overloaded operators, constructors, destructors, etc.
+// FIXME This comparison is way SLOWER than comparing pointers.
+// At some point in the future, we should compare FunctionDecl pointers.
+return Name.getAsString() == CD.getFunctionName();
+  };
+
+  const auto 

[clang] d448fcd - [analyzer][NFC] Introduce CallDescriptionSets

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T18:32:13+01:00
New Revision: d448fcd9b2238377dd8832ce9e35a37b59ef5aeb

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

LOG: [analyzer][NFC] Introduce CallDescriptionSets

Sometimes we only want to decide if some function is called, and we
don't care which of the set.
This `CallDescriptionSet` will have the same behavior, except
instead of `lookup()` returning a pointer to the mapped value,
the `contains()` returns `bool`.
Internally, it uses the `CallDescriptionMap` for implementing the
behavior. It is preferred, to reuse the generic
`CallDescriptionMap::lookup()` logic, instead of duplicating it.
The generic version might be improved by implementing a hash lookup or
something along those lines.

Reviewed By: martong, Szelethus

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CallDescription.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index bbf58d753b1f6..b34e1c82eb7d6 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -88,6 +88,8 @@ class CallDescription {
 /// An immutable map from CallDescriptions to arbitrary data. Provides a 
unified
 /// way for checkers to react on function calls.
 template  class CallDescriptionMap {
+  friend class CallDescriptionSet;
+
   // Some call descriptions aren't easily hashable (eg., the ones with 
qualified
   // names in which some sections are omitted), so let's put them
   // in a simple vector and use linear lookup.
@@ -118,6 +120,21 @@ template  class CallDescriptionMap {
   }
 };
 
+/// An immutable set of CallDescriptions.
+/// Checkers can efficiently decide if a given CallEvent matches any
+/// CallDescription in the set.
+class CallDescriptionSet {
+  CallDescriptionMap Impl = {};
+
+public:
+  CallDescriptionSet(std::initializer_list &);
+
+  CallDescriptionSet(const CallDescriptionSet &) = delete;
+  CallDescriptionSet =(const CallDescription &) = delete;
+
+  LLVM_NODISCARD bool contains(const CallEvent ) const;
+};
+
 } // namespace ento
 } // namespace clang
 

diff  --git a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp 
b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
index 0589a2c2cb980..097cbf68f0660 100644
--- a/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallDescription.cpp
@@ -46,3 +46,14 @@ ento::CallDescription::CallDescription(
 Optional RequiredArgs /*= None*/,
 Optional RequiredParams /*= None*/)
 : CallDescription(0, QualifiedName, RequiredArgs, RequiredParams) {}
+
+ento::CallDescriptionSet::CallDescriptionSet(
+std::initializer_list &) {
+  Impl.LinearMap.reserve(List.size());
+  for (const CallDescription  : List)
+Impl.LinearMap.push_back({CD, /*unused*/ true});
+}
+
+bool ento::CallDescriptionSet::contains(const CallEvent ) const {
+  return static_cast(Impl.lookup(Call));
+}



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


[PATCH] D114256: [clang-tidy] Fix crashing altera-struct-pack-align on invalid RecordDecls

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: ffrankies, aaron.ballman, alexfh, njames93.
Herald added subscribers: carlosgalvezp, martong, xazax.hun.
steakhal requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

https://reviews.llvm.org/D114256

Files:
  clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
===
--- /dev/null
+++ 
clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
@@ -0,0 +1,8 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s altera-struct-pack-align 
%t -- -header-filter=.*
+
+// This should not crash.
+
+struct Foo {
+  member;
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:3: error: C++ requires a type specifier for 
all declarations [clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
===
--- clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
+++ clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
@@ -51,6 +51,10 @@
   if (Struct->isTemplated())
  return;
 
+  // Ignore invalid decls to prevent crashing on calling `getASTRecordLayout`.
+  if (Struct->isInvalidDecl())
+return;
+
   // Get sizing info for the struct.
   llvm::SmallVector, 10> FieldSizes;
   unsigned int TotalBitSize = 0;


Index: clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/altera-struct-pack-align-invalid-decl-no-crash.cpp
@@ -0,0 +1,8 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s altera-struct-pack-align %t -- -header-filter=.*
+
+// This should not crash.
+
+struct Foo {
+  member;
+};
+// CHECK-MESSAGES: :[[@LINE-2]]:3: error: C++ requires a type specifier for all declarations [clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
===
--- clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
+++ clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp
@@ -51,6 +51,10 @@
   if (Struct->isTemplated())
  return;
 
+  // Ignore invalid decls to prevent crashing on calling `getASTRecordLayout`.
+  if (Struct->isInvalidDecl())
+return;
+
   // Get sizing info for the struct.
   llvm::SmallVector, 10> FieldSizes;
   unsigned int TotalBitSize = 0;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114254: [libtooling][clang-tidy] Fix crashing on rendering invalid SourceRanges

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: aaron.ballman, njames93, klimek, alexfh.
Herald added subscribers: carlosgalvezp, martong, xazax.hun.
steakhal requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Invalid SourceRanges can occur generally if the code does not compile,
thus we expect clang error diagnostics.
Unlike `clang`, `clang-tidy` did not swallow invalid source ranges, but
tried to highlight them, and blow various assertions.

The following two examples produce invalid source ranges, but this is
not a complete list:

  void test(x); // error: unknown type name 'x'
  struct Foo {
member; // error: C++ requires a type specifier for all declarations
  };

Thanks @Whisperity helping me fix this.


https://reviews.llvm.org/D114254

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
  clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
@@ -37,6 +37,33 @@
   }
 };
 
+class InvalidRangeTestCheck : public ClangTidyCheck {
+public:
+  InvalidRangeTestCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override {
+Finder->addMatcher(ast_matchers::varDecl().bind("var"), this);
+  }
+  void check(const ast_matchers::MatchFinder::MatchResult ) override {
+const auto *Var = Result.Nodes.getNodeAs("var");
+SourceLocation ValidBeginLoc = Var->getBeginLoc();
+SourceLocation ValidEndLoc = Var->getEndLoc();
+SourceLocation InvalidLoc;
+ASSERT_TRUE(ValidBeginLoc.isValid());
+ASSERT_TRUE(ValidEndLoc.isValid());
+ASSERT_TRUE(InvalidLoc.isInvalid());
+
+diag(ValidBeginLoc, "valid->valid")
+<< SourceRange(ValidBeginLoc, ValidEndLoc);
+diag(ValidBeginLoc, "valid->invalid")
+<< SourceRange(ValidBeginLoc, InvalidLoc);
+diag(ValidBeginLoc, "invalid->valid")
+<< SourceRange(InvalidLoc, ValidEndLoc);
+diag(ValidBeginLoc, "invalid->invalid")
+<< SourceRange(InvalidLoc, InvalidLoc);
+  }
+};
+
 } // namespace
 
 TEST(ClangTidyDiagnosticConsumer, SortsErrors) {
@@ -66,6 +93,24 @@
   EXPECT_EQ(7ul, Errors[0].Message.Ranges[0].Length);
 }
 
+TEST(ClangTidyDiagnosticConsumer, InvalidSourceLocationRangesIgnored) {
+  std::vector Errors;
+  runCheckOnCode("int x;", );
+  EXPECT_EQ(4ul, Errors.size());
+
+  EXPECT_EQ("invalid->invalid", Errors[0].Message.Message);
+  EXPECT_EQ(0ul, Errors[0].Message.Ranges.size());
+
+  EXPECT_EQ("invalid->valid", Errors[1].Message.Message);
+  EXPECT_EQ(0ul, Errors[1].Message.Ranges.size());
+
+  EXPECT_EQ("valid->invalid", Errors[2].Message.Message);
+  EXPECT_EQ(0ul, Errors[2].Message.Ranges.size());
+
+  EXPECT_EQ("valid->valid", Errors[3].Message.Message);
+  EXPECT_EQ(1ul, Errors[3].Message.Ranges.size());
+}
+
 } // namespace test
 } // namespace tidy
 } // namespace clang
Index: clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
@@ -7,6 +7,11 @@
 int a[-1];
 int b[0];
 
+void test(x);
+struct Foo {
+  member;
+};
+
 // CHECK-MESSAGES: -input.cpp:2:1: warning: no previous prototype for function 'ff' [clang-diagnostic-missing-prototypes]
 // CHECK-MESSAGES: -input.cpp:1:19: note: expanded from macro 'X'
 // CHECK-MESSAGES: {{^}}note: expanded from here{{$}}
@@ -14,6 +19,8 @@
 // CHECK-MESSAGES: -input.cpp:1:14: note: expanded from macro 'X'
 // CHECK-MESSAGES: -input.cpp:3:7: error: 'a' declared as an array with a negative size [clang-diagnostic-error]
 // CHECK-MESSAGES: -input.cpp:4:7: warning: zero size arrays are an extension [clang-diagnostic-zero-length-array]
+// CHECK-MESSAGES: -input.cpp:6:11: error: unknown type name 'x' [clang-diagnostic-error]
+// CHECK-MESSAGES: -input.cpp:8:3: error: C++ requires a type specifier for all declarations [clang-diagnostic-error]
 
 // CHECK-YAML: ---
 // CHECK-YAML-NEXT: MainSourceFile:  '{{.*}}-input.cpp'
@@ -71,4 +78,20 @@
 // CHECK-YAML-NEXT:  Length:  1
 // CHECK-YAML-NEXT: Level:   Warning
 // CHECK-YAML-NEXT: BuildDirectory:  '{{.*}}'
+// CHECK-YAML-NEXT:   - DiagnosticName:  clang-diagnostic-error
+// CHECK-YAML-NEXT: DiagnosticMessage:
+// CHECK-YAML-NEXT:   Message: 'unknown type name ''x'''
+// CHECK-YAML-NEXT:   FilePath:'{{.*}}-input.cpp'
+// CHECK-YAML-NEXT:   

[Diffusion] rGc93f93b2e3f2: Revert "Revert "Recommit "Revert "[CVP] processSwitch: Remove default case when…

2021-11-19 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added subscribers: cfe-commits, alexfh, bgraur.

BRANCHES
  main

Users:
  junparser (Author)

https://reviews.llvm.org/rGc93f93b2e3f2

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


[PATCH] D103094: [analyzer] Implemented RangeSet::Factory::castTo function to perform promotions, truncations and conversions

2021-11-19 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 388512.
ASDenysPetrov added a comment.

Fixed missed part during rebasing in the unit test.


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

https://reviews.llvm.org/D103094

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
  
clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/unittests/StaticAnalyzer/RangeSetTest.cpp

Index: clang/unittests/StaticAnalyzer/RangeSetTest.cpp
===
--- clang/unittests/StaticAnalyzer/RangeSetTest.cpp
+++ clang/unittests/StaticAnalyzer/RangeSetTest.cpp
@@ -40,12 +40,18 @@
   const Range ) {
   return OS << toString(R);
 }
+LLVM_ATTRIBUTE_UNUSED static std::ostream <<(std::ostream ,
+  APSIntType Ty) {
+  return OS << (Ty.isUnsigned() ? "u" : "s") << Ty.getBitWidth();
+}
 
 } // namespace ento
 } // namespace clang
 
 namespace {
 
+template  constexpr bool is_signed_v = std::is_signed::value;
+
 template  struct TestValues {
   static constexpr T MIN = std::numeric_limits::min();
   static constexpr T MAX = std::numeric_limits::max();
@@ -53,7 +59,7 @@
   // which unary minus does not affect on,
   // e.g. int8/int32(0), uint8(128), uint32(2147483648).
   static constexpr T MID =
-  std::is_signed::value ? 0 : ~(static_cast(-1) / static_cast(2));
+  is_signed_v ? 0 : ~(static_cast(-1) / static_cast(2));
   static constexpr T A = MID - (MAX - MID) / 3 * 2;
   static constexpr T B = MID - (MAX - MID) / 3;
   static constexpr T C = -B;
@@ -61,8 +67,40 @@
 
   static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
 "Values shall be in an ascending order");
+  // Clear bits in low bytes by the given amount.
+  template 
+  static constexpr T ClearLowBytes =
+  static_cast(static_cast(Value)
+ << ((Bytes >= CHAR_BIT) ? 0 : Bytes) * CHAR_BIT);
+
+  template 
+  static constexpr T TruncZeroOf = ClearLowBytes;
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T XAAA = static_cast(
+  0b10101010'10101010'10101010'10101010'10101010'10101010'10101010'10101010);
+  template 
+  static constexpr T XAAATruncZeroOf = TruncZeroOf; // 0x'AB00
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T X555 = static_cast(
+  0b01010101'01010101'01010101'01010101'01010101'01010101'01010101'01010101);
+  template 
+  static constexpr T X555TruncZeroOf = TruncZeroOf; // 0x'5600
+
+  // Numbers for ranges with the same bits in the lowest byte.
+  // 0x'AA2A
+  static constexpr T FromA = ClearLowBytes + 42;
+  static constexpr T ToA = FromA + 2; // 0x'AA2C
+  // 0x'552A
+  static constexpr T FromB = ClearLowBytes + 42;
+  static constexpr T ToB = FromB + 2; // 0x'552C
 };
 
+template 
+static constexpr APSIntType APSIntTy = APSIntType(sizeof(T) * CHAR_BIT,
+  !is_signed_v);
+
 template  class RangeSetTest : public testing::Test {
 public:
   // Init block
@@ -74,21 +112,24 @@
   // End init block
 
   using Self = RangeSetTest;
-  using RawRange = std::pair;
-  using RawRangeSet = std::initializer_list;
-
-  const llvm::APSInt (BaseType X) {
-static llvm::APSInt Base{sizeof(BaseType) * CHAR_BIT,
- std::is_unsigned::value};
-Base = X;
-return BVF.getValue(Base);
+  template  using RawRangeT = std::pair;
+  template 
+  using RawRangeSetT = std::initializer_list>;
+  using RawRange = RawRangeT;
+  using RawRangeSet = RawRangeSetT;
+
+  template  const llvm::APSInt (T X) {
+static llvm::APSInt Int = APSIntTy.getZeroValue();
+Int = X;
+return BVF.getValue(Int);
   }
 
-  Range from(const RawRange ) {
+  template  Range from(const RawRangeT ) {
 return Range(from(Init.first), from(Init.second));
   }
 
-  RangeSet from(const RawRangeSet ) {
+  template 
+  RangeSet from(RawRangeSetT Init, APSIntType Ty = APSIntTy) {
 RangeSet RangeSet = F.getEmptySet();
 for (const auto  : Init) {
   RangeSet = F.add(RangeSet, from(Raw));
@@ -211,9 +252,20 @@
RawRangeSet RawExpected) {
 wrap(::checkDeleteImpl, Point, RawFrom, RawExpected);
   }
-};
 
-} // namespace
+  void checkCastToImpl(RangeSet What, APSIntType Ty, RangeSet Expected) {
+RangeSet Result = F.castTo(What, Ty);
+EXPECT_EQ(Result, Expected)
+<< "while casting " << toString(What) << " to " << Ty;
+  }
+
+  template 
+  void checkCastTo(RawRangeSetT What, RawRangeSetT Expected) {
+static constexpr APSIntType FromTy = APSIntTy;
+static constexpr APSIntType ToTy = APSIntTy;
+this->checkCastToImpl(from(What, FromTy), ToTy, from(Expected, ToTy));
+  }
+};
 
 using IntTypes = 

[PATCH] D114116: [clang][ARM] relax -mtp=cp15 for ARMv6 non-thumb cases

2021-11-19 Thread Peter Smith via Phabricator via cfe-commits
peter.smith added inline comments.



Comment at: clang/lib/Driver/ToolChains/Arch/ARM.cpp:155
+  llvm::ARM::ArchKind AK = llvm::ARM::parseArch(Triple.getArchName());
+  return Ver >= 7 || AK == llvm::ARM::ArchKind::ARMV6T2 ||
+ (Ver == 6 && Triple.isARM());

nickdesaulniers wrote:
> ardb wrote:
> > peter.smith wrote:
> > > Are we restricting based on whether the threadid register is present or 
> > > whether the instructions are available to access the cp15 registers?
> > > 
> > > If we're going by whether the CPU has the register present then it will be
> > > * A and R profile (not M profile, even the ones that have Thumb2)
> > > * V6K (includes ARM1176 but not ARM1156t2-s which has Thumb-2!) and V7+ 
> > > (A and R profile)
> > > 
> > > If we're going by the instructions to write to CP15 then it is:
> > > * Arm state (everything)
> > > * Thumb2 (v7 + v6t2)
> > > 
> > > The above seems to be a blend of the two. Is it worth choosing one form 
> > > or the other? GCC seems to use the latter. I guess using this option 
> > > falls into the I know what I'm doing area that accessing named system 
> > > registers comes into. If the kernel supports it the stricter version may 
> > > help catch more mistakes though.
> > > 
> > > The v7 A/R Arm ARM https://developer.arm.com/documentation/ddi0403/ed
> > > has in `D12.7.21 CP15 c13, Context ID support`
> > > ``` An ARMv6K implementation requires the Software Thread ID registers 
> > > described in VMSA CP15 c13
> > > register summary, Process, context and thread ID registers on page 
> > > B3-1474. ```
> > > 
> > > The Arm 1156-s (the only v6t2 processor) TRM 
> > > https://developer.arm.com/documentation/ddi0338/g/system-control-coprocessor/system-control-processor-registers/c13--process-id-register?lang=en
> > >  which shows only one process ID register under opcode 1 accessed via:
> > > ```
> > > MRC p15, 0, , c13, c0, 1 ;Read Process ID Register
> > > ```
> > > Whereas the ThreadID register is opcode 3 on CPUs that are v6k and v7.
> > The primary reason for tightening these checks was to avoid an assert in 
> > the backend when using -mtp=cp15 with a Thumb1 target, so I'd say this is 
> > more about whether the ISA has the opcode to begin with, rather than 
> > whether CPU x implements it or not.
> > Arm state (everything)
> 
> 
> Does that mean that `-march=armv5 -marm` has access/support for "CP15 C13 
> ThreadID" access?
The co-processor instructions are the same, but the effect of the instructions 
will depend on the CPU. For example on armv5 we can write the instruction to 
read/write to CP15 C13 with the ThreadID opcode. However on no armv5 
implementation will the CP15 C13 have a Thread ID register. 

The more complex stricter check will make sure that the implementations have 
the ThreadID register. As Ard mentions, the GCC intent seems to be whether the 
instruction is encodable rather than check what the CPU supports. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114116

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


[PATCH] D114108: [NFC][clang] Inclusive language: rename master variable to controller in debug-info-block-helper.m

2021-11-19 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 388511.
quinnp added a comment.

Changing master to controller in another testcase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114108

Files:
  clang/test/CodeGenObjC/debug-info-block-helper.m
  cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m


Index: cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
===
--- cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
+++ cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
@@ -11,7 +11,7 @@
 // CHECK: ${{[0-9]}} = 1
 // DEBUGGER: p dbTransaction
 // CHECK: ${{[0-9]}} = 0
-// DEBUGGER: p master
+// DEBUGGER: p controller
 // CHECK: ${{[0-9]}} = 0
 
 #include 
@@ -21,16 +21,16 @@
 @interface A:NSObject @end
 @implementation A
 - (void) helper {
- int master = 0;
+ int controller = 0;
  __block int m2 = 0;
  __block int dbTransaction = 0;
  int (^x)(void) = ^(void) { (void) self; 
-   (void) master; 
+   (void) controller; 
(void) dbTransaction; 
m2++;
return m2;
};
-  master = x();
+  controller = x();
 }
 @end
 
Index: clang/test/CodeGenObjC/debug-info-block-helper.m
===
--- clang/test/CodeGenObjC/debug-info-block-helper.m
+++ clang/test/CodeGenObjC/debug-info-block-helper.m
@@ -12,17 +12,17 @@
 @interface A:NSObject @end
 @implementation A
 - (void) helper {
- int master = 0;
+ int controller = 0;
  __block int m2 = 0;
  __block int dbTransaction = 0;
  int (^x)(void) = ^(void) { (void) self; 
-   (void) master; 
+   (void) controller; 
(void) dbTransaction; 
m2++;
return m2;
 
};
-  master = x();
+  controller = x();
 }
 @end
 


Index: cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
===
--- cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
+++ cross-project-tests/debuginfo-tests/llgdb-tests/blocks.m
@@ -11,7 +11,7 @@
 // CHECK: ${{[0-9]}} = 1
 // DEBUGGER: p dbTransaction
 // CHECK: ${{[0-9]}} = 0
-// DEBUGGER: p master
+// DEBUGGER: p controller
 // CHECK: ${{[0-9]}} = 0
 
 #include 
@@ -21,16 +21,16 @@
 @interface A:NSObject @end
 @implementation A
 - (void) helper {
- int master = 0;
+ int controller = 0;
  __block int m2 = 0;
  __block int dbTransaction = 0;
  int (^x)(void) = ^(void) { (void) self; 
-	(void) master; 
+	(void) controller; 
 	(void) dbTransaction; 
 	m2++;
 	return m2;
 	};
-  master = x();
+  controller = x();
 }
 @end
 
Index: clang/test/CodeGenObjC/debug-info-block-helper.m
===
--- clang/test/CodeGenObjC/debug-info-block-helper.m
+++ clang/test/CodeGenObjC/debug-info-block-helper.m
@@ -12,17 +12,17 @@
 @interface A:NSObject @end
 @implementation A
 - (void) helper {
- int master = 0;
+ int controller = 0;
  __block int m2 = 0;
  __block int dbTransaction = 0;
  int (^x)(void) = ^(void) { (void) self; 
-	(void) master; 
+	(void) controller; 
 	(void) dbTransaction; 
 	m2++;
 	return m2;
 
 	};
-  master = x();
+  controller = x();
 }
 @end
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114251: [AST] Add a sugar type for types found via UsingDecl

2021-11-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
Herald added subscribers: dexonsmith, usaxena95, kadircet, arphaman, martong.
sammccall requested review of this revision.
Herald added projects: clang, clang-tools-extra.
Herald added a subscriber: cfe-commits.

WIP:

- needs tests of new functionality
- doesn't handle template names/instantiations (unsure if same mechanism)
- maybe we should unify with UnresolvedUsingType
- maybe we should unify with TypedefType


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114251

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeLoc.h
  clang/include/clang/AST/TypeProperties.td
  clang/include/clang/Basic/TypeNodes.td
  clang/include/clang/Serialization/TypeBitCodes.def
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTDiagnostic.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
  clang/test/SemaCXX/warn-enum-compare.cpp
  clang/tools/libclang/CIndex.cpp
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- clang/unittests/Tooling/StencilTest.cpp
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -559,7 +559,7 @@
 
 TEST_F(StencilTest, DescribeUnqualifiedType) {
   std::string Snippet = "using N::C; C c; c;";
-  std::string Expected = "N::C";
+  std::string Expected = "C";
   auto StmtMatch =
   matchStmt(Snippet, declRefExpr(hasType(qualType().bind("type";
   ASSERT_TRUE(StmtMatch);
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1666,6 +1666,10 @@
   return Visit(TL.getPointeeLoc());
 }
 
+bool CursorVisitor::VisitUsingTypeLoc(UsingTypeLoc TL) {
+  return Visit(TL.getUnderlyingLoc());
+}
+
 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
   return Visit(TL.getModifiedLoc());
 }
Index: clang/test/SemaCXX/warn-enum-compare.cpp
===
--- clang/test/SemaCXX/warn-enum-compare.cpp
+++ clang/test/SemaCXX/warn-enum-compare.cpp
@@ -78,15 +78,15 @@
 
   while (B1 == B2); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
   while (name1::B2 == name2::B3); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
-  while (z == name2::B2); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
+  while (z == name2::B2); // expected-warning  {{comparison of different enumeration types ('Baz' and 'name2::Baz')}}
 
   while (B1 == B2); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
   while (name1::B2 == (name2::B3)); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
-  while (z == name2::B2); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
+  while (z == name2::B2); // expected-warning  {{comparison of different enumeration types ('Baz' and 'name2::Baz')}}
 
   while B1))) == (((B2; // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
   while ((name1::B2) == (((name2::B3; // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
-  while z))) == (name2::B2)); // expected-warning  {{comparison of different enumeration types ('name1::Baz' and 'name2::Baz')}}
+  while z))) == (name2::B2)); // expected-warning  {{comparison of different enumeration types ('Baz' and 'name2::Baz')}}
 
   while (x == a); // expected-warning  {{comparison of different enumeration types ('Foo' and 'name1::Foo')}}
   while (x == b); // expected-warning  {{comparison of different enumeration types ('Foo' and 'oneFoo' (aka 'name1::Foo'))}}
@@ -229,14 +229,14 @@
   while (td == c); // expected-warning  {{comparison of different enumeration types ('TD' and 'twoFoo' (aka 'name1::Foo'))}}
   while (td == x); // expected-warning  {{comparison of different enumeration types ('TD' and 'Foo')}}
   while (td == y); // 

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added a comment.

(Re repeated thanks: You're welcome. :) For the record, I personally see 
nothing wrong with the phrase "sanity-check" either; but given that it's gonna 
happen, and we're re-wording comments on by definition the subtlest and most 
confusing parts of the code, I'm trying to help us not to lose/distort the 
semantics of those comments. Some of these comments are even //improving// 
through this exercise.)




Comment at: clang/include/clang/AST/Redeclarable.h:261
   assert(Current && "Advancing while iterator has reached end");
-  // Sanity check to avoid infinite loop on invalid redecl chain.
+  // Validation check to avoid infinite loop on invalid redecl chain.
   if (Current->isFirstDecl()) {

aaron.ballman wrote:
> Quuxplusone wrote:
> > `// Make sure we don't infinite-loop on an invalid redecl chain. This 
> > should never happen.`
> Alternatively, "Make sure we don't infinitely loop..."
s/on on/on an/
Also, I think comments should always end with a period `.`, or is it the other 
way around? :)



Comment at: clang/include/clang/Sema/Lookup.h:709-710
 
-  // Sanity checks.
+  // Validation checks.
   bool sanity() const;
 

Quuxplusone wrote:
> The original comment strikes me as pretty useless, except that it's kind of 
> obliquely explaining the meaning of the ungrammatical `bool sanity() const`. 
> It could have been fixed better, pre-PC, by just removing the comment and 
> changing the function to `bool isSane() const`. I have no particular 
> suggestion for this one, other than "you'll have to look at how it's used" 
> and/or "just leave the comment alone, until you're ready to rename the actual 
> identifiers too" and/or "just delete the comment because it's useless."
The new version has the problem that `check()` is really vague, which again 
means that in order to explain what it does, you have to use the term 
"sanity-check". ;)  Perhaps change the identifier to `checkAssumptions()` or 
even `checkDebugAssumptions()`?
(Pre-existing problem: the name of the function still doesn't describe what it 
does, because it doesn't //check// or //assert// anything; it simply returns 
true or false, and it's up to the caller to `assert` on the return value. But 
`conformsToAssumptions()` is a silly name.)



Comment at: clang/lib/Basic/DiagnosticIDs.cpp:695
   StringRef Best;
-  unsigned BestDistance = Group.size() + 1; // Sanity threshold.
+  unsigned BestDistance = Group.size() + 1; // Minumum threshold.
   for (const WarningOption  : OptionTable) {

`Minimum`, and also, I think it's a maximum? :P



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:9176
   // Don't check the implicit member of the anonymous union type.
-  // This is technically non-conformant, but sanity demands it.
+  // This is technically non-conformant, but validation tests demand it.
   return false;

Quuxplusone wrote:
> Quuxplusone wrote:
> > This comment seems incorrectly translated.
> This comment //still// seems incorrectly translated.
> Things we do "for sanity's sake" aren't necessarily //required//, 
> technically; but we're doing them anyway, for sanity.
"Don't check ... but check it anyway"?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D113754: [Analyzer][Core] Simplify IntSym in SValBuilder

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Great news, thanks.




Comment at: clang/test/Analysis/svalbuilder-simplify-intsym.cpp:18
+return;
+  clang_analyzer_eval(x == 77); // expected-warning{{TRUE}}
+  (void)(x * y);

extra spaces?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113754

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


[PATCH] D114249: [clang-tidy] performance-unnecessary-copy-initialization: Fix false negative.

2021-11-19 Thread Clement Courbet via Phabricator via cfe-commits
courbet created this revision.
courbet added reviewers: flx, aaron.ballman.
Herald added subscribers: carlosgalvezp, xazax.hun.
courbet requested review of this revision.
Herald added a project: clang-tools-extra.

`isConstRefReturningMethodCall` should be considering
`CXXOperatorCallExpr` in addition to `CXXMemberCallExpr`. Clang considers
these to be distinct (`CXXOperatorCallExpr` derives from `CallExpr`, not
`CXXMemberCallExpr`), but we don't care in the context of this
check.

This is important because of
`std::vector::operator[](size_t) const`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114249

Files:
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
@@ -24,6 +24,11 @@
   operator int() const; // Implicit conversion to int.
 };
 
+struct ExpensiveToCopyContainer {
+  const ExpensiveToCopyType [](int) const;
+  const ExpensiveToCopyType [](int);
+};
+
 struct TrivialToCopyType {
   const TrivialToCopyType () const;
 };
@@ -138,6 +143,50 @@
   VarCopyConstructed.constMethod();
 }
 
+void PositiveOperatorCallConstReferenceParam(const ExpensiveToCopyContainer 
) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 
'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 
'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 
'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = C[42];
+  VarAssigned.constMethod();
+
+  const ExpensiveToCopyType VarCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 
'VarCopyConstructed'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarCopyConstructed(C[42]);
+  VarCopyConstructed.constMethod();
+}
+
+void PositiveOperatorCallConstValueParam(const ExpensiveToCopyContainer C) {
+  const auto AutoAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 
'AutoAssigned'
+  // CHECK-FIXES: const auto& AutoAssigned = C[42];
+  AutoAssigned.constMethod();
+
+  const auto AutoCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: the const qualified variable 
'AutoCopyConstructed'
+  // CHECK-FIXES: const auto& AutoCopyConstructed(C[42]);
+  AutoCopyConstructed.constMethod();
+
+  const ExpensiveToCopyType VarAssigned = C[42];
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 
'VarAssigned'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarAssigned = C[42];
+  VarAssigned.constMethod();
+
+  const ExpensiveToCopyType VarCopyConstructed(C[42]);
+  // CHECK-MESSAGES: [[@LINE-1]]:29: warning: the const qualified variable 
'VarCopyConstructed'
+  // CHECK-FIXES: const ExpensiveToCopyType& VarCopyConstructed(C[42]);
+  VarCopyConstructed.constMethod();
+}
+
 void PositiveLocalConstValue() {
   const ExpensiveToCopyType Obj;
   const auto UnnecessaryCopy = Obj.reference();
Index: 
clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
===
--- clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
+++ clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
@@ -83,15 +83,19 @@
   // variable being declared. The assumption is that the const reference being
   // returned either points to a global static variable or to a member of the
   // called object.
-  return cxxMemberCallExpr(
-  callee(cxxMethodDecl(
- returns(hasCanonicalType(matchers::isReferenceToConst(
- .bind(MethodDeclId)),
-  on(declRefExpr(to(
-  varDecl(
-  
unless(hasType(qualType(hasCanonicalType(hasDeclaration(namedDecl(
-  matchers::matchesAnyListedName(ExcludedContainerTypes
-  .bind(ObjectArgId);
+  const auto MethodDecl =
+  cxxMethodDecl(returns(hasCanonicalType(matchers::isReferenceToConst(
+  .bind(MethodDeclId);
+  const auto ReceiverExpr = declRefExpr(to(varDecl().bind(ObjectArgId)));
+  const auto ReceiverTypeDecl =
+  
namedDecl(unless(matchers::matchesAnyListedName(ExcludedContainerTypes)));
+
+  return expr(anyOf(
+ 

[PATCH] D114229: [clang][driver] Always add LTO options when using GNU toolchain

2021-11-19 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson added inline comments.



Comment at: clang/lib/Driver/ToolChains/Gnu.cpp:558
 assert(!Inputs.empty() && "Must have at least one input.");
 addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
   D.getLTOMode() == LTOK_Thin);

This will add a whole lot of options besides -plugin, which is the only thing 
guarded against for lld. But in general I'm not in favor of adding a dependence 
on having the LTO plugin available to all non-lld links by default.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114229

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


[PATCH] D114151: [clang-format] [C++20] [Module] clang-format couldn't recognize partitions

2021-11-19 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3235
+if (Left.is(TT_ModulePartitionColon) &&
+Right.isOneOf(tok::identifier, tok::kw_public, tok::kw_private))
+  return false;

owenpan wrote:
> Is `module :public` a thing in C++20? If not, I would remove `kw_public`.
For the record, my understanding is that `module :public` is not a thing, and 
neither is `module public:while` or any other combination of keywords 
//except// for `module :private`. (I don't even think `module foo:private` is a 
thing; is it?)
So +1 to removing `kw_public`. However, if the codebase happens to already have 
a function for `isIdentifierOrKeyword`, I think this would be a perfect place 
to use it. Consider an autoformatter-as-you-type dealing with `module 
foo:public[X]_methods` or `module :if[X]stream`.


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

https://reviews.llvm.org/D114151

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


[PATCH] D114151: [clang-format] [C++20] [Module] clang-format couldn't recognize partitions

2021-11-19 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3226
+// No space between module :.
+if (Left.isOneOf(Keywords.kw_module, tok::kw_export, Keywords.kw_import) &&
+Right.is(TT_ModulePartitionColon))

You can remove `kw_export` as it must be followed by `import` or `module`, 
based on how `TT_ModulePartitionColon` is set on Line 908.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3230-3231
+// No space between import foo:bar but keep a space between import :bar;
+if (Left.isOneOf(tok::identifier, tok::kw_public, tok::kw_private) &&
+!Left.is(Keywords.kw_import) && Right.is(TT_ModulePartitionColon))
+  return false;

You can drop `!Left.is(Keywords.kw_import)` as `import :bar` is already covered 
by Line 3226. Also, I would remove `kw_public` and `kw_private` as they are not 
special WRT other keywords when followed by `TT_ModulePartitionColon`.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3235
+if (Left.is(TT_ModulePartitionColon) &&
+Right.isOneOf(tok::identifier, tok::kw_public, tok::kw_private))
+  return false;

Is `module :public` a thing in C++20? If not, I would remove `kw_public`.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3238
+// import .;
+if (Left.is(Keywords.kw_import) && Right.is(tok::ellipsis))
+  return true;

You can fold this line into Line 3223 above.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1253
   }
+  if (Style.isCpp()) {
+nextToken();

Maybe move this entire block into a function?



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1260
+  // Handle import  as we would an include statement
+  if (FormatTok && FormatTok->is(tok::less)) {
+nextToken();

You can change this line to `else if (FormatTok->is(tok::less)) {` as 
`FormatTok` can't be null.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1262-1264
+while (FormatTok) {
+  if (FormatTok->is(tok::semi))
+break;

You can combine these three lines into one: `while (FormatTok && 
FormatTok->isNot(tok::semi)) {`



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1267-1268
+  // literals.
+  if (FormatTok->isNot(tok::comment) &&
+  !FormatTok->TokenText.startswith("//"))
+FormatTok->setType(TT_ImplicitStringLiteral);

Don't you want to mark up to the matching `>`?


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

https://reviews.llvm.org/D114151

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


[PATCH] D113754: [Analyzer][Core] Simplify IntSym in SValBuilder

2021-11-19 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D113754#3127245 , @steakhal wrote:

> Great stuff. Have you checked the coverage?

Thanks for the review! So, here are the coverage results for the new test file:

  1186   2 : SVal VisitIntSymExpr(const IntSymExpr *S) {
  1187   2 :   auto I = Cached.find(S);
  1188   2 :   if (I != Cached.end())
  1189   0 : return I->second;
  1190 :
  1191   2 :   SVal RHS = Visit(S->getRHS());
  1192   2 :   if (isUnchanged(S->getRHS(), RHS))
  1193   0 : return skip(S);
  1194   2 :   SVal LHS = SVB.makeIntVal(S->getLHS());
  1195 :   return cache(
  1196   2 :   S, SVB.evalBinOp(State, S->getOpcode(), LHS, 
RHS, S->getType()));
  1197 : }

L1189 is not covered, but that is related to the caching mechanism, which is 
already existing and this patch is independent from that. We have the very same 
caching implementation in all the other `Visit` functions.
L1193 There is an existing test case in `find-binop-constraints.cpp` which 
covers this line. :

  int test_lhs_and_rhs_further_constrained(int x, int y) {
if (x % y != 1)
  return 0;
if (x != 1)
  return 0;
if (y != 2)
  return 0;
clang_analyzer_eval(x % y == 1); // expected-warning{{TRUE}}
clang_analyzer_eval(y == 2); // expected-warning{{TRUE}}
return 0;
  }

I could have replicated this test case here, but hadn't been able to formulate 
any new expectations with a `clang_analyzer_` function. So there is no visible 
functional change in this case with this patch concerning this line. Besides, 
all other existing `Visit` functions have the same optimization and they do an 
early return with `skip` if the symbol is unchanged.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113754

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


[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA updated this revision to Diff 388494.
ZarkoCA added a comment.

- Add FIXME to comments and fix grammar on one comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

Files:
  clang/include/clang/AST/Redeclarable.h
  clang/include/clang/Analysis/CFG.h
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/include/clang/Sema/Lookup.h
  clang/lib/Analysis/BodyFarm.cpp
  clang/lib/Analysis/RetainSummaryManager.cpp
  clang/lib/Basic/DiagnosticIDs.cpp
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -126,7 +126,7 @@
   for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
-// FIXME: sanity-check the role.
+// FIXME: validate the role.
   }
 
   auto Reachable = [](Node *From, Node *N) {
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -249,7 +249,7 @@
 }
 
 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
-  // Sanity check to avoid doing the wrong thing in the face of
+  // Early return to avoid doing the wrong thing in the face of
   // reinterpret_cast.
   if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
 return UnknownVal();
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -326,8 +326,8 @@
 }
 Result = InitWithAdjustments;
   } else {
-// We need to create a region no matter what. For sanity, make sure we don't
-// try to stuff a Loc into a non-pointer temporary region.
+// We need to create a region no matter what. Make sure we don't try to
+// stuff a Loc into a non-pointer temporary region.
 assert(!InitValWithAdjustments.getAs() ||
Loc::isLocType(Result->getType()) ||
Result->getType()->isMemberPointerType());
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1670,9 +1670,10 @@
   if (isUnderconstrained(PrevN)) {
 IsSatisfied = true;
 
-// As a sanity check, make sure that the negation of the constraint
-// was infeasible in the current state.  If it is feasible, we somehow
-// missed the transition point.
+// At this point, the negation of the constraint should be infeasible. If it
+// is feasible, make sure that the negation of the constrainti was
+// infeasible in the current state.  If it is feasible, we somehow missed
+// the transition point.
 assert(!isUnderconstrained(N));
 
 // We found the transition point for the constraint.  We now need to
Index: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -182,8 +182,7 @@
   ProgramStateRef state = C.getState();
 
   if (CE->getNumArgs() < MinArgCount) {
-// The frontend should issue a warning for this case, so this is a sanity
-// check.
+// The frontend should issue a warning for this case. Just return.
 return;
   } else if (CE->getNumArgs() == MaxArgCount) {
 const Expr *Arg = CE->getArg(CreateModeArgIndex);
@@ -366,7 +365,7 @@
  const unsigned numArgs,
  const unsigned sizeArg,
  const char *fn) const {
-  // Sanity check for the correct number of arguments
+  // Check for the correct number of arguments.
   if (CE->getNumArgs() != numArgs)
 return;

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA marked 3 inline comments as done.
ZarkoCA added a comment.

In D114025#3142565 , @aaron.ballman 
wrote:

> In D114025#3141414 , @keryell wrote:
>
>> In D114025#3140192 , @Quuxplusone 
>> wrote:
>>
>>> I think "sanity-check" could be reasonably replaced with "smoke-test," but 
>>> (1) this PR doesn't do that, and (2) the phrase "smoke-test" is probably 
>>> //harder// to understand,
>>
>> It seems difficult considering the potential atmospheric pollution, carbon 
>> footprint, health issues, lung cancer, drug abuse, etc. implied.
>
> This is not a constructive comment either, please stop.
>
> In D114025#3141358 , @ZarkoCA wrote:
>
>> @Quuxplusone Thanks for thorough review.
>
> +1, you caught some stuff I was glossing over, but this is much improved. I 
> made a few tiny suggestions (take them or leave them). Continues to LGTM

Yes, agreed, the suggestions made this much better. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 388490.
sgatev added a comment.

Add using namespace declarations in the cpp file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,30 @@
+//===- DataflowAnalysis.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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+using namespace clang;
+using namespace dataflow;
+
+std::vector>
+runDataflowAnalysis(const CFG , DataflowAnalysisDynamic ,
+const Environment ) {
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- 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
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+
+namespace clang {
+namespace dataflow {
+
+/// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,164 @@
+//===- DataflowAnalysis.h ---*- 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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+
+#include 
+#include 
+#include 
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Any.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+/// Type-erased lattice element container.
+///
+/// 

[PATCH] D113540: [OpenMP] support depend clause for taskwait directive

2021-11-19 Thread Alexey Bataev 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 rG80256605f8c6: [OpenMP] support depend clause for taskwait 
directive, by Deepak (authored by ABataev).
Herald added projects: clang, OpenMP.
Herald added subscribers: openmp-commits, cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D113540?vs=386345=388488#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113540

Files:
  clang/docs/OpenMPSupport.rst
  clang/include/clang/AST/StmtOpenMP.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/StmtOpenMP.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/OpenMP/taskwait_ast_print.cpp
  clang/test/OpenMP/taskwait_depend_codegen.cpp
  clang/test/OpenMP/taskwait_depend_messages.cpp
  clang/test/OpenMP/taskwait_messages.cpp
  openmp/runtime/test/ompt/tasks/taskwait-depend.c
  openmp/runtime/test/tasking/omp50_taskwait_depend.c

Index: openmp/runtime/test/tasking/omp50_taskwait_depend.c
===
--- openmp/runtime/test/tasking/omp50_taskwait_depend.c
+++ openmp/runtime/test/tasking/omp50_taskwait_depend.c
@@ -1,11 +1,12 @@
 // RUN: %libomp-compile-and-run
 // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8
-// clang does not yet support taskwait with depend clause
-// clang-12 introduced parsing, but no codegen
-// TODO: update expected result when codegen in clang is added
+
+// support for taskwait with depend clause introduced in clang-14
+// UNSUPPORTED: clang-5, clang-6, clang-6, clang-8, clang-9, clang-10, clang-11,
+// clang-12, clang-13
+
 // icc does not yet support taskwait with depend clause
-// TODO: update expected result when support for icc is added
-// XFAIL: clang, icc
+// XFAIL: icc
 
 #include 
 #include 
Index: openmp/runtime/test/ompt/tasks/taskwait-depend.c
===
--- openmp/runtime/test/ompt/tasks/taskwait-depend.c
+++ openmp/runtime/test/ompt/tasks/taskwait-depend.c
@@ -7,10 +7,9 @@
 // icc does not yet support taskwait with depend clause
 // XFAIL: icc
 
-// clang does not yet support taskwait with depend clause
-// clang-12 introduced parsing, but no codegen
-// update expected result when codegen in clang was added
-// XFAIL: clang
+// support for taskwait with depend clause introduced in clang-14
+// UNSUPPORTED: clang-5, clang-6, clang-6, clang-8, clang-9, clang-10, clang-11,
+// clang-12, clang-13
 
 #include "callback.h"
 #include 
Index: clang/test/OpenMP/taskwait_messages.cpp
===
--- clang/test/OpenMP/taskwait_messages.cpp
+++ clang/test/OpenMP/taskwait_messages.cpp
@@ -1,10 +1,11 @@
-// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 %s -Wuninitialized
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -ferror-limit 100 %s -Wuninitialized
 
-// RUN: %clang_cc1 -verify -fopenmp-simd -ferror-limit 100 %s -Wuninitialized
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=45 -ferror-limit 100 %s -Wuninitialized
 
 template 
 T tmain(T argc) {
 #pragma omp taskwait allocate(argc) // expected-error {{unexpected OpenMP clause 'allocate' in directive '#pragma omp taskwait'}}
+#pragma omp taskwait depend(in:argc) // expected-error {{unexpected OpenMP clause 'depend' in directive '#pragma omp taskwait'}}
   ;
 #pragma omp taskwait untied  // expected-error {{unexpected OpenMP clause 'untied' in directive '#pragma omp taskwait'}}
 #pragma omp taskwait unknown // expected-warning {{extra tokens at the end of '#pragma omp taskwait' are ignored}}
Index: clang/test/OpenMP/taskwait_depend_messages.cpp
===
--- /dev/null
+++ clang/test/OpenMP/taskwait_depend_messages.cpp
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=50 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
+
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=50 -ferror-limit 100 -o - -std=c++11 %s -Wuninitialized
+
+void foo() {
+}
+
+bool foobool(int argc) {
+  return argc;
+}
+
+struct S1; // expected-note {{declared here}}
+
+class vector {
+  public:
+int operator[](int index) { return 0; }
+};
+
+int main(int argc, char **argv, char *env[]) {
+  vector vec;
+  typedef float V __attribute__((vector_size(16)));
+  V a;
+  auto arr = x; // expected-error {{use of undeclared identifier 'x'}}
+
+  #pragma omp taskwait depend // expected-error {{expected '(' after 'depend'}}
+  #pragma omp taskwait depend ( // expected-error {{expected depend modifier(iterator) or 'in', 'out', 'inout', 

[clang] 8025660 - [OpenMP] support depend clause for taskwait directive, by Deepak

2021-11-19 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2021-11-19T06:30:17-08:00
New Revision: 80256605f8c6aab8cb33ac3a3784aacd005087a3

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

LOG: [OpenMP] support depend clause for taskwait directive, by Deepak
Eachempati.

This patch adds clang (parsing, sema, serialization, codegen) support for the 
'depend' clause on the 'taskwait' directive.

Reviewed By: ABataev

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

Added: 
clang/test/OpenMP/taskwait_depend_codegen.cpp
clang/test/OpenMP/taskwait_depend_messages.cpp

Modified: 
clang/docs/OpenMPSupport.rst
clang/include/clang/AST/StmtOpenMP.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/AST/StmtOpenMP.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
clang/lib/CodeGen/CGStmtOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/test/OpenMP/taskwait_ast_print.cpp
clang/test/OpenMP/taskwait_messages.cpp
openmp/runtime/test/ompt/tasks/taskwait-depend.c
openmp/runtime/test/tasking/omp50_taskwait_depend.c

Removed: 




diff  --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index 0e3cd25e59e3c..8b530b9febef6 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -147,7 +147,7 @@ implementation.
 
+--+--+--+---+
 | task extension   | task affinity 
   | :part:`not upstream` | 
https://github.com/jklinkenberg/openmp/tree/task-affinity |
 
+--+--+--+---+
-| task extension   | clause: depend on the taskwait construct  
   | :part:`worked on`| 
  |
+| task extension   | clause: depend on the taskwait construct  
   | :part:`mostly done`  | D113540 (regular codegen only)  
  |
 
+--+--+--+---+
 | task extension   | depend objects and detachable tasks   
   | :good:`done` | 
  |
 
+--+--+--+---+

diff  --git a/clang/include/clang/AST/StmtOpenMP.h 
b/clang/include/clang/AST/StmtOpenMP.h
index 48b2dce152a64..d5b5c9580da9e 100644
--- a/clang/include/clang/AST/StmtOpenMP.h
+++ b/clang/include/clang/AST/StmtOpenMP.h
@@ -2569,15 +2569,20 @@ class OMPTaskwaitDirective : public 
OMPExecutableDirective {
   /// \param C AST context.
   /// \param StartLoc Starting location of the directive kind.
   /// \param EndLoc Ending Location of the directive.
+  /// \param Clauses List of clauses.
   ///
-  static OMPTaskwaitDirective *
-  Create(const ASTContext , SourceLocation StartLoc, SourceLocation EndLoc);
+  static OMPTaskwaitDirective *Create(const ASTContext ,
+  SourceLocation StartLoc,
+  SourceLocation EndLoc,
+  ArrayRef Clauses);
 
   /// Creates an empty directive.
   ///
   /// \param C AST context.
+  /// \param NumClauses Number of clauses.
   ///
-  static OMPTaskwaitDirective *CreateEmpty(const ASTContext , EmptyShell);
+  static OMPTaskwaitDirective *CreateEmpty(const ASTContext ,
+   unsigned NumClauses, EmptyShell);
 
   static bool classof(const Stmt *T) {
 return T->getStmtClass() == OMPTaskwaitDirectiveClass;

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 50c1e0a1746bc..dc67f86f25cab 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10599,6 +10599,8 @@ def err_omp_depend_sink_unexpected_expr : Error<
   "unexpected expression: number of expressions is larger than the number of 
associated loops">;
 def 

[PATCH] D114229: [clang][driver] Always add LTO options when using GNU toolchain

2021-11-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

The test failures are pretty obvious about when this fails. All affected builds 
have an implicit dependency on the `LLVMgold.so` like this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114229

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


[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp:21-22
+
+namespace clang {
+namespace dataflow {
+

It's more common in .cpp files to use using declarations instead:
```
using clang;
using dataflow;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

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


[PATCH] D114099: Enable `_Float16` type support on X86 without the avx512fp16 flag

2021-11-19 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

rG6623c02d70c3 



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

https://reviews.llvm.org/D114099

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


[PATCH] D114206: [Clang][ScanDeps] Use the virtual path for module maps

2021-11-19 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added a comment.
This revision is now accepted and ready to land.

LGTM provided the Windows crash gets resolved.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114206

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


[PATCH] D103094: [analyzer] Implemented RangeSet::Factory::castTo function to perform promotions, truncations and conversions

2021-11-19 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 388481.
ASDenysPetrov added a comment.

Rebased.


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

https://reviews.llvm.org/D103094

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
  
clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/unittests/StaticAnalyzer/RangeSetTest.cpp

Index: clang/unittests/StaticAnalyzer/RangeSetTest.cpp
===
--- clang/unittests/StaticAnalyzer/RangeSetTest.cpp
+++ clang/unittests/StaticAnalyzer/RangeSetTest.cpp
@@ -40,12 +40,18 @@
   const Range ) {
   return OS << toString(R);
 }
+LLVM_ATTRIBUTE_UNUSED static std::ostream <<(std::ostream ,
+  APSIntType Ty) {
+  return OS << (Ty.isUnsigned() ? "u" : "s") << Ty.getBitWidth();
+}
 
 } // namespace ento
 } // namespace clang
 
 namespace {
 
+template  constexpr bool is_signed_v = std::is_signed::value;
+
 template  struct TestValues {
   static constexpr T MIN = std::numeric_limits::min();
   static constexpr T MAX = std::numeric_limits::max();
@@ -53,7 +59,7 @@
   // which unary minus does not affect on,
   // e.g. int8/int32(0), uint8(128), uint32(2147483648).
   static constexpr T MID =
-  std::is_signed::value ? 0 : ~(static_cast(-1) / static_cast(2));
+  is_signed_v ? 0 : ~(static_cast(-1) / static_cast(2));
   static constexpr T A = MID - (MAX - MID) / 3 * 2;
   static constexpr T B = MID - (MAX - MID) / 3;
   static constexpr T C = -B;
@@ -61,8 +67,40 @@
 
   static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
 "Values shall be in an ascending order");
+  // Clear bits in low bytes by the given amount.
+  template 
+  static const T ClearLowBytes = static_cast(static_cast(Value)
+<< ((Bytes >= 8) ? 0 : Bytes) *
+   8);
+
+  template 
+  static constexpr T TruncZeroOf = ClearLowBytes;
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T XAAA = static_cast(
+  0b10101010'10101010'10101010'10101010'10101010'10101010'10101010'10101010);
+  template 
+  static constexpr T XAAATruncZeroOf = TruncZeroOf; // 0x'AB00
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T X555 = static_cast(
+  0b01010101'01010101'01010101'01010101'01010101'01010101'01010101'01010101);
+  template 
+  static constexpr T X555TruncZeroOf = TruncZeroOf; // 0x'5600
+
+  // Numbers for ranges with the same bits in the lowest byte.
+  // 0x'AA2A
+  static constexpr T FromA = ClearLowBytes + 42;
+  static constexpr T ToA = FromA + 2; // 0x'AA2C
+  // 0x'552A
+  static constexpr T FromB = ClearLowBytes + 42;
+  static constexpr T ToB = FromB + 2; // 0x'552C
 };
 
+template 
+static constexpr APSIntType APSIntTy = APSIntType(sizeof(T) * 8,
+  !is_signed_v);
+
 template  class RangeSetTest : public testing::Test {
 public:
   // Init block
@@ -74,8 +112,11 @@
   // End init block
 
   using Self = RangeSetTest;
-  using RawRange = std::pair;
-  using RawRangeSet = std::initializer_list;
+  template  using RawRangeT = std::pair;
+  template 
+  using RawRangeSetT = std::initializer_list>;
+  using RawRange = RawRangeT;
+  using RawRangeSet = RawRangeSetT;
 
   const llvm::APSInt (BaseType X) {
 static llvm::APSInt Base{sizeof(BaseType) * CHAR_BIT,
@@ -84,11 +125,12 @@
 return BVF.getValue(Base);
   }
 
-  Range from(const RawRange ) {
+  template  Range from(const RawRangeT ) {
 return Range(from(Init.first), from(Init.second));
   }
 
-  RangeSet from(const RawRangeSet ) {
+  template 
+  RangeSet from(RawRangeSetT Init, APSIntType Ty = APSIntTy) {
 RangeSet RangeSet = F.getEmptySet();
 for (const auto  : Init) {
   RangeSet = F.add(RangeSet, from(Raw));
@@ -211,9 +253,20 @@
RawRangeSet RawExpected) {
 wrap(::checkDeleteImpl, Point, RawFrom, RawExpected);
   }
-};
 
-} // namespace
+  void checkCastToImpl(RangeSet What, APSIntType Ty, RangeSet Expected) {
+RangeSet Result = F.castTo(What, Ty);
+EXPECT_EQ(Result, Expected)
+<< "while casting " << toString(What) << " to " << Ty;
+  }
+
+  template 
+  void checkCastTo(RawRangeSetT What, RawRangeSetT Expected) {
+static constexpr APSIntType FromTy = APSIntTy;
+static constexpr APSIntType ToTy = APSIntTy;
+this->checkCastToImpl(from(What, FromTy), ToTy, from(Expected, ToTy));
+  }
+};
 
 using IntTypes = ::testing::Types;
@@ -591,3 +644,425 @@
{{MIN, MIN}, {B, MID}, {MID + 1, C}, {C + 4, D - 1}},
{{MIN, MIN}, {A, C}, {C + 2, D}, {MAX - 1, MAX}});
 }
+
+template  

[clang] 6623c02 - The _Float16 type is supported on x86 systems with SSE2 enabled.

2021-11-19 Thread Zahira Ammarguellat via cfe-commits

Author: Zahira Ammarguellat
Date: 2021-11-19T08:59:50-05:00
New Revision: 6623c02d70c3732dbea59c6d79c69501baf9627b

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

LOG: The _Float16 type is supported on x86 systems with SSE2 enabled.
Operations are emulated by software emulation and “float” instructions.
This patch is allowing the support of _Float16 type without the use of
-max512fp16 flag. The final goal being, perform _Float16 emulation for
all arithmetic expressions.

Added: 
clang/test/CodeGen/X86/Float16-arithmetic.c
clang/test/CodeGen/X86/fp16-abi.c
clang/test/CodeGen/X86/fp16-complex.c

Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/ReleaseNotes.rst
clang/lib/Basic/Targets/X86.cpp
clang/test/Sema/Float16.c
clang/test/Sema/conversion-target-dep.c
clang/test/SemaCXX/Float16.cpp

Removed: 
clang/test/CodeGen/X86/avx512fp16-abi.c
clang/test/CodeGen/X86/avx512fp16-complex.c



diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 60b1ed383a1ff..dfdb01b8ff542 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -673,7 +673,7 @@ targets pending ABI standardization:
 * 64-bit ARM (AArch64)
 * AMDGPU
 * SPIR
-* X86 (Only available under feature AVX512-FP16)
+* X86 (Available with feature SSE2 and up enabled)
 
 ``_Float16`` will be supported on more targets as they define ABIs for it.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 104d2e908d809..d2fa7ff05a160 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -187,6 +187,7 @@ X86 Support in Clang
 
 
 - Support for ``AVX512-FP16`` instructions has been added.
+- Support for ``_Float16`` type has been added.
 
 Arm and AArch64 Support in Clang
 

diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index 454a7743dded3..5e36868937194 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -239,9 +239,9 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector ,
   HasAVX512ER = true;
 } else if (Feature == "+avx512fp16") {
   HasAVX512FP16 = true;
-  HasFloat16 = true;
 } else if (Feature == "+avx512pf") {
   HasAVX512PF = true;
+  HasLegalHalfType = true;
 } else if (Feature == "+avx512dq") {
   HasAVX512DQ = true;
 } else if (Feature == "+avx512bitalg") {
@@ -369,6 +369,8 @@ bool 
X86TargetInfo::handleTargetFeatures(std::vector ,
  .Default(NoXOP);
 XOPLevel = std::max(XOPLevel, XLevel);
   }
+  // Turn on _float16 for x86 (feature sse2)
+  HasFloat16 = SSELevel >= SSE2;
 
   // LLVM doesn't have a separate switch for fpmath, so only accept it if it
   // matches the selected sse level.

diff  --git a/clang/test/CodeGen/X86/Float16-arithmetic.c 
b/clang/test/CodeGen/X86/Float16-arithmetic.c
new file mode 100644
index 0..7f7b3ff594424
--- /dev/null
+++ b/clang/test/CodeGen/X86/Float16-arithmetic.c
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -triple  x86_64-unknown-unknown -emit-llvm  \
+// RUN: < %s  | FileCheck %s --check-prefixes=CHECK
+
+_Float16 add1(_Float16 a, _Float16 b) {
+  // CHECK-LABEL: define{{.*}} half @add1
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: load half, half*
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fadd half {{.*}}, {{.*}}
+  // CHECK: ret half
+  return a + b;
+}
+
+_Float16 add2(_Float16 a, _Float16 b, _Float16 c) {
+  // CHECK-LABEL: define{{.*}} half @add2
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: load half, half* {{.*}}
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fadd half {{.*}}, {{.*}}
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fadd half {{.*}}, {{.*}}
+  // CHECK: ret half
+return a + b + c;
+}
+
+_Float16 sub(_Float16 a, _Float16 b) {
+  // CHECK-LABEL: define{{.*}} half @sub
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: load half, half*
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fsub half {{.*}}, {{.*}}
+  // CHECK: ret half
+  return a - b;
+}
+
+_Float16 div(_Float16 a, _Float16 b) {
+  // CHECK-LABEL: define{{.*}} half @div
+  // CHECK: alloca half
+  // CHECK: alloca half
+  // CHECK: store half {{.*}}, half*
+  // CHECK: store half {{.*}}, half*
+  // CHECK: load half, half* {{.*}}
+  // CHECK: load half, half* {{.*}}
+  // CHECK: fdiv half {{.*}}, {{.*}}
+  // 

[clang] c227192 - Make clang-format fuzz through Lexing with asserts enabled.

2021-11-19 Thread Manuel Klimek via cfe-commits

Author: Manuel Klimek
Date: 2021-11-19T14:44:06+01:00
New Revision: c2271926a4fc395e05cf75a8e57c2dfab1f02d3d

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

LOG: Make clang-format fuzz through Lexing with asserts enabled.

Makes clang-format bail out if an in-memory source file with an
unsupported BOM is handed in instead of creating source locations that
are violating clang's assumptions.

In the future, we should add support to better transport error messages
like this through clang-format instead of printing to stderr and not
creating any changes.

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/lib/Format/SortJavaScriptImports.cpp
clang/lib/Format/TokenAnalyzer.cpp
clang/lib/Format/TokenAnalyzer.h

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 1d60f2b3a321b..085cca8853e62 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2989,8 +2989,10 @@ reformat(const FormatStyle , StringRef Code,
   if (Style.isJson()) {
 std::vector Ranges(1, tooling::Range(0, Code.size()));
 auto Env =
-std::make_unique(Code, FileName, Ranges, FirstStartColumn,
+Environment::make(Code, FileName, Ranges, FirstStartColumn,
   NextStartColumn, LastStartColumn);
+if (!Env)
+  return {};
 // Perform the actual formatting pass.
 tooling::Replacements Replaces =
 Formatter(*Env, Style, Status).process().first;
@@ -3046,9 +3048,10 @@ reformat(const FormatStyle , StringRef Code,
   return TrailingCommaInserter(Env, Expanded).process();
 });
 
-  auto Env =
-  std::make_unique(Code, FileName, Ranges, FirstStartColumn,
-NextStartColumn, LastStartColumn);
+  auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
+   NextStartColumn, LastStartColumn);
+  if (!Env)
+return {};
   llvm::Optional CurrentCode = None;
   tooling::Replacements Fixes;
   unsigned Penalty = 0;
@@ -3061,10 +3064,12 @@ reformat(const FormatStyle , StringRef Code,
   Penalty += PassFixes.second;
   if (I + 1 < E) {
 CurrentCode = std::move(*NewCode);
-Env = std::make_unique(
+Env = Environment::make(
 *CurrentCode, FileName,
 tooling::calculateRangesAfterReplacements(Fixes, Ranges),
 FirstStartColumn, NextStartColumn, LastStartColumn);
+if (!Env)
+  return {};
   }
 }
   }
@@ -3090,7 +3095,10 @@ tooling::Replacements cleanup(const FormatStyle , 
StringRef Code,
   // cleanups only apply to C++ (they mostly concern ctor commas etc.)
   if (Style.Language != FormatStyle::LK_Cpp)
 return tooling::Replacements();
-  return Cleaner(Environment(Code, FileName, Ranges), Style).process().first;
+  auto Env = Environment::make(Code, FileName, Ranges);
+  if (!Env)
+return {};
+  return Cleaner(*Env, Style).process().first;
 }
 
 tooling::Replacements reformat(const FormatStyle , StringRef Code,
@@ -3107,7 +3115,10 @@ tooling::Replacements fixNamespaceEndComments(const 
FormatStyle ,
   StringRef Code,
   ArrayRef Ranges,
   StringRef FileName) {
-  return NamespaceEndCommentsFixer(Environment(Code, FileName, Ranges), Style)
+  auto Env = Environment::make(Code, FileName, Ranges);
+  if (!Env)
+return {};
+  return NamespaceEndCommentsFixer(*Env, Style)
   .process()
   .first;
 }
@@ -3116,7 +3127,10 @@ tooling::Replacements sortUsingDeclarations(const 
FormatStyle ,
 StringRef Code,
 ArrayRef Ranges,
 StringRef FileName) {
-  return UsingDeclarationsSorter(Environment(Code, FileName, Ranges), Style)
+  auto Env = Environment::make(Code, FileName, Ranges);
+  if (!Env)
+return {};
+  return UsingDeclarationsSorter(*Env, Style)
   .process()
   .first;
 }

diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index c70705a1cd7ff..5a89225c7fc86 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -61,10 +61,10 @@ QualifierAlignmentFixer::QualifierAlignmentFixer(
 std::pair QualifierAlignmentFixer::analyze(
 TokenAnnotator , SmallVectorImpl 
,
 FormatTokenLexer ) {
-
-  auto Env =
-  std::make_unique(Code, FileName, Ranges, FirstStartColumn,
-NextStartColumn, LastStartColumn);
+  auto Env = 

[PATCH] D114025: [clang][NFC] Inclusive terms: replace some uses of sanity in clang

2021-11-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

In D114025#3141414 , @keryell wrote:

> In D114025#3140192 , @Quuxplusone 
> wrote:
>
>> I think "sanity-check" could be reasonably replaced with "smoke-test," but 
>> (1) this PR doesn't do that, and (2) the phrase "smoke-test" is probably 
>> //harder// to understand,
>
> It seems difficult considering the potential atmospheric pollution, carbon 
> footprint, health issues, lung cancer, drug abuse, etc. implied.

This is not a constructive comment either, please stop.

In D114025#3141358 , @ZarkoCA wrote:

> @Quuxplusone Thanks for thorough review.

+1, you caught some stuff I was glossing over, but this is much improved. I 
made a few tiny suggestions (take them or leave them). Continues to LGTM




Comment at: clang/include/clang/AST/Redeclarable.h:261
   assert(Current && "Advancing while iterator has reached end");
-  // Sanity check to avoid infinite loop on invalid redecl chain.
+  // Validation check to avoid infinite loop on invalid redecl chain.
   if (Current->isFirstDecl()) {

Quuxplusone wrote:
> `// Make sure we don't infinite-loop on an invalid redecl chain. This should 
> never happen.`
Alternatively, "Make sure we don't infinitely loop..."



Comment at: clang/lib/Sema/SemaChecking.cpp:5536
+// GCC does not enforce these rules for GNU atomics, but we do, because if
+// we didn't it would be very confusing [For whom? How so?]
 auto IsAllowedValueType = [&](QualType ValType) {





Comment at: clang/lib/Sema/SemaChecking.cpp:5578
+// the GNU atomics specification, but we enforce it, because if we didn't 
it
+// would be very confusing [For whom? How so?]
 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114025

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


[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 388469.
sgatev added a comment.

Use triple slash at the start of declaration comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,33 @@
+//===- DataflowAnalysis.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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+std::vector>
+runDataflowAnalysis(const CFG , DataflowAnalysisDynamic ,
+const Environment ) {
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
+
+} // namespace dataflow
+} // namespace clang
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- 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
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+
+namespace clang {
+namespace dataflow {
+
+/// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,164 @@
+//===- DataflowAnalysis.h ---*- 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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+
+#include 
+#include 
+#include 
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Any.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+/// Type-erased 

[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 388465.
sgatev added a comment.

Fix ifndefs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,33 @@
+//===- DataflowAnalysis.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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+std::vector>
+runDataflowAnalysis(const CFG , DataflowAnalysisDynamic ,
+const Environment ) {
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
+
+} // namespace dataflow
+} // namespace clang
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- 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
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
+
+namespace clang {
+namespace dataflow {
+
+// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,162 @@
+//===- DataflowAnalysis.h ---*- 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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
+
+#include 
+#include 
+#include 
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Any.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+// Type-erased lattice element container.
+//
+// 

[PATCH] D114235: [clang] Extend ParsedAttr to allow custom handling for type attributes

2021-11-19 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
mboehme added a reviewer: aaron.ballman.
mboehme added a project: clang.
mboehme requested review of this revision.
Herald added a subscriber: cfe-commits.

A typical use case would be to allow custom attributes for pointer types. See 
examples/Attribute/Attribute.cpp for an example.

Unfortuantely, it is hard to provide meaningful test coverage for this change.  
The existing handleDeclAttribute() covered by lit tests for
attributes because multiple declaration attributes are marked 'SimpleHandler', 
which causes ClangAttrEmitter.cpp to generate a
handleDeclAttribute() handler for them.  However, all of the existing type 
attributes need custom semantic handling, so it is not possible to simply 
implement them with 'SimpleHandler'.

The modified Attribute.cpp example does at least demonstrate that it is 
possible to use the new API without any build errors, but this is all that it 
does.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114235

Files:
  clang/docs/ClangPlugins.rst
  clang/examples/Attribute/Attribute.cpp
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/Sema/SemaType.cpp

Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -27,6 +27,7 @@
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/DelayedDiagnostic.h"
 #include "clang/Sema/Lookup.h"
+#include "clang/Sema/ParsedAttr.h"
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/SemaInternal.h"
@@ -350,16 +351,6 @@
   toList.addAtEnd();
 }
 
-/// The location of a type attribute.
-enum TypeAttrLocation {
-  /// The attribute is in the decl-specifier-seq.
-  TAL_DeclSpec,
-  /// The attribute is part of a DeclaratorChunk.
-  TAL_DeclChunk,
-  /// The attribute is immediately after the declaration's name.
-  TAL_DeclName
-};
-
 static void processTypeAttrs(TypeProcessingState , QualType ,
  TypeAttrLocation TAL, ParsedAttributesView );
 
@@ -8141,14 +8132,34 @@
 // If this is an attribute we can handle, do so now,
 // otherwise, add it to the FnAttrs list for rechaining.
 switch (attr.getKind()) {
-default:
-  // A [[]] attribute on a declarator chunk must appertain to a type.
-  if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) {
-state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
-<< attr;
+default: {
+  Attr *outAttr = nullptr;
+  unsigned chunkIndex = 0;
+  if (TAL == TAL_DeclChunk) {
+chunkIndex = state.getCurrentChunkIndex();
+  }
+  switch (attr.getInfo().handleTypeAttribute(state.getSema(), type, TAL,
+ state.getDeclarator(),
+ chunkIndex, attr, )) {
+  case ParsedAttrInfo::AttributeApplied:
+assert(outAttr != nullptr);
+type = state.getAttributedType(outAttr, type, type);
 attr.setUsedAsTypeAttr();
+break;
+  case ParsedAttrInfo::AttributeNotApplied:
+// Do nothing.
+break;
+  case ParsedAttrInfo::NotHandled:
+// A [[]] attribute on a declarator chunk must appertain to a type.
+if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) {
+  state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
+  << attr;
+  attr.setUsedAsTypeAttr();
+}
+break;
   }
   break;
+}
 
 case ParsedAttr::UnknownAttribute:
   if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk)
Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -34,6 +34,7 @@
 
 class ASTContext;
 class Decl;
+class Declarator;
 class Expr;
 class IdentifierInfo;
 class LangOptions;
@@ -42,6 +43,16 @@
 class Stmt;
 class TargetInfo;
 
+/// The location of a type attribute.
+enum TypeAttrLocation {
+  /// The attribute is in the decl-specifier-seq.
+  TAL_DeclSpec,
+  /// The attribute is part of a DeclaratorChunk.
+  TAL_DeclChunk,
+  /// The attribute is immediately after the declaration's name.
+  TAL_DeclName
+};
+
 struct ParsedAttrInfo {
   /// Corresponds to the Kind enum.
   unsigned AttrKind : 16;
@@ -123,6 +134,19 @@
const ParsedAttr ) const {
 return NotHandled;
   }
+  /// If this ParsedAttrInfo knows how to handle this ParsedAttr applied to this
+  /// Type then do so and return either AttributeApplied if it was applied or
+  /// AttributeNotApplied if it wasn't. Otherwise return NotHandled.
+  /// If AttributeApplied is returned, *OutAttr should be set to point to a
+  /// corresponding Attr.
+  /// If TAL is TAL_DeclChunk, ChunkIndex contains the index of the chunk in
+  /// 

[PATCH] D113995: [clangd] Dex Trigrams: Improve query trigram generation

2021-11-19 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 388461.
kbobyrev added a comment.

Add improvements for identifier trigram generation and make query & id
generators consistent with each other.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113995

Files:
  clang-tools-extra/clangd/index/dex/Trigram.cpp
  clang-tools-extra/clangd/unittests/DexTests.cpp

Index: clang-tools-extra/clangd/unittests/DexTests.cpp
===
--- clang-tools-extra/clangd/unittests/DexTests.cpp
+++ clang-tools-extra/clangd/unittests/DexTests.cpp
@@ -386,30 +386,35 @@
   trigramsAre({"c", "cl", "cla", "lan", "ang", "ngd"}));
 
   EXPECT_THAT(identifierTrigramTokens("abc_def"),
-  trigramsAre({"a", "ab", "ad", "abc", "abd", "ade", "bcd", "bde",
-   "cde", "def"}));
+  trigramsAre({"a", "d", "ab", "ad", "de", "abc", "abd", "ade",
+   "bcd", "bde", "cde", "def"}));
 
   EXPECT_THAT(identifierTrigramTokens("a_b_c_d_e_"),
-  trigramsAre({"a", "a_", "ab", "abc", "bcd", "cde"}));
+  trigramsAre({"a", "b", "ab", "abc", "bcd", "cde"}));
 
   EXPECT_THAT(identifierTrigramTokens("unique_ptr"),
-  trigramsAre({"u", "un", "up", "uni", "unp", "upt", "niq", "nip",
-   "npt", "iqu", "iqp", "ipt", "que", "qup", "qpt",
-   "uep", "ept", "ptr"}));
+  trigramsAre({"u",   "p",   "un",  "up",  "pt",  "uni", "unp",
+   "upt", "niq", "nip", "npt", "iqu", "iqp", "ipt",
+   "que", "qup", "qpt", "uep", "ept", "ptr"}));
 
-  EXPECT_THAT(
-  identifierTrigramTokens("TUDecl"),
-  trigramsAre({"t", "tu", "td", "tud", "tde", "ude", "dec", "ecl"}));
+  EXPECT_THAT(identifierTrigramTokens("TUDecl"),
+  trigramsAre({"t", "d", "tu", "td", "de", "tud", "tde", "ude",
+   "dec", "ecl"}));
 
   EXPECT_THAT(identifierTrigramTokens("IsOK"),
-  trigramsAre({"i", "is", "io", "iso", "iok", "sok"}));
+  trigramsAre({"i", "o", "is", "ok", "io", "iso", "iok", "sok"}));
 
-  EXPECT_THAT(
-  identifierTrigramTokens("abc_defGhij__klm"),
-  trigramsAre({"a",   "ab",  "ad",  "abc", "abd", "ade", "adg", "bcd",
-   "bde", "bdg", "cde", "cdg", "def", "deg", "dgh", "dgk",
-   "efg", "egh", "egk", "fgh", "fgk", "ghi", "ghk", "gkl",
-   "hij", "hik", "hkl", "ijk", "ikl", "jkl", "klm"}));
+  EXPECT_THAT(identifierTrigramTokens("_pb"),
+  trigramsAre({"_", "_p", "p", "pb"}));
+  EXPECT_THAT(identifierTrigramTokens("__pb"),
+  trigramsAre({"_", "_p", "p", "pb"}));
+
+  EXPECT_THAT(identifierTrigramTokens("abc_defGhij__klm"),
+  trigramsAre({"a",   "d",   "ab",  "ad",  "de",  "abc", "abd",
+   "ade", "adg", "bcd", "bde", "bdg", "cde", "cdg",
+   "def", "deg", "dgh", "dgk", "efg", "egh", "egk",
+   "fgh", "fgk", "ghi", "ghk", "gkl", "hij", "hik",
+   "hkl", "ijk", "ikl", "jkl", "klm"}));
 }
 
 TEST(DexTrigrams, QueryTrigrams) {
@@ -419,8 +424,16 @@
 
   EXPECT_THAT(generateQueryTrigrams(""), trigramsAre({}));
   EXPECT_THAT(generateQueryTrigrams("_"), trigramsAre({"_"}));
-  EXPECT_THAT(generateQueryTrigrams("__"), trigramsAre({"__"}));
-  EXPECT_THAT(generateQueryTrigrams("___"), trigramsAre({}));
+  EXPECT_THAT(generateQueryTrigrams("__"), trigramsAre({"_"}));
+  EXPECT_THAT(generateQueryTrigrams("___"), trigramsAre({"_"}));
+
+  EXPECT_THAT(generateQueryTrigrams("m_"), trigramsAre({"m"}));
+
+  EXPECT_THAT(generateQueryTrigrams("p_b"), trigramsAre({"pb"}));
+  EXPECT_THAT(generateQueryTrigrams("pb_"), trigramsAre({"pb"}));
+  EXPECT_THAT(generateQueryTrigrams("_p"), trigramsAre({"_p"}));
+  EXPECT_THAT(generateQueryTrigrams("_pb_"), trigramsAre({"pb"}));
+  EXPECT_THAT(generateQueryTrigrams("__pb"), trigramsAre({"pb"}));
 
   EXPECT_THAT(generateQueryTrigrams("X86"), trigramsAre({"x86"}));
 
@@ -525,25 +538,45 @@
 }
 
 TEST(DexTest, ShortQuery) {
-  auto I = Dex::build(generateSymbols({"OneTwoThreeFour"}), RefSlab(),
+  auto I = Dex::build(generateSymbols({"_OneTwoFourSix"}), RefSlab(),
   RelationSlab());
   FuzzyFindRequest Req;
   Req.AnyScope = true;
   bool Incomplete;
 
-  EXPECT_THAT(match(*I, Req, ), ElementsAre("OneTwoThreeFour"));
+  EXPECT_THAT(match(*I, Req, ), ElementsAre("_OneTwoFourSix"));
   EXPECT_FALSE(Incomplete) << "Empty string is not a short query";
 
-  Req.Query = "t";
+  Req.Query = "o";
+  EXPECT_THAT(match(*I, Req, ), ElementsAre("_OneTwoFourSix"));
+  EXPECT_TRUE(Incomplete) << "Using first head as unigram";
+
+  Req.Query = "_o";
+  EXPECT_THAT(match(*I, Req, ), ElementsAre("_OneTwoFourSix"));
+  EXPECT_TRUE(Incomplete) << "Using 

[PATCH] D114234: [clang][dataflow] Add base types for building dataflow analyses

2021-11-19 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev created this revision.
sgatev added reviewers: ymandel, NoQ, xazax.hun, gribozavr.
Herald added subscribers: rnkovacs, mgorny.
sgatev requested review of this revision.
Herald added a project: clang.

This is part of the implementation of the dataflow analysis framework.
See "[RFC] A dataflow analysis framework for Clang AST" on cfe-dev.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114234

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Environment.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/DataflowAnalysis.cpp
@@ -0,0 +1,33 @@
+//===- DataflowAnalysis.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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#include 
+
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Environment.h"
+#include "llvm/ADT/Optional.h"
+
+namespace clang {
+namespace dataflow {
+
+std::vector>
+runDataflowAnalysis(const CFG , DataflowAnalysisDynamic ,
+const Environment ) {
+  // FIXME: Implement work list-based algorithm to compute the fixed
+  // point of `Analysis::transform` for every basic block in `Cfg`.
+  return {};
+}
+
+} // namespace dataflow
+} // namespace clang
Index: clang/lib/Analysis/FlowSensitive/CMakeLists.txt
===
--- /dev/null
+++ clang/lib/Analysis/FlowSensitive/CMakeLists.txt
@@ -0,0 +1,7 @@
+add_clang_library(clangAnalysisFlowSensitive
+  DataflowAnalysis.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAST
+  )
Index: clang/lib/Analysis/CMakeLists.txt
===
--- clang/lib/Analysis/CMakeLists.txt
+++ clang/lib/Analysis/CMakeLists.txt
@@ -44,3 +44,4 @@
   )
 
 add_subdirectory(plugins)
+add_subdirectory(FlowSensitive)
Index: clang/include/clang/Analysis/FlowSensitive/Environment.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/Environment.h
@@ -0,0 +1,27 @@
+//===-- Environment.h ---*- 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
+//
+//===--===//
+//
+//  This file defines an Environment class that is used by dataflow analyses
+//  that run over Control-Flow Graphs (CFGs) to keep track of the state of the
+//  program at given program points.
+//
+//===--===//
+
+#ifndef LOCAL_GOOGLE_HOME_SGATEV_LLVM_PROJECT_DATAFLOW_CLANG_INCLUDE_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H_
+#define LOCAL_GOOGLE_HOME_SGATEV_LLVM_PROJECT_DATAFLOW_CLANG_INCLUDE_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H_
+
+namespace clang {
+namespace dataflow {
+
+// Holds the state of the program (store and heap) at a given program point.
+class Environment {};
+
+} // namespace dataflow
+} // namespace clang
+
+#endif // LOCAL_GOOGLE_HOME_SGATEV_LLVM_PROJECT_DATAFLOW_CLANG_INCLUDE_CLANG_ANALYSIS_FLOWSENSITIVE_ENVIRONMENT_H_
Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- /dev/null
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -0,0 +1,162 @@
+//===- DataflowAnalysis.h ---*- 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
+//
+//===--===//
+//
+//  This file defines base types for building dataflow analyses that run over
+//  Control-Flow Graphs (CFGs).
+//
+//===--===//
+
+#ifndef 

[PATCH] D107450: [clang-tidy] Fix wrong FixIt in performance-move-const-arg

2021-11-19 Thread gehry via Phabricator via cfe-commits
Sockke added a comment.

Kindly ping. @whisperity


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

https://reviews.llvm.org/D107450

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


[PATCH] D113401: [analyzer][docs] Ellaborate the docs of cplusplus.StringChecker

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbf55b9f0d0e9: [analyzer][docs] Ellaborate the docs of 
cplusplus.StringChecker (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113401

Files:
  clang/docs/analyzer/checkers.rst


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -319,13 +319,22 @@
 "
 Checks std::string operations.
 
+Checks if the cstring pointer from which the ``std::string`` object is
+constructed is ``NULL`` or not.
+If the checker cannot reason about the nullness of the pointer it will assume
+that it was non-null to satisfy the precondition of the constructor.
+
+This checker is capable of checking the `SEI CERT C++ coding rule STR51-CPP.
+Do not attempt to create a std::string from a null pointer
+`__.
+
 .. code-block:: cpp
 
  #include 
 
  void f(const char *p) {
if (!p) {
- std::string msg(p); // warn: p is NULL
+ std::string msg(p); // warn: The parameter must not be null
}
  }
 


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -319,13 +319,22 @@
 "
 Checks std::string operations.
 
+Checks if the cstring pointer from which the ``std::string`` object is
+constructed is ``NULL`` or not.
+If the checker cannot reason about the nullness of the pointer it will assume
+that it was non-null to satisfy the precondition of the constructor.
+
+This checker is capable of checking the `SEI CERT C++ coding rule STR51-CPP.
+Do not attempt to create a std::string from a null pointer
+`__.
+
 .. code-block:: cpp
 
  #include 
 
  void f(const char *p) {
if (!p) {
- std::string msg(p); // warn: p is NULL
+ std::string msg(p); // warn: The parameter must not be null
}
  }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bf55b9f - [analyzer][docs] Ellaborate the docs of cplusplus.StringChecker

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T11:59:46+01:00
New Revision: bf55b9f0d0e938def5d24629325b271cbfc3b04a

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

LOG: [analyzer][docs] Ellaborate the docs of cplusplus.StringChecker

Let's describe accurately what the users can expect from the checker in
a direct way.
Also, add an example warning message.

Reviewed By: martong, Szelethus

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

Added: 


Modified: 
clang/docs/analyzer/checkers.rst

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index 80cf3bc7c313..df62fb0643f8 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -319,13 +319,22 @@ cplusplus.StringChecker (C++)
 "
 Checks std::string operations.
 
+Checks if the cstring pointer from which the ``std::string`` object is
+constructed is ``NULL`` or not.
+If the checker cannot reason about the nullness of the pointer it will assume
+that it was non-null to satisfy the precondition of the constructor.
+
+This checker is capable of checking the `SEI CERT C++ coding rule STR51-CPP.
+Do not attempt to create a std::string from a null pointer
+`__.
+
 .. code-block:: cpp
 
  #include 
 
  void f(const char *p) {
if (!p) {
- std::string msg(p); // warn: p is NULL
+ std::string msg(p); // warn: The parameter must not be null
}
  }
 



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


[PATCH] D46081: [analyzer] Expand conversion check to check more expressions for overflow and underflow

2021-11-19 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/ConversionChecker.cpp:102
 }
-  } else if (isa(Parent)) {
+  } else if (isa(Parent) || isa(Parent)) {
+if (!Cast->IgnoreParenImpCasts()->isEvaluatable(C.getASTContext())) {




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

https://reviews.llvm.org/D46081

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


[PATCH] D46081: [analyzer] Expand conversion check to check more expressions for overflow and underflow

2021-11-19 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

@whisperity Thank you for pinging! This seems still feasible. Besides, this is 
valuable for us, as it could pass some SEI CERT test cases, notably from INT31 
-C.


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

https://reviews.llvm.org/D46081

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


[PATCH] D113668: [ASTImporter][NFC] Dump decl name at assertion violation

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf3753ad77450: [ASTImporter][NFC] Dump decl name at assertion 
violation (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113668

Files:
  clang/lib/AST/ASTImporterLookupTable.cpp


Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "llvm/Support/FormatVariadic.h"
 
 namespace clang {
 
@@ -93,10 +94,19 @@
 }
 
 void ASTImporterLookupTable::remove(DeclContext *DC, NamedDecl *ND) {
-  DeclList  = LookupTable[DC][ND->getDeclName()];
+  const DeclarationName Name = ND->getDeclName();
+  DeclList  = LookupTable[DC][Name];
   bool EraseResult = Decls.remove(ND);
   (void)EraseResult;
-  assert(EraseResult == true && "Trying to remove not contained Decl");
+#ifndef NDEBUG
+  if (!EraseResult) {
+std::string Message =
+llvm::formatv("Trying to remove not contained Decl '{0}' of type {1}",
+  Name.getAsString(), DC->getDeclKindName())
+.str();
+llvm_unreachable(Message.c_str());
+  }
+#endif
 }
 
 void ASTImporterLookupTable::add(NamedDecl *ND) {


Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "llvm/Support/FormatVariadic.h"
 
 namespace clang {
 
@@ -93,10 +94,19 @@
 }
 
 void ASTImporterLookupTable::remove(DeclContext *DC, NamedDecl *ND) {
-  DeclList  = LookupTable[DC][ND->getDeclName()];
+  const DeclarationName Name = ND->getDeclName();
+  DeclList  = LookupTable[DC][Name];
   bool EraseResult = Decls.remove(ND);
   (void)EraseResult;
-  assert(EraseResult == true && "Trying to remove not contained Decl");
+#ifndef NDEBUG
+  if (!EraseResult) {
+std::string Message =
+llvm::formatv("Trying to remove not contained Decl '{0}' of type {1}",
+  Name.getAsString(), DC->getDeclKindName())
+.str();
+llvm_unreachable(Message.c_str());
+  }
+#endif
 }
 
 void ASTImporterLookupTable::add(NamedDecl *ND) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f3753ad - [ASTImporter][NFC] Dump decl name at assertion violation

2021-11-19 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-11-19T11:31:01+01:00
New Revision: f3753ad774506804ef5df065b48268712bdaa554

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

LOG: [ASTImporter][NFC] Dump decl name at assertion violation

Sometimes it would be useful to see which Decl kind caused some issue,
along with the name of the concrete instance of the Decl in the source
code.

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/AST/ASTImporterLookupTable.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporterLookupTable.cpp 
b/clang/lib/AST/ASTImporterLookupTable.cpp
index bf772c20d32ee..ef42561c6f941 100644
--- a/clang/lib/AST/ASTImporterLookupTable.cpp
+++ b/clang/lib/AST/ASTImporterLookupTable.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "llvm/Support/FormatVariadic.h"
 
 namespace clang {
 
@@ -93,10 +94,19 @@ void ASTImporterLookupTable::add(DeclContext *DC, NamedDecl 
*ND) {
 }
 
 void ASTImporterLookupTable::remove(DeclContext *DC, NamedDecl *ND) {
-  DeclList  = LookupTable[DC][ND->getDeclName()];
+  const DeclarationName Name = ND->getDeclName();
+  DeclList  = LookupTable[DC][Name];
   bool EraseResult = Decls.remove(ND);
   (void)EraseResult;
-  assert(EraseResult == true && "Trying to remove not contained Decl");
+#ifndef NDEBUG
+  if (!EraseResult) {
+std::string Message =
+llvm::formatv("Trying to remove not contained Decl '{0}' of type {1}",
+  Name.getAsString(), DC->getDeclKindName())
+.str();
+llvm_unreachable(Message.c_str());
+  }
+#endif
 }
 
 void ASTImporterLookupTable::add(NamedDecl *ND) {



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


[PATCH] D113558: [clang-tidy] Fix cppcoreguidelines-virtual-base-class-destructor in macros

2021-11-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

ping




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-virtual-class-destructor.cpp:288
+protected:
+  virtual CONCAT(~Foo, Bar2()); // no-fixit
+};

whisperity wrote:
> whisperity wrote:
> > It is strange that there is no fix-it here even though the keyword appears 
> > as a single token ...[1]
> Maybe a FIXME could be added for this case, just to register that we indeed 
> realised something is //strange// here, but I'm not convinced neither for nor 
> against. The purpose of the patch is to get rid of the crash, after all.
Definitely deserves a FIXME. Yes.


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

https://reviews.llvm.org/D113558

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


[PATCH] D113118: [clang][AST] Check context of record in structural equivalence.

2021-11-19 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.

Thanks @balazske for updating the tests, I think this addresses @shafik 's 
questions. LGTM! Ping @shafik


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113118

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


[PATCH] D114006: [analyzer][NFC] Enable access to CodeGenOptions from analyzer's instances

2021-11-19 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.

LGTM!


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

https://reviews.llvm.org/D114006

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


[PATCH] D114229: [clang][driver] Always add LTO options when using GNU toolchain

2021-11-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: MaskRay, fhahn, tejohnson.
Herald added subscribers: ormris, steven_wu, hiraditya, inglorion.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is what the GCC driver does as well.

This way, ld.bfd can properly handle inputs from a clang LTO build,
without `-flto` being specified at link time explicitly.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D114229

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/test/Driver/lto.c


Index: clang/test/Driver/lto.c
===
--- clang/test/Driver/lto.c
+++ clang/test/Driver/lto.c
@@ -104,4 +104,19 @@
 // FLTO-THIN-NOT: "-flto"
 // FLTO-THIN: -flto=thin
 // FLTO-THIN-NOT: "-flto"
-// FLTO-THIN-NOT: -flto=full
\ No newline at end of file
+// FLTO-THIN-NOT: -flto=full
+
+// When ld.bfd is being used and no lto option has been specified, the driver
+// should pass the lto plugin options to the linker anyway, so LTO
+// input files can be linked.
+// RUN: %clang -target x86_64-unknown-linux -fuse-ld=bfd -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=FLTO-NOT-SPECIFIED-BFD %s
+//
+// FLTO-NOT-SPECIFIED-BFD: "-plugin" "{{.*}}{{[/\\]}}LLVMgold.{{dll|dylib|so}}"
+//
+//
+// But not when LLD is used:
+// RUN: %clang -target x86_64-unknown-linux -fuse-ld=lld -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=FLTO-NOT-SPECIFIED-LLD %s
+//
+// FLTO-NOT-SPECIFIED-LLD-NOT: "-plugin" 
"{{.*}}{{[/\\]}}LLVMgold.{{dll|dylib|so}}"
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -546,7 +546,14 @@
 
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
-  if (D.isUsingLTO()) {
+  // If no LTO option has been specified, add the LTO options anyway.
+  // This has the upside of making the linking automatically work with
+  // LLVM bitcode files created from an LTO compile. If the input is not
+  // an LTO file, the LTO plugin will not be invoked.
+  // This is the same behavior the GCC driver uses.
+  if ((!Args.hasArg(options::OPT_flto_EQ) &&
+   !Args.hasArg(options::OPT_fno_lto)) ||
+  D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
 addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
   D.getLTOMode() == LTOK_Thin);


Index: clang/test/Driver/lto.c
===
--- clang/test/Driver/lto.c
+++ clang/test/Driver/lto.c
@@ -104,4 +104,19 @@
 // FLTO-THIN-NOT: "-flto"
 // FLTO-THIN: -flto=thin
 // FLTO-THIN-NOT: "-flto"
-// FLTO-THIN-NOT: -flto=full
\ No newline at end of file
+// FLTO-THIN-NOT: -flto=full
+
+// When ld.bfd is being used and no lto option has been specified, the driver
+// should pass the lto plugin options to the linker anyway, so LTO
+// input files can be linked.
+// RUN: %clang -target x86_64-unknown-linux -fuse-ld=bfd -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=FLTO-NOT-SPECIFIED-BFD %s
+//
+// FLTO-NOT-SPECIFIED-BFD: "-plugin" "{{.*}}{{[/\\]}}LLVMgold.{{dll|dylib|so}}"
+//
+//
+// But not when LLD is used:
+// RUN: %clang -target x86_64-unknown-linux -fuse-ld=lld -### %s 2>&1 | \
+// RUN: FileCheck --check-prefix=FLTO-NOT-SPECIFIED-LLD %s
+//
+// FLTO-NOT-SPECIFIED-LLD-NOT: "-plugin" "{{.*}}{{[/\\]}}LLVMgold.{{dll|dylib|so}}"
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -546,7 +546,14 @@
 
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
-  if (D.isUsingLTO()) {
+  // If no LTO option has been specified, add the LTO options anyway.
+  // This has the upside of making the linking automatically work with
+  // LLVM bitcode files created from an LTO compile. If the input is not
+  // an LTO file, the LTO plugin will not be invoked.
+  // This is the same behavior the GCC driver uses.
+  if ((!Args.hasArg(options::OPT_flto_EQ) &&
+   !Args.hasArg(options::OPT_fno_lto)) ||
+  D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
 addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
   D.getLTOMode() == LTOK_Thin);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >